In this example, if I swap the commented code out the global variables work correctly. I seem to failing to grok something fundamental about Python here as passing the variables doesn't seem to work correctly.
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)
Example results I get from the non-global version:
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
...And the game loops forever
source https://stackoverflow.com/questions/70414299/how-might-i-move-away-from-globals-in-python
Comments
Post a Comment