I'm writing a Conway's Game of Life implementation. My first attempt was just to plot the board after each update using matplotlib's imshow on a NxN board of 1's and 0's. However, this didn't work as the program pauses whenever it shows the plot. You have to close the plot to get the next loop iteration.
I found out there was an animation package in matplotlib, but it doesn't take (or give) variables, so every implementatin of it I've seen (even matplotlib's documentation) relies on global variables.
So there's kind of two questions here:
1) Is this a place where it's ok to use globals? I've always read that it's never a good idea, but is this just dogma?
2) how would you do such an animation in python without globals (Even if it means ditching matplotlib, I guess; standard library is always preferred).
These are just example programs. You can use an object instead of global variables, like this:
class GameOfLife(object):
def __init__(self, initial):
self.state = initial
def step(self):
# TODO: Game of Life implementation goes here
# Either assign a new value to self.state, or modify it
def plot_step(self):
self.step()
# TODO: Plot here
# TODO: Initialize matplotlib here
initial = [(0,0), (0,1), (0,2)]
game = GameOfLife(initial)
ani = animation.FuncAnimation(fig, game.plot_step)
plt.show()
If you really want to avoid classes, you can also rewrite the program like this:
def step(state):
newstate = state[:] # TODO Game of Life implementation goes here
return newstate
def plot(state):
# TODO: Plot here
def play_game(state):
while True:
yield state
state = step(state)
initial = [(0,0), (0,1), (0,2)]
game = play_game(initial)
ani = animation.FuncAnimation(fig, lambda: next(game))
plt.show()
Note that for non-mathematical animations (without labels, graphs, scales, etc.), you may prefer pyglet or pygame.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With