简易石头剪刀布Python游戏重复运行时结果不显示问题求助
解决石头剪刀布游戏二次游玩无输出的问题
问题根源
你第二次输入选择后没有输出结果,核心原因是:第一次游戏通过print(play())输出了返回值,但在script()函数中选择"yes"后,仅调用了play()却没有打印它的返回结果。另外原代码的script()还存在逻辑漏洞,比如restart == True永远不会触发(input()返回字符串,不会等于布尔值),且没有循环机制,导致第二次游玩后无法继续重复流程。
修改后的完整代码
import random def play(): user = input("What's your choice? 'r' for rock, 'p' for paper, 's' for scissors\n") computer = random.choice(['r', 'p', 's']) if user == computer: return "It's a tie!" if is_win(user, computer): return "You won!" else: return "You lost! Better luck next time!" def is_win(player, opponent): # 直接返回胜负判断表达式,更简洁 return (player == 'r' and opponent == 's') or \ (player == 's' and opponent == 'p') or \ (player == 'p' and opponent == 'r') def script(): while True: restart = input("Would you like to play again? (yes/no)\n").lower() if restart in ["yes", "y"]: # 关键修改:打印play()的返回结果 print(play()) elif restart in ["no", "n"]: print("Thanks for playing!") break else: print("Invalid input, please enter 'yes' or 'no'") # 启动第一次游戏 print(play()) # 进入循环询问是否继续游玩 script()
关键修改点
- 打印返回结果:在
script()的"yes"分支中,将play()改为print(play()),确保二次游玩的胜负结果能正常输出。 - 循环持续询问:用
while True包裹询问逻辑,让玩家可以多次重复游玩,直到选择退出。 - 优化输入处理:将输入转为小写,支持"yes"/"y"、"no"/"n"等多种输入,并添加无效输入的提示。
- 简化代码逻辑:移除了未使用的
options列表,简化is_win函数的返回写法,让代码更简洁易读。
内容的提问来源于stack exchange,提问作者Will Childress
相关产品推荐
相关产品推荐

