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

Python中While True循环未正常终止问题求助(石头剪刀布游戏)

问题分析与修复:石头剪刀布游戏无法终止的问题

核心问题1:终止条件逻辑完全错误

你的代码在玩家输入动作后判断if score1 <3 or score2 <3,这个逻辑是只要有一个玩家分数没到3,就继续执行回合。但当其中一个玩家分数已经≥3时(比如score1=3,score2=1),score2<3为True,整个条件仍成立,会继续运行回合,永远不会触发终止逻辑。

正确逻辑应该是:只要任意一个玩家分数≥3,就立即终止游戏,需要把判断时机和条件逻辑调整过来。

核心问题2:胜负判断与计分全错

代码里多个分支的胜负判断搞反,导致分数累积错误,比如:

  • 玩家1出P、玩家2出S时,剪刀剪纸应该是玩家2赢,但代码给score1加分
  • 玩家1出R、玩家2出P时,纸包石头应该是玩家2赢,代码同样给score1加分
    这种错误会导致分数无法正确累积到3,或者分数达标后也因逻辑问题无法触发终止。

修复后的完整代码

print("---Rock 🪨 paper 📄 or scissors ✂---")
print("")
print("Choose your move; R, P or S")

score1 = 0
score2 = 0
while True:
    # 先检查是否有人达标,达标则终止游戏
    if score1 >= 3 or score2 >= 3:
        print("Game over")
        break
    
    player_1 = input("Player 1 move? ").strip().upper()
    player_2 = input("Player 2 move? ").strip().upper()
    
    # 处理平局
    if player_1 == player_2:
        print("Even round")
        continue
    
    # 正确的胜负判断逻辑
    if (player_1 == "P" and player_2 == "R") or \
       (player_1 == "R" and player_2 == "S") or \
       (player_1 == "S" and player_2 == "P"):
        print("Player 1 won!")
        score1 += 1
    else:
        print("Player 2 won!")
        score2 += 1
    
    # 打印当前分数
    print(f"Current scores: Player1 = {score1}, Player2 = {score2}")

print(f"Player 1 final score = {score1}")
print(f"Player 2 final score = {score2}")

修复说明

  1. 调整终止判断时机:在玩家输入动作前先检查分数,一旦有人达标就立即终止,避免无效的输入请求
  2. 简化并修正胜负逻辑:用简洁的条件覆盖玩家1获胜的所有情况,剩余情况自动判定为玩家2获胜,减少分支错误
  3. 优化输入兼容性:加入.strip().upper(),支持输入空格或小写字母的情况
  4. 优化分数展示:用f-string统一打印当前分数,更直观清晰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 02:22:45