Python石头剪刀布游戏while循环无法正常终止问题求助
问题原因及修复方案
1. 循环无法终止的核心原因
你仅在程序初始化时给game变量赋值了一次game = game_round != rounds,后续每次game_round更新后,都没有重新计算game的值,只要你输入的轮数不为0,game就永远等于初始的True,循环自然会无限执行。
2. 其他隐藏bug
- 未导入
random模块,直接调用random.choice会直接报错 - 电脑获胜的判断逻辑写错:
(opponent == 's' and opponent == 'p')永远不成立,应该改为(opponent == 's' and player == 'p') user_win统计放在了循环内部,每次轮次都会重置为0,无法累计用户总胜场- 用多个独立
if做胜负判断存在重复计数的漏洞,应该用if-elif-else结构替代 - 拼写错误:
loose应为lose - 最终分数打印的判断逻辑永远触发不了,因为你从未更新
game变量
修复后的完整代码
import random print('石头剪刀布!\n输入"r"代表石头,"p"代表布,"s"代表剪刀\n') rounds = int(input('你想玩几轮?: ')) game_round = 0 user_win = 0 # 胜场统计放在循环外初始化 while game_round < rounds: # 直接判断轮数,不用额外的game变量更清晰 user = input('\n请出拳(r/p/s): ').lower() computer = random.choice(['r', 'p', 's']) print(f'电脑出拳: {computer}\n') player = user opponent = computer # 规则:石头赢剪刀,剪刀赢布,布赢石头 player_win = (player == 'r' and opponent == 's') or (player == 's' and opponent == 'p') or (player == 'p' and opponent == 'r') # 修复电脑获胜的判断逻辑 computer_w = (opponent == 'r' and player == 's') or (opponent == 's' and player == 'p') or (opponent == 'p' and player == 'r') if user == computer: print('平局!') elif player_win: user_win += 1 print('你赢了!') elif computer_w: print('你输了!') # 每轮结束统一更新轮次,避免重复计数 game_round += 1 # 循环结束后直接打印分数 print(f'最终比分 {user_win}/{rounds}')
内容的提问来源于stack exchange,提问作者ASTRONOMICAL
相关产品推荐
相关产品推荐

