Python石头剪刀布游戏实现三局两胜积分系统开发求助
石头剪刀布三局两胜功能修改方案
核心问题原因
你当前代码无法累计分数的核心原因是:player_score和comp_score两个分数变量定义在了游戏循环内部,每开启新一局对局都会被重置为0,自然无法实现跨对局的分数累计。
具体修改点
- 将分数初始化代码移到最外层游戏循环的外部,避免每局重置
- 单局胜负判定时,将固定赋值
=1改为累加赋值+=1,实现分数累计 - 每局结束后增加最终胜负判定:任意一方分数达到2分就触发最终胜利提示,结束当前三局两胜对局
- 保留原有的手动确认重开逻辑,玩家输入
yes时会重置分数,开启新一轮三局两胜对局
修改后完整代码
# ROCK PAPER SCISSOR import random # 分数初始化移到循环外,实现跨局累计 player_score = 0 comp_score = 0 rpc = ["rock","paper","scissor"] while True: player = None # 玩家输入校验 while player not in rpc: player = input("rock, paper, or scissor: ").lower() comp = random.choice(rpc) print("Rock, Paper, or Scissor?: ") # 胜负判定 if player == comp: print("player: ", player) print("computer: ", comp) print("TIE!") elif player == "rock": if comp == "paper": print("player: ", player) print("computer: ", comp) print("YOU LOSE!") comp_score += 1 if comp == "scissor": print("player: ", player) print("computer: ", comp) print("YOU WIN!") player_score += 1 elif player == "scissor": if comp == "rock": print("player: ", player) print("computer: ", comp) print("YOU LOSE!") comp_score += 1 if comp == "paper": print("player: ", player) print("computer: ", comp) print("YOU WIN!") player_score += 1 elif player == "paper": if comp == "scissor": print("player: ", player) print("computer: ", comp) print("YOU LOSE!") comp_score += 1 if comp == "rock": print("player: ", player) print("computer: ", comp) print("YOU WIN!") player_score += 1 # 打印当前分数 print("your score:", player_score) print("computers score: ", comp_score) # 三局两胜判定 if player_score >= 2: print("🎉 恭喜你获得最终胜利!") # 重置分数准备下一轮 player_score = 0 comp_score = 0 elif comp_score >=2: print("😢 电脑获得最终胜利,你输了") # 重置分数准备下一轮 player_score = 0 comp_score = 0 # 原有是否继续逻辑保留 player_choice = input("keep playing?: yes/no").lower() if player_choice == "no": break print("Goodbye")
功能说明
修改后代码运行逻辑:
- 每局结束自动累计双方分数
- 任意一方率先拿到2分就会触发最终胜负提示,同时重置分数
- 玩家可以选择输入
yes继续新一轮三局两胜,输入no退出游戏
内容的提问来源于stack exchange,提问作者Kyle Young
相关产品推荐
相关产品推荐

