我正在尝试编写一个掷出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行,位于 DiceGame.game() 文件“ C:/ Users / fredd / Desktop / dan / Dice游戏控制的评估最小值 lines.py“,游戏中的第61行 DiceGame.draw() 文件“ C:/ Users / fredd / Desktop / dan / Dice游戏控制的评估最小值 lines.py“,第63行,在绘制中 打印(“播放器1具有:”,p1total) UnboundLocalError:分配前已引用本地变量'p1total'
我只需要变量可用于draw()函数并输出获胜者
答案 0 :(得分:0)
这是我的错误,因为我没有在全局语句中正确定义变量!