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

如何解决Python游戏在while循环确认yes后无法进入游戏的问题

问题分析

你的代码核心问题出在while循环逻辑和游戏代码执行时机上:

  • 输入yes后用了continue,导致循环直接进入下一轮,永远跳不出循环去执行后续游戏逻辑
  • 就算跳出循环,游戏函数仅被定义在if块里,没有实际调用启动游戏
  • 缺少random模块导入,且check_win函数的胜负判断逻辑不完整
修复后的完整代码
import random  # 必须导入random模块才能使用随机选择功能

user_name = input("What is your name? ")
user = user_name
print(f"Welcome {user}!")

while True:
    user_ans = input("Are you ready to play ROCK, PAPER, SCISSORS? (yes or no?) ")

    if user_ans.lower() == 'yes':
        print("Alright, Let's play!")
        break  # 输入yes后跳出循环,进入游戏流程
    elif user_ans.lower() == 'no':
        print('Not ready to play? Okay, see ya later!')
        exit()
    else:
        print('Type yes or no')

# 定义游戏核心函数(建议放在全局作用域,避免嵌套在条件块中)
def get_choices():  
    player_choice = input("Enter a choice (rock, paper, scissors): ").lower()
    # 增加输入验证,防止无效选项
    while player_choice not in ['rock', 'paper', 'scissors']:
        print("Invalid choice! Please enter rock, paper, or scissors.")
        player_choice = input("Enter a choice (rock, paper, scissors): ").lower()
    options = ['rock', 'paper', 'scissors']
    computer_choice = random.choice(options)
    choices = {"player": player_choice, "computer": computer_choice}
    return choices 

def check_win(player, computer ):
    print(f"You chose {player}, computer chose {computer}.")
  
    if player == computer:
        return "It's a tie!"
    elif player == "rock":
        return "Rock smashes scissors! You win!" if computer == "scissors" else "Paper covers rock! You lose!"
    elif player == "paper":
        return "Paper covers rock! You win!" if computer == "rock" else "Scissors cuts paper! You lose!"
    elif player == "scissors":
        return "Scissors cuts paper! You win!" if computer == "paper" else "Rock smashes scissors! You lose!"

# 启动游戏流程
choices = get_choices()
result = check_win(choices["player"], choices["computer"])
print(result)

# 可选:添加多轮游戏支持
play_again = input("Do you want to play again? (yes/no) ").lower()
while play_again == 'yes':
    choices = get_choices()
    result = check_win(choices["player"], choices["computer"])
    print(result)
    play_again = input("Do you want to play again? (yes/no) ").lower()
print("Thanks for playing!")
关键修改说明
  • 将continue替换为break:输入yes后跳出循环,让程序执行后续游戏代码
  • 补充random模块导入:解决random.choice的报错问题
  • 完善check_win函数:补全所有胜负场景的判断逻辑
  • 增加输入验证:避免玩家输入无效选项导致游戏异常
  • 优化函数作用域:将游戏函数移到全局范围,让代码结构更清晰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 15:15:16