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

石头剪刀布游戏重启分数未重置问题及while循环按需重复需求

石头剪刀布游戏分数重置与循环问题解决

问题描述

  • 已实现石头剪刀布基础功能,但重启游戏时玩家分数(ps)与电脑分数(cs)无法重置为0
  • 需要优化循环逻辑,实现按用户要求重复执行游戏循环

原始代码框架

x=1
i=1
ps=0
cs=0
while i==1:
    while x==1:
        print("First to 5 wins!")
        #print score
        score(str(ps),str(cs))
        #code for game and the outcomes
        #ending
        if ps!=5 and cs!=5:
            end=yesorno("Would you like to forfeit? (y/n)")
            if end=="y":
                print("You coward!")
                ngc=yesorno("Would you like to start a new game? (y/n)")
                ng=ngc.lower()
                if ng=="y":
                    i=2
                else:
                    i=1
                    x=2
                    input("press enter to exit...")
            
            else:
                i=1
        else:
            if cs==5:
                print("The computer won 5 to "+ps+"...")
                ngc=yesorno("Would you like to start a new game? (y/n)")
                ng=ngc.lower()
                if ng=="y":
                    i=2
                else:
                    i=1
                    x=2
                    input("press enter to exit...")
            else:
                print("The player won 5 to "+str(cs)+"...")
                ngc=yesorno("Would you like to start a new game? (y/n)")
                ng=ngc.lower()
                if ng=="y":
                    i=2
                else:
                    i=1
                    x=2
                    input("press enter to exit...")

解决方案

1. 分数重置问题修复

将分数变量ps和cs的初始化移到外层循环内部,每次启动新游戏时自动重置为0。

2. 循环逻辑优化

简化嵌套循环结构,用单循环配合条件判断控制游戏流程,避免多余状态变量的混乱赋值。

修改后的完整代码

while True:
    # 每次新游戏重置分数
    ps = 0
    cs = 0
    print("First to 5 wins!")
    
    while ps < 5 and cs < 5:
        # 打印当前分数
        print(f"Score: Player {ps} - Computer {cs}")
        # 此处插入游戏核心逻辑(玩家出拳、电脑随机出拳、判断胜负并更新分数)
        
        # 中途认输选项
        end = input("Would you like to forfeit? (y/n)").lower()
        if end == "y":
            print("You coward!")
            break
    
    # 游戏结束后判定胜负
    if cs == 5:
        print(f"The computer won 5 to {ps}...")
    elif ps == 5:
        print(f"The player won 5 to {cs}...")
    
    # 询问是否开启新游戏
    ng = input("Would you like to start a new game? (y/n)").lower()
    if ng != "y":
        input("press enter to exit...")
        break

修改说明

  • 外层while True循环负责控制游戏的重复启动,用户选择不玩时通过break退出
  • 每次进入外层循环时,自动重置ps和cs为0,彻底解决分数无法重置的问题
  • 内层循环专注于单局游戏的进行,直到一方达到5分或玩家认输
  • 移除了冗余的状态变量x和i,逻辑更清晰,避免赋值混乱

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 21:15:33