Python石头剪刀布游戏计分上限失效问题求助
石头剪刀布游戏计分终止问题修复
你的问题出在continue语句的使用上:每次玩家或电脑得分后,你都用continue直接跳回循环开头,导致循环末尾的终止条件判断代码永远不会被执行。哪怕分数已经到了5,程序也会跳过检查,直接让玩家继续输入。
修复方案
把终止条件的检查移到每次计分操作之后,确保分数达标时立刻终止游戏。以下是修改后的完整代码:
# 石头剪刀布游戏 import random choices = ("Rock", "Paper", "Scissors") player_score = 0 computer_score = 0 playing = False score_limit = 5 play = input("要不要玩?(y/n): ") if play in ["y", "yes"]: playing = True elif play in ["n", "no"]: playing = False else: raise Exception("输入无效") while playing: player = input("请输入你的选择:") computer = random.choice(choices) if player == "Rock": if computer == "Paper": print(f"电脑选择:{computer}") computer_score += 1 print(f"你的分数:{player_score}") print(f"电脑分数:{computer_score}") if computer_score == score_limit: print("游戏结束!电脑获胜!") playing = False break elif computer == "Scissors": print(f"电脑选择:{computer}") player_score += 1 print(f"你的分数:{player_score}") print(f"电脑分数:{computer_score}") if player_score == score_limit: print("游戏结束!你获胜!") playing = False break else: print(f"电脑选择:{computer}") print(f"你的分数:{player_score}") print(f"电脑分数:{computer_score}") elif player == "Paper": if computer == "Rock": print(f"电脑选择:{computer}") player_score += 1 print(f"你的分数:{player_score}") print(f"电脑分数:{computer_score}") if player_score == score_limit: print("游戏结束!你获胜!") playing = False break elif computer == "Scissors": print(f"电脑选择:{computer}") computer_score += 1 print(f"你的分数:{player_score}") print(f"电脑分数:{computer_score}") if computer_score == score_limit: print("游戏结束!电脑获胜!") playing = False break else: print(f"电脑选择:{computer}") print(f"你的分数:{player_score}") print(f"电脑分数:{computer_score}") elif player == "Scissors": if computer == "Rock": print(f"电脑选择:{computer}") computer_score += 1 print(f"你的分数:{player_score}") print(f"电脑分数:{computer_score}") if computer_score == score_limit: print("游戏结束!电脑获胜!") playing = False break elif computer == "Paper": print(f"电脑选择:{computer}") player_score += 1 print(f"你的分数:{player_score}") print(f"电脑分数:{computer_score}") if player_score == score_limit: print("游戏结束!你获胜!") playing = False break else: print(f"电脑选择:{computer}") print(f"你的分数:{player_score}") print(f"电脑分数:{computer_score}") elif player not in choices: raise Exception("输入无效,请输入Rock、Paper或Scissors")
修复逻辑说明
- 去掉了原来所有的
continue语句,避免跳过后续的终止检查 - 在每次玩家或电脑得分后,立即判断分数是否达到上限
score_limit - 一旦分数达标,打印获胜信息,将
playing设为False并break终止循环
内容的提问来源于stack exchange,提问作者DR Cherry Bomb
相关产品推荐
相关产品推荐

