Skip to content

Instantly share code, notes, and snippets.

@cleichner
Created March 19, 2012 16:04
Show Gist options
  • Save cleichner/2117400 to your computer and use it in GitHub Desktop.
Save cleichner/2117400 to your computer and use it in GitHub Desktop.
Succinct Game of Life
# Jack Diederich wrote the advance function
# original code from http://pyvideo.org/video/880/stop-writing-classes
import collections
import curses
import gettext
import random
import signal
import sys
import time
from itertools import chain, count, ifilter, product
ROWS = 22
COLS = 40
ENTROPY = 100
REDRAW = 0.05
def not_origin(pt):
return pt != (0,0)
def neighbors(point):
x, y = point
for dx, dy in ifilter(not_origin, product((0,1,-1),(0,1,-1))):
yield x+dx, y+dy
def truncate(point):
x, y = point
return (x % ROWS, y % COLS)
def advance(board):
newstate = set()
recalc = board | set(chain(*map(neighbors, board)))
for point in recalc:
count = sum((neighbor in board) for neighbor in neighbors(point))
if count == 3 or (count == 2 and point in board):
newstate.add(point)
return set(map(truncate, newstate))
def display(board):
for x in range(ROWS):
for y in range(COLS):
screen.addstr(x, y, '*' if (x, y) in board else '.')
screen.refresh()
time.sleep(REDRAW)
def endwin(signum, frame):
curses.endwin()
sys.exit(0)
signal.signal(signal.SIGINT, endwin)
screen = curses.initscr()
board = set()
for _ in range(ENTROPY):
x = random.randint(0, COLS)
y = random.randint(0, ROWS)
board.add((x, y))
prev = collections.deque(maxlen=2)
for i in count(1):
display(board)
prev.append(board)
board = advance(board)
if any(p == board for p in prev):
break
plural = gettext.ngettext('', 's', i)
screen.addstr(ROWS,0,'Equillibrium in %d generation%s.\n' % (i, plural))
screen.getch()
curses.endwin()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment