我正在尝试编写一个掷 2 个骰子的代码,并且还有一些其他要求需要寻找。我已将变量声明为全局变量,但它仍然给我一个错误
我也尝试过将变量作为draw()函数中的条件,但这仍然不起作用
class DiceGame():
def game():
global p1total
global p1total
p1total = 0
p2total = 0
i=1
for i in range(1,5):
dice1 = random.randint(1,6)
dice2 = random.randint(1,6)
dice3 = random.randint(1,6)
dice4 = random.randint(1,6)
dice5 = random.randint(1,6)
dice6 = random.randint(1,6)
if (dice1+dice2)%2 == 0:
if p1total >= 10:
p1total -+10
else:
p1total = 0
else:
p1total += 5
if dice1==dice2:
p1total += dice1+dice2+dice3
if (dice4+dice5)%2 == 0:
if p2total >= 10:
p2total -+10
else:
p2total = 0
else:
p2total += 5
if dice4==dice5:
p2total += dice4+dice5+dice6
i+=1
DiceGame.draw(p1total, p2total)
def draw(p1total, p2total):
print("Player 1 has:",p1total)
print("Player 2 has:",p2total)
if p1total==p2total:
p1dice = random.randint(1,6)
p1total+=p1dice
p2dice = random.randint(1,6)
p2total+=p2dice
DiceGame.draw()
elif p1total > p2total:
print("Player 1 wins with",p1total)
print("Player 2 lost with",p2total)
DiceGame.scores()
elif p1total < p2total:
print("Player 2 wins with",p2total)
print("Player 1 lost with",p1total)
错误: 回溯(最近一次调用最后一次): 文件“”,第 1 行,位于 骰子游戏.game() 文件“C:/Users/fredd/Desktop/dan/Dice 游戏控制评估分钟 lines.py”,第 61 行,游戏中 骰子游戏.draw() 文件“C:/Users/fredd/Desktop/dan/Dice 游戏控制评估分钟 lines.py”,第 63 行,绘图中 print("玩家 1 有:",p1total) UnboundLocalError:赋值前引用的局部变量“p1total”
我只需要变量可用于draw()函数并输出获胜者
这是我的一个错误,我没有在全局语句中正确定义变量!