Skip to content

Instantly share code, notes, and snippets.

@tobgu
Created December 15, 2013 08:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tobgu/7970432 to your computer and use it in GitHub Desktop.
Save tobgu/7970432 to your computer and use it in GitHub Desktop.
Set based game of life
def candidates_for(world):
return set.union(*[neighbours_of(cell) | set([cell]) for cell in world])
DIRECTIONS = {(-1, 1), (0, 1), (1, 1),
(-1, 0), (1, 0),
(-1, -1), (0, -1), (1, -1)}
def neighbours_of(cell):
x, y = cell
return set((x+dx, y+dy) for dx, dy in DIRECTIONS)
def judge(cell, world):
neighbour_count = len(neighbours_of(cell) & world)
return neighbour_count in (2, 3) if cell in world else neighbour_count == 3
def evolve(world):
return set(c for c in candidates_for(world) if judge(c, world))
def test_single_cell_dies():
single_cell = {(0, 0)}
assert evolve(single_cell) == set([])
def test_square_remains():
square = {(0, 0), (0, 1), (1, 0), (1, 1)}
assert evolve(square) == square
def test_blinker_blinks():
blinker_1 = {(0, -1), (0, 0), (0, 1)}
blinker_2 = {(-1, 0), (0, 0), (1, 0)}
assert evolve(blinker_1) == blinker_2
assert evolve(blinker_2) == blinker_1
def test_three_diagonal_cells_evolve_to_single_cell():
assert evolve({(-1, -1), (0, 0), (1, 1)}) == {(0, 0)}
def test_three_cells_in_angle_evolves_to_square():
angle = {(0, 0), (0, 1), (1, 0)}
square = {(0, 0), (0, 1), (1, 0), (1, 1)}
assert evolve(angle) == square
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment