我想做一个掷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:UsersfreddDesktopdanDice游戏控制评估min行.py",第61行,在游戏DiceGame.game中。 文件"",第1行,在DiceGame.game() 文件 "C:UsersfreddDesktopdanDice游戏控制评估min lines.py",第61行,在游戏DiceGame.draw() 文件 "C:UsersfreddDesktopdanDice游戏控制评估min lines.py",第63行,在draw print("Player 1 has:",p1total) UnboundLocalError: local variable 'p1total' referenced before assignment
我只需要将变量提供给draw()函数,并输出赢家。
这是我的一个错误,我没有在全局语句中正确定义变量!