Created
August 25, 2017 01:15
-
-
Save egregius313/059db360426764179c00ba4c0f3d1540 to your computer and use it in GitHub Desktop.
Adaptation of the "Conway's Really Simple Game" code from Jack Diederich's talk "Stop Writing Classes".
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
# stop_writing_classes_game_of_life.py | |
""" | |
Adaptation of the "Conway's Really Simple Game" code | |
from Jack Diederich's talk "Stop Writing Classes". | |
Meant to help make some of the logic more explicit. | |
""" | |
from itertools import chain | |
def neighbors(point): | |
x, y = point | |
return ((x - 1, y - 1), (x - 1, y), (x - 1, y + 1), | |
(x, y - 1), (x, y + 1), | |
(x + 1, y - 1), (x + 1, y), (x + 1, y + 1)) | |
def advance(board): | |
new_state = set() | |
all_neighbors = (neighbors(point) for point in board) | |
points_to_recalculate = board | set(chain(*all_neighbors)) | |
for point in points_to_recalculate: | |
count = sum(neighbor in board for neighbor in neighbors(point)) | |
if count == 3 or (count == 2 and point in board): | |
new_state.add(point) | |
return new_state | |
glider = {(0, 0), (1, 2), (2, 0), (0, 1), (0, 2)} | |
for _ in range(1000): | |
glider = advance(glider) | |
print(glider) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment