Python石头剪刀布游戏平局逻辑失效问题求助
石头剪刀布平局判定问题修复
你的代码存在两个关键错误,导致平局场景无法触发,反而走到失败提示分支:
- 平局条件的语法缺失:所有平局判断的
elif语句中,uinput后都少了比较运算符==(比如elif uinput "paper" and cpp == "paper")。缺少==会让这些条件无法被正确识别,程序会直接跳过它们,最终进入else分支触发失败提示。 - 多余的语法字符:第二个胜利条件的
print("You won!")语句末尾多了一个反引号`,这会导致代码运行报错,必须删除。
另外,平局判断可以简化成一个统一条件,避免重复写三个类似分支,让代码更简洁易维护。以下是修正后的完整代码:
import random uw = 0 cpw = 0 options = ["rock", "paper", "scissors"] while True: uinput = input("Type Rock/Paper/Scissors or Q to quit: ").lower() if uinput == "q": break if uinput not in options: continue rn = random.randint(0, 2) # rock: 0, paper: 1, scissors: 2 cpp = options[rn] print("Computer picked", cpp + ".") if uinput == "rock" and cpp == "scissors": print("You won!") uw += 1 elif uinput == "paper" and cpp == "rock": print("You won!") uw += 1 elif uinput == "scissors" and cpp == "paper": print("You won!") uw += 1 elif uinput == cpp: # 统一判断平局 print("It's a tie, no points.") else: print("You lost!") cpw += 1 print("You won", uw, "times.") print("The computer won", cpw, "times") print("Goodbye")
修改后,平局场景会正确触发对应提示,不会再误判为失败。
内容的提问来源于stack exchange,提问作者Griyz
相关产品推荐
相关产品推荐

