如何修复石头剪刀布Python程序中while循环的重启失效问题?
问题原因及修复方案
核心问题
- 循环变量被覆盖:你用
player同时存储布尔值(循环条件)和玩家输入的字符串,第一次循环后player变成了输入内容(比如'Rock'),下一次循环判断player == True时,字符串和布尔值不相等,循环直接终止。 - 电脑选择未重置:电脑的选择
computer定义在循环外,重启游戏时电脑会重复使用之前的选择,不符合游戏逻辑。 - 重启判断不严谨:当前只判断输入是否为
'y',但用户输入'yes'时会被判定为不继续,导致程序终止。
修复后的完整代码
from random import randint # 选项列表 choices = ['Rock', 'Paper', 'Scissors'] # 用独立变量控制循环 playing = True while playing: # 每次游戏重新生成电脑选择 computer = choices[randint(0, 2)] player_input = input('Rock, Paper, or Scissors? ') if player_input == computer: print('Tie!') elif player_input == 'Rock': if computer == 'Paper': print('You lose!', computer, 'covers', player_input) else: print('You win!', player_input, 'smashes', computer) elif player_input == 'Paper': if computer == 'Scissors': print('You lose', computer, 'cuts', player_input) else: print('You win!', player_input, 'covers', computer) elif player_input == 'Scissors': if computer == 'Rock': print('You lose!', computer, 'smashes', player_input) else: print('You win!', player_input, 'cuts', computer) else: print('Not a valid answer. Please try again.') play_again = input("Play again? (y/n): ") # 支持y/yes两种输入,不区分大小写 if play_again.lower() not in ['y', 'yes']: playing = False
关键修改点
- 新增
playing变量专门控制循环,避免和玩家输入变量冲突。 - 将
computer的生成代码移到while循环内部,每次游戏电脑重新随机选择。 - 修改重启判断逻辑,支持
y或yes的输入,覆盖用户的输入习惯。
内容的提问来源于stack exchange,提问作者len
相关产品推荐
相关产品推荐

