You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python新手编写石头剪刀布游戏代码过度复杂,求简化方案

代码优化方案

原代码存在的核心问题

  • 逻辑运算符使用错误:user_choice == 'Rock' or 'rock'这类写法永远为True,非空字符串在Python中布尔值为True,你实际想表达的是user_choice == 'Rock' or user_choice == 'rock',但这种写法本身就非常冗余
  • 大小写判断逻辑重复,不需要单独适配每一种大小写格式
  • 胜负判定分支写的过于零散,复用性差
  • 循环逻辑无意义,你写了while循环但每个分支都加了break,实际只会执行一次

简化实现方案

1. 统一输入格式消除大小写判断

直接将用户输入统一处理为首字母大写的格式,一行代码就能适配所有大小写输入:
user_choice = input("(What would you like to play?...)").strip().capitalize()

2. 用字典映射胜负规则

把胜负关系存在字典里,不需要写多分支判断胜负:
win_rules = {'Rock': 'Scissors', 'Scissors': 'Paper', 'Paper': 'Rock'}

3. 简化输入校验

直接判断处理后的用户输入是否在可选选项列表中即可

4. 优化循环逻辑

保留循环可以实现输错重输、平局重玩的效果,体验更合理

简化后的完整可运行代码

import random

print("Rock, Paper, Scissors, Shoot!")
options = ['Rock', 'Paper', 'Scissors']
win_rules = {'Rock': 'Scissors', 'Scissors': 'Paper', 'Paper': 'Rock'}

while True:
    bot_choice = random.choice(options)
    user_choice = input("(What would you like to play?...)").strip().capitalize()
    
    # 输入校验
    if user_choice not in options:
        print("Bad input! Try again!")
        continue
    
    # 胜负判定
    print(f"Game: {bot_choice}!")
    if bot_choice == user_choice:
        print("Tie! Try Again!")
    elif win_rules[user_choice] == bot_choice:
        print("You win!")
        break
    else:
        print("You lose!")
        break

内容的提问来源于stack exchange,提问作者Malvur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 16:24:03