From f42fa91f1d2ff65ee0f54da32352444908442cd5 Mon Sep 17 00:00:00 2001 From: Tom Weber Date: Sat, 1 Oct 2022 15:25:25 +0200 Subject: [PATCH] matplotlib animation --- main.py | 54 ++++++++++++++++++++++++++++++++++++++---------- requirements.txt | 11 ++++++++++ 2 files changed, 54 insertions(+), 11 deletions(-) create mode 100644 requirements.txt diff --git a/main.py b/main.py index 28ba6b9..bb3186f 100644 --- a/main.py +++ b/main.py @@ -1,9 +1,7 @@ import random import copy -import time -import os - -os.system("cls") +import matplotlib.pyplot as plt +import matplotlib.animation as animation class State(object): @@ -37,7 +35,7 @@ class State(object): else: self.board[idx][jdx] = 0 - def render(self): + def terminal_render(self): print("-" * (self.width + 2)) for i in self.board: print( @@ -47,6 +45,10 @@ class State(object): ) print("-" * (self.width + 2)) + def plt_render(self): + plt.imshow(self.board) + plt.show() + def step(self): boardcopy = copy.deepcopy(self.board) for rowidx, row in enumerate(self.board): @@ -91,14 +93,44 @@ class State(object): 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(): state = State(20, 20, [(0, 1), (1, 2), (2, 0), (2, 1), (2, 2)]) - state.render() - for i in range(100): - time.sleep(0.1) - os.system("clear") - state.step() - state.render() + animation = BoardAnimation(state) + ani = animation.animate() + plt.show() if __name__ == "__main__": diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..03abb3d --- /dev/null +++ b/requirements.txt @@ -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