matplotlib animation

matplotlib
Tom Weber 3 years ago
parent dc509eb03b
commit f42fa91f1d

@ -1,9 +1,7 @@
import random import random
import copy import copy
import time import matplotlib.pyplot as plt
import os import matplotlib.animation as animation
os.system("cls")
class State(object): class State(object):
@ -37,7 +35,7 @@ class State(object):
else: else:
self.board[idx][jdx] = 0 self.board[idx][jdx] = 0
def render(self): def terminal_render(self):
print("-" * (self.width + 2)) print("-" * (self.width + 2))
for i in self.board: for i in self.board:
print( print(
@ -47,6 +45,10 @@ class State(object):
) )
print("-" * (self.width + 2)) print("-" * (self.width + 2))
def plt_render(self):
plt.imshow(self.board)
plt.show()
def step(self): def step(self):
boardcopy = copy.deepcopy(self.board) boardcopy = copy.deepcopy(self.board)
for rowidx, row in enumerate(self.board): for rowidx, row in enumerate(self.board):
@ -91,14 +93,44 @@ class State(object):
return alive return alive
class BoardAnimation(object):
def __init__(self, state, steps=None):
self.state = state
self.steps = steps
self.fig, self.ax = plt.subplots()
self.ax = self.ax.matshow(self.state.board)
def frame_yield(self):
while True:
self.state.step()
yield self.state.board
def frame_gen(self):
frames = []
for i in range(self.steps):
self.state.step()
[].append(self.state.board)
return self.ax, frames
def init(self):
return self.state.board
def update(self, data):
self.ax.set_data(data)
return self.ax
def animate(self):
return animation.FuncAnimation(
self.fig, self.update, self.frame_yield, init_func=self.init, interval=100
)
def main(): def main():
state = State(20, 20, [(0, 1), (1, 2), (2, 0), (2, 1), (2, 2)]) state = State(20, 20, [(0, 1), (1, 2), (2, 0), (2, 1), (2, 2)])
state.render() animation = BoardAnimation(state)
for i in range(100): ani = animation.animate()
time.sleep(0.1) plt.show()
os.system("clear")
state.step()
state.render()
if __name__ == "__main__": if __name__ == "__main__":

@ -0,0 +1,11 @@
contourpy==1.0.5
cycler==0.11.0
fonttools==4.37.4
kiwisolver==1.4.4
matplotlib==3.6.0
numpy==1.23.3
packaging==21.3
Pillow==9.2.0
pyparsing==3.0.9
python-dateutil==2.8.2
six==1.16.0
Loading…
Cancel
Save