Last active
December 11, 2015 23:58
-
-
Save tombatron/4680522 to your computer and use it in GitHub Desktop.
PyLife
This file contains hidden or 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 curses | |
import random | |
class Life(object): | |
max_x = 200 | |
max_y = 60 | |
_grid = {} | |
_coordinates = [] | |
def __init__(self, seed=None): | |
for x in (x for x in range(0, self.max_x)): | |
for y in (y for y in range(0, self.max_y)): | |
self._coordinates.append((x, y,)) | |
for x, y in self._coordinates: | |
self._grid[x, y] = int(random.randint(1, 100) % 2) if seed is None else 0 | |
if seed is not None: | |
self._grid.update(seed) | |
def find_neighbors(self, x, y): | |
x_plus_1 = x + 1 | |
x_minus_1 = x -1 | |
y_plus_1 = y + 1 | |
y_minus_1 = y - 1 | |
return [(x, y_plus_1), | |
(x, y_minus_1), | |
(x_plus_1, y), | |
(x_plus_1, y_plus_1), | |
(x_plus_1, y_minus_1), | |
(x_minus_1, y), | |
(x_minus_1, y_plus_1), | |
(x_minus_1, y_minus_1) | |
] | |
def _live_neighbor_count(self, x, y, ref_grid): | |
live_cells = 0 | |
for nX, nY in self.find_neighbors(x , y): | |
try: live_cells += ref_grid[nX, nY] | |
except KeyError: pass | |
return live_cells | |
def evolve(self): | |
existing_grid = self._grid.copy() | |
for x, y in self._coordinates: | |
current_value = result = self._grid[x, y] | |
live_neighbor_count = self._live_neighbor_count(x, y, existing_grid) | |
if current_value == 0: | |
result = int(live_neighbor_count == 3) | |
else: | |
if live_neighbor_count < 2 or live_neighbor_count > 3: | |
result = 0 | |
if live_neighbor_count in (2,3): | |
result = 1 | |
self._grid[x, y] = result | |
yield y, x, ' ' if result == 0 else '@' | |
def main(stdscr): | |
curses.cbreak() | |
stdscr.keypad(1) | |
stdscr.nodelay(1) | |
seed = { | |
(1,3): 1, | |
(2,1): 1, | |
(2,3): 1, | |
(3,2): 1, | |
(3,3): 1, | |
} | |
l = Life(seed=seed) | |
counter = 0 | |
while True: | |
input = stdscr.getch() | |
if input == ord('q'): | |
break | |
if input == ord('r'): | |
l = Life() # Reinit | |
counter = 0 | |
for y, x, result in l.evolve(): | |
try: stdscr.addch(y, x, result) | |
except curses.error: pass | |
stdscr.addstr(60, 0, 'Iteration: %r' % counter) | |
stdscr.refresh() | |
counter += 1 | |
if __name__ == "__main__": | |
curses.wrapper(main) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment