如何在Python中摆脱全局变量



在本例中,如果将注释的代码交换出去,global变量将正常工作。我似乎没能在这里找到Python的一些基本知识,因为传递变量似乎不正确。

import random
def roll_die(sides=6):
return random.randint(1, sides)
# def game():
def game(score_p1,score_p2,rounds):
# global score_p1
# global score_p2
# global rounds

roll_1=roll_die()
roll_2=roll_die()
winner=None
if roll_1 > roll_2:
score_p1 = score_p1 +1
score_p2 = score_p2 -1
winner='player 1'
if roll_1 < roll_2:
score_p1 = score_p1 -1
score_p2 = score_p2 +1
winner='player 2'
if roll_1 == roll_2:
winner='No one'
print(f'p1 rolled {roll_1} and p2 rolled {roll_2}: Winner is {winner} ')    
print(score_p1,score_p2)
rounds = rounds + 1
# print(score_p1,score_p2, rounds)
return score_p1,score_p2,rounds
if __name__  == '__main__':

tokens=5
score_p1=tokens
score_p2=tokens
rounds=0
while True:
if (score_p1 <= 0) or (score_p2 <= 0):
print(f'Final Score: {score_p1}:{score_p2} with {rounds} rounds')
break
else:
# game()
game(score_p1,score_p2,rounds)

我从非全局版本获得的示例结果:

p1 rolled 3 and p2 rolled 1: Winner is Player 1
6 4
p1 rolled 1 and p2 rolled 4: Winner is Player 2
4 6
p1 rolled 5 and p2 rolled 3: Winner is Player 1
6 4
p1 rolled 3 and p2 rolled 1: Winner is Player 1
6 4
p1 rolled 4 and p2 rolled 4: Winner is No one
5 5
p1 rolled 2 and p2 rolled 2: Winner is No one
5 5

游戏永远循环

您必须将game返回的值重新分配给名称:

while True:
if (score_p1 <= 0) or (score_p2 <= 0):
print(f'Final Score: {score_p1}:{score_p2} with {rounds} rounds')
break
else:
score_p1, score_p2, rounds = game(score_p1,score_p2,rounds)

一种解决方案是将这些变量存储在一个对象中,以便它们在函数调用之间保持不变——例如,所有游戏状态都可以存在于Game对象中,如下所示:

import random

def roll_die(sides=6):
return random.randint(1, sides)

class Game:
def __init__(self):
self.tokens = self.score_p1 = self.score_p2 = 5
self.rounds = 0
def play(self):
roll_1 = roll_die()
roll_2 = roll_die()
if roll_1 > roll_2:
self.score_p1 += 1
self.score_p2 -= 1
winner = 'player 1'
elif roll_1 < roll_2:
self.score_p1 -= 1
self.score_p2 += 1
winner = 'player 2'
else:
winner = 'No one'
print(f'p1 rolled {roll_1} and p2 rolled {roll_2}: Winner is {winner} ')
print(self.score_p1, self.score_p2)
self.rounds += 1

if __name__ == '__main__':
game = Game()
while True:
game.play()
if game.score_p1 <= 0 or game.score_p2 <= 0:
print(f'Final Score: {game.score_p1}:{game.score_p2} with {game.rounds} rounds')
break

最新更新