Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from time import sleep
- from random import random
- def main():
- printIntro()
- rows, cols, gens = getInputs()
- thisGen = initGame(rows, cols)
- nextGen = initGame(rows, cols)
- for gen in range(gens): #I meant to have it clear the screen each time
- printGen(rows, cols, thisGen) # but I couldn't get os.system('cls')
- calcNext(rows, cols, thisGen, nextGen) #to work right.
- thisGen = nextGen[:]
- sleep(.1)
- print()
- if input("Type 'again' to try again. <return> to close. ") == "again":
- main()
- def printIntro():
- print("Conway's Game of Life")
- print()
- print("Conway's Game of Life is a cellular automaton.")
- print("There's a grid of cells that act according to rules.")
- print("If a cell is alive and has 2 or 3 neighbors (in the surrounding 8) it survives.")
- print("If a cell is dead and has 3 neighbors it lives.")
- print("All other cells are dead or die.")
- print()
- def getInputs():
- try:
- rows = eval(input("How many rows tall? 'return' for 20 "))
- except SyntaxError:
- rows = 20
- try:
- cols = eval(input("How many columns wide? 'return' for 40 "))
- except SyntaxError:
- cols = 40
- try:
- gens = eval(input("How many generations would you like to simulate? 'return' for 100 "))
- except SyntaxError:
- gens = 100
- return rows, cols, gens
- def initGame(rows, cols): # makes a randomized grid
- array = []
- for r in range(rows):
- row = []
- for c in range(cols):
- if (r == 0 or c == 0 or r == rows - 1 or c == cols - 1):
- row += [-1] #establish a boundary that won't change
- else:
- rand = random()
- if rand < .33:
- row += [1]
- else:
- row += [0]
- array.append(row)
- return array
- def printGen(rows, cols, thisGen):
- for r in range(rows):
- for c in range(cols):
- if r ==(0 or rows - 1):
- print("-", end="") # top and bottom boundary
- elif c ==(0):
- print("|", end="") # left boundary
- elif c == (cols - 1):
- print("|") #different line so it'd end with \n
- elif thisGen[r][c] == 1:
- print("█", end="")
- else:
- print("░", end="") # because I wanted more than just a " "
- def calcNext(rows, cols, thisGen, nextGen):
- for r in range(1, rows - 1):
- for c in range(1, cols-1):
- nextGen[r][c] = getState(r, c, thisGen)
- def getState(x, y, gen):
- count = 0 #number of neighbors
- for r in range(x-1, x+2):
- for c in range(y-1, y + 2):
- if gen[r][c] != -1:
- count += gen[r][c]
- if count == 3:
- return 1
- elif count == 4:
- return gen[x][y]
- else:
- return 0
- # I got this idea from the wikipedia page for Conway's Game of Life, under "algorithms"
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement