Advertisement
Guest User

LIFE

a guest
Nov 20th, 2019
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. from collections import defaultdict
  4. import numpy as np
  5. import matplotlib as plt
  6. from matplotlib.animation import FuncAnimation
  7.  
  8. ROWS = 10
  9. COLS = 10
  10.  
  11.  
  12. class StateMachine:
  13. def __init__(self):
  14. self.init = None
  15. self.curr_state = None
  16. self.trans = defaultdict(dict)
  17.  
  18. def add_trans(self, state_from, state_to, fn):
  19. self.trans[state_from][fn] = to_state
  20.  
  21. def transit(self, x):
  22. choices = self.trans[self.curr_state]
  23.  
  24. for fn in choices:
  25. if fn(x):
  26. self.curr_state = choices[fn]
  27. return self.curr_state
  28.  
  29. raise ValueError(f"Unable to transit with x={x}")
  30.  
  31. def _main():
  32. b = gen_random_board()
  33. m = get_state_machine()
  34.  
  35. for _ in range(10):
  36. b = advance(b)
  37. print(b)
  38.  
  39.  
  40. def get_state_machine():
  41. m = StateMachine()
  42. m.add_trans(1, 1, lambda x: x in [2,3])
  43. m.add_trans(1, 0, lambda x: (x > 3 or x < 2))
  44. m.add_trans(0, 1, lambda x: x == 3)
  45. m.add_trans(0, 0, lambda x: x != 3)
  46.  
  47. return sm
  48.  
  49.  
  50. def gen_random_board(rows, cols):
  51. board = np.random.random((rows, cols))
  52. return np.round(board)
  53.  
  54.  
  55. def advance(old):
  56. new = old.copy()
  57. m = get_state_machine()
  58. for row in range(old.shape[0]):
  59. for col in range(old.shape[1]):
  60. cnt = count_living(old, row, col)
  61. curr = board[row, col]
  62. future = m.transit(cnt)
  63. new[row, col] = future
  64.  
  65. return new
  66.  
  67.  
  68. def count_living(board, row, col):
  69. sub = board[max(0, row-2):row+2, max(0, col-2):col+2]
  70. return np.sum(sub) - board[row, col]
  71.  
  72.  
  73. if __name__ == "__main__":
  74. _main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement