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

请求协助实现石头剪刀布程序至少循环3次(附现有代码)

实现至少循环3次的石头剪刀布程序

原代码存在嵌套while True导致的逻辑混乱问题,且没有计数机制保证最少运行3局。以下是修改后的完整代码,同时优化了输入验证和逻辑结构:

import random

# 欢迎界面
input("欢迎来到石头剪刀布!按回车键开始游戏")

games_played = 0
min_required_games = 3

while True:
    # 获取玩家输入并统一格式,同时做输入验证
    player_choice = input("请选择:石头(Rock)、剪刀(Scissor)、布(Paper): ").strip().capitalize()
    while player_choice not in ["Rock", "Paper", "Scissor"]:
        print("输入无效,请重新选择!")
        player_choice = input("请选择:石头(Rock)、剪刀(Scissor)、布(Paper): ").strip().capitalize()
    
    # 电脑随机选择
    computer_choice = random.choice(["Rock", "Paper", "Scissor"])
    print(f"电脑选择了: {computer_choice}")

    # 判断胜负
    if (player_choice == "Rock" and computer_choice == "Paper") or \
       (player_choice == "Paper" and computer_choice == "Scissor") or \
       (player_choice == "Scissor" and computer_choice == "Rock"):
        print("电脑获胜!")
    elif player_choice == computer_choice:
        print("平局!")
    else:
        print("你获胜了!")
    
    games_played += 1
    
    # 完成最少3局后询问是否继续
    if games_played >= min_required_games:
        continue_choice = input("已完成3局游戏,是否继续?(y/n) ").strip().lower()
        if continue_choice == "n":
            break

print("游戏结束!")

核心修改说明:

  • 新增games_played计数器,确保程序至少运行3局后才会询问是否终止
  • 添加输入验证逻辑,避免玩家输入无效内容(如小写、错别字)
  • 简化胜负判断的条件写法,用or合并同类逻辑,让代码更简洁易读
  • 移除原代码中嵌套的while True循环,修复逻辑混乱问题
  • 将“是否继续”的询问逻辑移至完成3局后,避免每局都重复询问

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 10:20:33