Skip to content

Instantly share code, notes, and snippets.

@usergenic
Created January 13, 2022 23:31
Show Gist options
  • Save usergenic/6ef2a124bc89fcbcf90126bbf15a3b07 to your computer and use it in GitHub Desktop.
Save usergenic/6ef2a124bc89fcbcf90126bbf15a3b07 to your computer and use it in GitHub Desktop.
Quick Conway's Game of Life implementation
# You can run this on http://pythonsandbox.com/graphics
import sandbox
import time
canvas = sandbox.createCanvas()
def makegrid(width,height):
return [[0 for y in range(0, height)] for x in range(0, width)]
def drawgrid(grid, cellwidth, cellheight):
for x in range(0, len(grid)):
for y in range(0, len(grid[x])):
cx=x*cellwidth
cy=y*cellheight
c=grid[x][y]
if c == 0:
canvas.fillColor("Black")
else:
canvas.fillColor("Green")
canvas.fillRect((cx, cy), (cx+cellwidth,cy+cellheight))
def getcell(grid, x, y):
if x < 0:
x = len(grid)-1
if y < 0:
y = len(grid[0])-1
if x >= len(grid):
x = 0
if y >= len(grid[x]):
y = 0
return grid[x][y]
def countneighbors(grid, x, y):
neighbors = [(x-1,y-1),(x,y-1),(x+1,y-1),(x-1,y),(x+1,y),(x-1,y+1),(x,y+1),(x+1,y+1)]
count = 0
for n in neighbors:
count = count + getcell(grid, n[0], n[1])
return count
def liferule(grid, x, y):
n = countneighbors(grid, x, y)
if n <= 1:
return 0
if n >= 4:
return 0
if n == 3:
return 1
return getcell(grid, x, y)
def nextgrid(grid):
newgrid = makegrid(len(grid), len(grid[0]))
for x in range(0, len(grid)):
for y in range(0, len(grid[x])):
newgrid[x][y] = liferule(grid, x, y)
return newgrid
g = makegrid(16, 16)
g[11][8] = 1
g[12][9] = 1
g[10][10] = 1
g[11][10] = 1
g[12][10] = 1
g[4][9] = 1
g[4][10] = 1
g[4][11] = 1
g[5][9] = 1
g[6][10] = 1
while True:
drawgrid(g, 20, 20)
g = nextgrid(g)
time.sleep(0.06)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment