Skip to content

Instantly share code, notes, and snippets.

@WitherOrNot
Created June 14, 2019 05:06
Show Gist options
  • Save WitherOrNot/198aab432034d07507ec19c79a68f2cd to your computer and use it in GitHub Desktop.
Save WitherOrNot/198aab432034d07507ec19c79a68f2cd to your computer and use it in GitHub Desktop.
Conway's Game of Life in the terminal
import random
size = 20
#on = [(1,1),(1,2),(1,3)] #Blinker
#on = [(1,0),(2,1),(0,2),(1,2),(2,2)] #Glider
on = [(2,2),(3,2),(4,2),(5,2),(6,2),(7,2),(9,2),(10,2),(2,3),(3,3),(4,3),(5,3),(6,3),(7,3),(9,3),(10,3),(9,4),(10,4),(2,5),(3,5),(9,5),(10,5),(2,6),(3,6),(9,6),(10,6),(2,7),(3,7),(9,7),(10,7),(2,8),(3,8),(2,9),(3,9),(5,9),(6,9),(7,9),(8,9),(9,9),(10,9),(2,10),(3,10),(5,10),(6,10),(7,10),(8,10),(9,10),(10,10)]
#^ Galaxy
#on = [(24, 0), (22, 1), (24, 1), (12, 2), (13, 2), (20, 2), (21, 2), (34, 2), (35, 2), (11, 3), (15, 3), (20, 3), (21, 3), (34, 3), (35, 3), (0, 4), (1, 4), (10, 4), (16, 4), (20, 4), (21, 4), (0, 5), (1, 5), (10, 5), (14, 5), (16, 5), (17, 5), (22, 5), (24, 5), (10, 6), (16, 6), (24, 6), (11, 7), (15, 7), (12, 8), (13, 8)]
#^Glider gun, 60 iters (start at 60)
#on = [(random.randint(0,size),random.randint(0,size)) for _ in range(random.randint(1,size**2))] #Random
def iterate(on, size):
u = [(x,y) for x in range(size) for y in range(size)]
offsets = [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]
nb = []
for x,y in u:
r = [(x+i,y+j) for i,j in offsets]
rc = [(x+i,y+j) for i,j in offsets]
for i in rc:
if i not in on:
r.remove(i)
r = len(r)
nb.append(r)
for i in range(len(u)):
if nb[i] != 2 and nb[i] != 3:
if u[i] in on:
on.remove(u[i])
if nb[i] == 3:
if u[i] not in on:
on.append(u[i])
return on
u = [(y,x) for x in range(size) for y in range(size)]
i = 0
while True:
print("Generation "+str(i))
c = lambda x: "# " if x in on else ". "
r = ""
for j in range(1, len(u)+1):
r += c(u[j-1])
if j % size == 0:
r += "\n"
print(r)
on = iterate(on, size)
i += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment