如何优化带有计分器的石头剪刀布Python代码?
石头剪刀布代码优化方案
优化后的代码
import random # 定义胜负映射:玩家选择为键,对应的击败目标为值 WINNING_MAPPING = {'p': 'r', 's': 'p', 'r': 's'} total_games = 3 user_score = 0 computer_score = 0 for remaining_games in range(total_games, 0, -1): print(f"剩余游戏次数: {remaining_games}") user_choice = input("请输入选择(r=石头,p=布,s=剪刀): ").lower() # 输入合法性校验 while user_choice not in WINNING_MAPPING: user_choice = input("输入无效,请重新输入(r/p/s): ").lower() computer_choice = random.choice(list(WINNING_MAPPING.keys())) # 判断单局胜负 if WINNING_MAPPING[user_choice] == computer_choice: user_score += 1 elif user_choice != computer_choice: computer_score += 1 print(f"你({user_score}分): {user_choice} | 电脑({computer_score}分): {computer_choice}\n") # 最终结果判定 if user_score > computer_score: print("你赢了!") elif computer_score > user_score: print("你输了!") else: print("平局!")
优化细节说明
- 命名规范统一:改用PEP8风格的下划线命名(如
user_score替代userScore),代码可读性更强。 - 胜负逻辑简化:用字典
WINNING_MAPPING存储胜负关系,替代原代码中冗长的多条件判断,逻辑更直观且便于后续扩展。 - 循环逻辑优化:用
for循环直接控制游戏次数,无需手动维护剩余次数变量,减少出错概率。 - 冗余代码移除:删除平局时无意义的
+=0操作,精简代码结构。 - 输入健壮性提升:增加输入合法性校验,避免无效输入干扰游戏流程。
- 输出格式优化:调整结果展示的分隔符,让比分和选择的对应关系更清晰。
内容的提问来源于stack exchange,提问作者Right.Orphée
相关产品推荐
相关产品推荐

