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

Python石头剪刀布游戏变量值无法跨if语句持久保存的问题

问题分析

你的代码核心问题是每次调用rock_paper_scissors()函数时,life和comp_life都会被重新初始化为3,导致之前的生命值无法保留。另外还有几个次要问题:

  • 函数被定义在while True循环内部,每次循环都会重复定义函数,完全没必要
  • 输入无效时用递归调用函数,会导致函数嵌套,进一步丢失生命值状态
  • 存在重复的胜负判断条件(比如两次判断user_choice == 1 and computer_choice ==3)
修复方案

把生命值的管理移到函数外部,让循环控制游戏回合,函数只负责单回合逻辑并返回生命值变化:

import random

def rock_paper_scissors(user_life, comp_life):
    print("1 = rock\n2 = paper\n3 = scissors\nEnter")
    # 循环直到输入有效
    while True:
        try:
            user_choice = int(input("1, 2, 3\n"))
            if 1 <= user_choice <=3:
                break
            else:
                print("Invalid choice, please enter 1,2 or 3")
        except ValueError:
            print("Please enter a valid number")
    
    # 映射选择到对应名称
    choice_map = {1: "rock", 2: "paper", 3: "scissors"}
    user_name = choice_map[user_choice]
    print("You chose ", user_name)
    
    print("Bob's turn")
    computer_choice = random.randint(1,3)
    comp_name = choice_map[computer_choice]
    
    # 判断胜负并更新生命值
    if user_choice == computer_choice:
        print(f"Draw! Bob chose {comp_name}")
    elif (user_choice ==1 and computer_choice ==3) or \
         (user_choice ==2 and computer_choice ==1) or \
         (user_choice ==3 and computer_choice ==2):
        print(f"You win! Bob chose {comp_name}")
        comp_life -=1
        print(f"Computer lost a life, now has {comp_life} lives")
    else:
        print(f"You lose! Bob chose {comp_name}")
        user_life -=1
        print(f"You lost a life, now have {user_life} lives")
    
    return user_life, comp_life

# 初始化全局生命值
life = 3
comp_life = 3

print("Welcome. I am Bob the AI.\nWe will play rock paper scissors. This is how we play:\nRock beats scissors\nScissors beat paper\nPaper beats rock\n")
print("You and Bob have three lives. If you lose all lives, the game is over. If Bob loses all lives, you win!\n")

while True:
    life, comp_life = rock_paper_scissors(life, comp_life)
    
    # 检查游戏结束条件
    if life <1:
        print("Game Over! You lost all lives.")
        break
    if comp_life <1:
        print("Congratulations! You won! Bob lost all lives.")
        break
修改说明
  • 将life和comp_life的初始化移到函数外部,通过函数参数传入当前生命值,修改后返回新值,保证状态持续保留
  • 把函数定义移到循环外部,避免重复定义函数的冗余操作
  • 用while True循环处理无效输入,替代递归调用,彻底避免状态丢失
  • 用字典映射选择到名称,简化代码结构
  • 合并胜负判断逻辑,去掉冗余的条件分支
  • 用break替代exit(),更符合Python循环控制的常规写法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 17:47:50