71 lines
2.4 KiB
Python
Executable file
71 lines
2.4 KiB
Python
Executable file
#! /usr/bin/env python3
|
|
|
|
#conways game of life
|
|
import time, random, copy
|
|
|
|
width = 100
|
|
hight = 50
|
|
nextCells = []
|
|
currentCells = []
|
|
|
|
def createInitalBoard(): #create inital board
|
|
for x in range(width):
|
|
column = [] #add a column
|
|
for y in range(hight):
|
|
if random.randint(0, 1) == 0:
|
|
column.append('#') #add a living cell
|
|
else:
|
|
column.append(' ') #add a dead cell
|
|
nextCells.append(column) #append the newly created random column
|
|
def printBoard():
|
|
for y in range(hight):
|
|
for x in range(width):
|
|
print(nextCells[x][y], end='')
|
|
print()#print a newline at the end of the row.
|
|
print('\n\n\n\n\n') #seperate each step with newlines
|
|
|
|
def updateBoard():
|
|
currentCells = copy.deepcopy(nextCells) #create a buffer of the grid to work on.
|
|
for x in range(width):
|
|
for y in range(hight):
|
|
#get neighboring cordinates
|
|
#% width makes the board wrap.
|
|
leftCoord = (x-1)%width
|
|
rightCoord = (x+1)%width
|
|
aboveCoord = (y-1)%hight
|
|
belowCoord = (y+1)%hight
|
|
|
|
numNeighbors = 0
|
|
#count the number of living neighbors
|
|
if currentCells[leftCoord][aboveCoord] == '#':
|
|
numNeighbors +=1 #top left
|
|
if currentCells[x][aboveCoord] == '#':
|
|
numNeighbors +=1 #top
|
|
if currentCells[rightCoord][aboveCoord] == '#':
|
|
numNeighbors +=1 #top right
|
|
if currentCells[leftCoord][y] == '#':
|
|
numNeighbors +=1 #left
|
|
if currentCells[rightCoord][y] == '#':
|
|
numNeighbors +=1 #right
|
|
if currentCells[leftCoord][belowCoord] == '#':
|
|
numNeighbors +=1 #bottom left
|
|
if currentCells[x][belowCoord] == '#':
|
|
numNeighbors +=1 #bottom
|
|
if currentCells[rightCoord][belowCoord] == '#':
|
|
numNeighbors +=1 #bottom right
|
|
|
|
#set cell state based on conways rules
|
|
if currentCells[x][y] == '#' and (numNeighbors == 2 or numNeighbors == 3):
|
|
nextCells[x][y] = '#'
|
|
elif currentCells[x][y] == ' ' and numNeighbors == 3:
|
|
nextCells[x][y] = '#'
|
|
else:
|
|
nextCells[x][y] = ' '
|
|
|
|
createInitalBoard()
|
|
|
|
while True: #main loop
|
|
printBoard()
|
|
updateBoard()
|
|
time.sleep(.1)
|