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

如何为Craps游戏Python程序添加胜负次数计数器?

解决Craps游戏胜负计数器的问题

问题原因

你遇到的"局部变量在赋值前被引用"错误,是因为WinTotal和LoseTotal是全局变量,但在函数内部修改时,Python默认会将其视为局部变量,导致变量未定义的错误。要在函数里修改全局变量,必须先用global关键字声明。

修改步骤

  1. 在gameloop函数的胜负分支中,添加global声明来引用全局的计数器变量,然后执行累加操作
  2. 优化showstats函数,直接使用全局变量(避免不必要的参数传递)
  3. 修正原代码中潜在的逻辑小问题

修改后的完整代码

import random

# 全局变量声明
WinningValues = [7, 11]
LosingValues = [2, 3, 12]
WinTotal = 0
LoseTotal = 0

def gameloop():
    global WinTotal, LoseTotal  # 声明要使用全局变量
    D1 = random.randint(1,6)
    D2 = random.randint(1,6)
    DTotal = D1 + D2
    print("You rolled", D1, "and", D2, "for a total of", DTotal)
    
    if DTotal in WinningValues:
        print("You win")
        WinTotal += 1  # 累加获胜次数
        Cont = input("Type Y to roll again, X to quit, or S to see your stats: ")
        craps(Cont)
    elif DTotal in LosingValues:
        print("You lose")
        LoseTotal += 1  # 累加失败次数
        Cont = input("Type Y to roll again, X to quit, or S to see your stats: ")
        craps(Cont)
    else:
        print("You roll again")
        craps(Cont="Y")

def showstats():
    # 直接使用全局变量,无需参数传递
    print(f"You won a total of {WinTotal} and lost a total of {LoseTotal} times.")

def craps(Cont):
    if Cont == "Y":
        gameloop()
    elif Cont == "S":
        print("Executing")
        showstats()
    elif Cont == "X":
        quit()

# 程序入口
Cont = input("Would you like to play a game of craps? Type Y to play or X to quit: ")
if Cont == 'Y':
    gameloop()
elif Cont == 'X':
    quit()

关键改动说明

  • 在gameloop开头添加global WinTotal, LoseTotal,告诉Python我们要修改的是全局作用域的这两个变量,而非创建新的局部变量
  • 移除了showstats的参数,直接读取全局计数器,简化调用逻辑
  • 用f-string优化了统计信息的输出格式,让代码更简洁

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 20:45:34