Created
February 2, 2019 19:32
-
-
Save sshh12/4b834ea0694910b262fe4d32f2274664 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import cv2 | |
class CellularAutomaton: | |
def __init__(self, size=1000, rule=0): | |
self.size = size | |
self.rule = rule | |
self.r = 0 | |
self.grid = [[False for c in range(size)] for r in range(size)] | |
def get_render(self): | |
image = np.zeros((self.size, self.size, 3)) | |
image[:, :] = (255, 255, 255) | |
for r, row in enumerate(self.grid): | |
for c, life in enumerate(row): | |
if life: | |
image[r, c] = (0, 0, 0) | |
return image | |
def run(self): | |
r, row = self.r, self.grid[self.r] | |
for c in range(self.size): | |
if c > 0: | |
left = self.grid[r][c - 1] | |
else: | |
left = False | |
if c < self.size - 1: | |
right = self.grid[r][c + 1] | |
else: | |
right = False | |
center = self.grid[r][c] | |
state = False | |
if left and center and right: | |
state = (self.rule & 128) != 0 | |
elif left and center and not right: | |
state = (self.rule & 64) != 0 | |
elif left and not center and right: | |
state = (self.rule & 32) != 0 | |
elif left and not center and not right: | |
state = (self.rule & 16) != 0 | |
elif not left and center and right: | |
state = (self.rule & 8) != 0 | |
elif not left and center and not right: | |
state = (self.rule & 4) != 0 | |
elif not left and not center and right: | |
state = (self.rule & 2) != 0 | |
elif not left and not center and not right: | |
state = (self.rule & 1) != 0 | |
self.grid[(r + 1) % self.size][c] = state | |
self.r = (r + 1) % self.size | |
ca = CellularAutomaton(rule=215) | |
ca.grid[0][500] = True | |
while True: | |
image = ca.get_render() | |
ca.run() | |
cv2.imshow('frame', image) | |
if cv2.waitKey(1) & 0xFF == ord('q'): | |
break | |
cv2.destroyAllWindows() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment