Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # coding: utf-8
- from collections import defaultdict
- import numpy as np
- import matplotlib as plt
- from matplotlib.animation import FuncAnimation
- ROWS = 10
- COLS = 10
- class StateMachine:
- def __init__(self):
- self.init = None
- self.curr_state = None
- self.trans = defaultdict(dict)
- def add_trans(self, state_from, state_to, fn):
- self.trans[state_from][fn] = to_state
- def transit(self, x):
- choices = self.trans[self.curr_state]
- for fn in choices:
- if fn(x):
- self.curr_state = choices[fn]
- return self.curr_state
- raise ValueError(f"Unable to transit with x={x}")
- def _main():
- b = gen_random_board()
- m = get_state_machine()
- for _ in range(10):
- b = advance(b)
- print(b)
- def get_state_machine():
- m = StateMachine()
- m.add_trans(1, 1, lambda x: x in [2,3])
- m.add_trans(1, 0, lambda x: (x > 3 or x < 2))
- m.add_trans(0, 1, lambda x: x == 3)
- m.add_trans(0, 0, lambda x: x != 3)
- return sm
- def gen_random_board(rows, cols):
- board = np.random.random((rows, cols))
- return np.round(board)
- def advance(old):
- new = old.copy()
- m = get_state_machine()
- for row in range(old.shape[0]):
- for col in range(old.shape[1]):
- cnt = count_living(old, row, col)
- curr = board[row, col]
- future = m.transit(cnt)
- new[row, col] = future
- return new
- def count_living(board, row, col):
- sub = board[max(0, row-2):row+2, max(0, col-2):col+2]
- return np.sum(sub) - board[row, col]
- if __name__ == "__main__":
- _main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement