Python石头剪刀布游戏问题咨询及代码优化建议请求
石头剪刀布游戏问题修复与优化方案
问题1:非法输入导致程序终止的修复
原代码遇到非法输入时直接用return退出函数,导致程序终止。正确做法是打印错误提示,不消耗对局次数,让用户重新输入:
# 替换原输入判断逻辑 chosen = input("Make your choice: ").lower() # 统一转小写,简化大小写判断 valid_choices = {"rock", "paper", "scissors"} if chosen not in valid_choices: print("Invalid Entry") continue # 跳过本轮剩余流程,回到输入步骤 element = chosen
问题2:全局胜负结果未打印的修复
原函数最后返回了胜负结果,但调用game()时未打印返回值。直接在函数内打印结果即可:
# 替换原函数末尾的return逻辑 print(f"Your Wins: {win_count}") print(f"Computer Wins: {lose_count}") if win_count > lose_count: print("Congrats, you won the game!") elif win_count < lose_count: print("Sorry, you lost the game") else: print("It's a tie game!") # 补充全局平局的情况
完整修复优化后的代码
import random def game(): win_count = 0 lose_count = 0 tries = 0 # 将电脑选项移到循环外,避免重复创建列表 computer_choices = ["scissors", "paper", "rock"] while tries < 5: chosen = input("Make your choice: ").lower() valid_choices = {"rock", "paper", "scissors"} if chosen not in valid_choices: print("Invalid Entry") continue element = chosen computer_choice = random.choice(computer_choices) # 用字典映射获胜规则,替代大量elif判断,逻辑更清晰 win_combinations = { ("scissors", "paper"), ("paper", "rock"), ("rock", "scissors") } if element == computer_choice: print(f"Computer chose {computer_choice}, you chose {element}, that's a draw, try again") # 平局不消耗对局次数,重新进行本轮 continue elif (element, computer_choice) in win_combinations: print(f"Computer chose {computer_choice}, you chose {element}, you win!") win_count += 1 tries += 1 else: print(f"Computer chose {computer_choice}, you chose {element}, you lose!") lose_count += 1 tries += 1 print(f"Your Wins: {win_count}") print(f"Computer Wins: {lose_count}") if win_count > lose_count: print("Congrats, you won the game!") elif win_count < lose_count: print("Sorry, you lost the game") else: print("It's a tie game!") game()
额外代码优化建议
- 统一输入处理:用
lower()将输入转为小写,无需分别判断大小写形式,简化代码。 - 规则字典化:用集合存储玩家获胜的组合,替代冗余的elif判断,逻辑更易维护。
- 优化对局次数:原代码平局消耗对局次数,改为平局不增加
tries,确保完成5轮有效胜负对局。 - 修正变量名:原代码中
loose_count拼写错误,改为lose_count(loose意为“松散的”,lose才是“失败”的正确拼写)。 - 减少重复对象创建:将
computer_choices移到循环外部,避免每次循环重新创建列表。 - 使用格式化字符串:用f-string替代字符串拼接,代码更简洁易读。
- 补充全局平局逻辑:原代码未处理全局平局的情况,新增分支让结果更完整。
内容的提问来源于stack exchange,提问作者salmon_fish
相关产品推荐
相关产品推荐

