Skip to content

Instantly share code, notes, and snippets.

@findoff
Last active July 28, 2016 19:06
Show Gist options
  • Save findoff/4a5699a735b90c55b4e5544c637ec68e to your computer and use it in GitHub Desktop.
Save findoff/4a5699a735b90c55b4e5544c637ec68e to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import random
import sys
from time import sleep
class Life:
symbols = ["\033[37;47m.\033[0m", "\033[31;41m#\033[0m"]
rules = [
# 0, 1, 2, 3, 4, 5, 6, 7, 8
[ 0, 0, 0, 1, 0, 0, 0, 0, 0 ], # dead
[ 0, 0, 1, 1, 0, 0, 0, 0, 0 ], # live
]
def __init__(self, w, h):
self.w = w
self.h = h
self.cells = []
self.shifts = [
-1, -1,
0, -1,
+1, -1,
-1, +1,
0, +1,
+1, +1,
-1, 0,
+1, 0,
]
self.clear()
self.forms = {
'acorn': [1,0, 3,1, 0,2, 1,2, 4,2, 5,2, 6,2,],
'glider': [0,0, 2,0, 2,1, 1,1, 1,2,],
}
self.place(15,15, self.forms['acorn'])
self.place(25,25, self.forms['glider'])
self.place(25,25, self.forms['glider'])
def clear(self):
self.cells = [ 0 for i in range(0,self.w * self.h) ]
def fill(self, f):
self.cells = [ round( random.random()*f ) for i in range(0,self.w * self.h) ]
def place(self, x,y, a):
for i in range(0, int(len(a)/2)):
self.cells[ a[i*2] + x + (a[i*2+1]+y) * self.w ] = 1
def render(self):
s = ''
n = 0
for y in range(0,self.h):
for x in range(0,self.w):
s = '%s%s'%(s, self.symbols[ self.cells[n] ] )
n = n + 1
s = "%s\n"%(s)
sys.stdout.write(s);
def process(self):
old = self.cells[:]
cnt = self.w * self.h
for y in range(0, self.h):
for x in range(0, self.w):
n = 0
for j in range(0,8):
pos = ( x+self.shifts[j*2]+self.w ) % self.w
pos += ( ( y+self.shifts[j*2+1]+self.h ) % self.h ) * self.w
n += old[ pos ]
pos = x + y * self.w
self.cells[pos] = self.rules[ old[pos] ] [n]
life = Life(64, 32)
while True:
print("\n\n\n\n");
life.render()
for i in range(0,1):
life.process()
sleep(0.1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment