!/usr/bin/env python3

Python版本及模块导入

import random
import time

选项列表、初始化分数和其他变量

play_choices = ["rock", "paper", "scissors"]
player_score = 0
cpu_score = 0
player_choice = ""
p_choice = ""
restart = ""
r = ""

播放者开始游戏函数

def player_start():
"""
获取播放者的游戏选择
"""
global p_choice

# 进入循环以获得游戏选择
while True:
    # 获取玩家的选择并将其转换成小写
    player_choice = input("请输入rock、paper或scissors:")
    p_choice = player_choice.lower()

    # 根据选择返回相应的操作
    if p_choice == "rock":
        break
    elif p_choice == "paper":
        break
    elif p_choice == "scissors":
        break
    else:
        print("您的选择无效。请再试一次。")
        continue

return p_choice

运行游戏的函数

def main_game():
"""
运行游戏
"""
global player_score
global cpu_score

# 进入循环直到玩家或CPU得分达到5分
while player_score < 5 or cpu_score < 5:
    # cpu随机生成选择
    cpu_choice = random.choice(play_choices)

    # 玩家生成选择
    p_choice = player_start()

    # 呈现游戏结果
    print(f"玩家选择:{p_choice},CPU选择:{cpu_choice}。")

    # 根据玩家和CPU的选择决定游戏结果
    if p_choice == cpu_choice:
        print("游戏结束平手!")
        time.sleep(1)
    elif p_choice == "rock" and cpu_choice == "scissors":
        print("石头击败剪刀,玩家获胜!")
        player_score += 1
        time.sleep(1)
    elif p_choice == "scissors" and cpu_choice == "rock":
        print("石头击败剪刀,CPU获胜!")
        cpu_score += 1
        time.sleep(1)
    elif p_choice == "rock" and cpu_choice == "paper":
        print("纸张击败石头,CPU获胜!")
        cpu_score += 1
        time.sleep(1)
    elif p_choice == "paper" and cpu_choice == "rock":
        print("纸张击败石头,玩家获胜!")
        player_score += 1
        time.sleep(1)
    elif p_choice == "paper" and cpu_choice == "scissors":
        print("剪刀击败纸张,CPU获胜!")
        cpu_score += 1
        time.sleep(1)
    elif p_choice == "scissors" and cpu_choice == "paper":
        print("剪刀击败纸张,玩家获胜!")
        player_score += 1
        time.sleep(1)

return player_score, cpu_score

输出游戏结果的函数

def final_score():
"""
输出游戏结果
"""
# 玩家和CPU的得分
a, b = main_game()

# 根据分数决定游戏结果
if a > b:
    print("玩家获胜!")
elif a == b:
    print("游戏结束平手!")
else:
    print("CPU获胜!")

运行游戏

while r != "no":
# 输出游戏结果
final_score()

# 等待玩家输入
time.sleep(1)
while r != "no":
    # 询问玩家是否继续游戏
    restart = input("是否继续游戏?(yes/no)")
    r = restart.lower()

    # 根据玩家输入决定是否继续游戏
    if r == "yes":
        print("重新启动...")
        time.sleep(1)
        break
    elif r == "no":
        print("game over!")
        time.sleep(1)
        break
    else:
        print("无效输入。")
        time.sleep(1)