Skip to content

Instantly share code, notes, and snippets.

@wwhtrbbtt
Created April 18, 2021 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wwhtrbbtt/90674cbf59de0265f98f6ac13e03bcf6 to your computer and use it in GitHub Desktop.
Save wwhtrbbtt/90674cbf59de0265f98f6ac13e03bcf6 to your computer and use it in GitHub Desktop.
from random import choice
from time import sleep
from os import system
class Game():
def __init__(self, width=50, height=50, timeBetweenGenerations=0.1) -> None:
self.width = width
self.height = height
self.timeBetweenGenerations = timeBetweenGenerations
self.initialize()
def _getNeighbourCount(self, x: int, y: int) -> int:
alive = 0
try: alive += self.cells[x-1][y-1]
except KeyError: pass
try: alive += self.cells[x-1][y]
except KeyError: pass
try: alive += self.cells[x-1][y+1]
except KeyError: pass
try: alive += self.cells[x][y-1]
except KeyError: pass
try: alive += self.cells[x][y+1]
except KeyError: pass
try: alive += self.cells[x+1][y-1]
except KeyError: pass
try: alive += self.cells[x+1][y]
except KeyError: pass
try: alive += self.cells[x+1][y+1]
except KeyError: pass
return alive
def initialize(self) -> None:
self.cells = {}
for x in range(self.width):
self.cells[x] = {}
for y in range(self.height):
self.cells[x][y] = False
def print(self) -> None:
alive = "🟩"
dead = "🟥"
for x in self.cells:
for y in self.cells[x]:
if self.cells[x][y]:
print(alive, end="")
else:
print(dead, end="")
print()
def randomize(self) -> None:
for x in self.cells:
for y in self.cells[x]:
self.cells[x][y] = choice([True, False])
def calculate(self) -> None:
newCells = {}
for x in self.cells:
newCells[x] = {}
for y in self.cells[x]:
count = self._getNeighbourCount(x, y)
# Any live cell with fewer than two live neighbours dies, as if by underpopulation.
if count < 2 and self.cells[x][y]:
newCells[x][y] = False
# Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
elif count == 3 and not self.cells[x][y]:
newCells[x][y] = True
# Any live cell with two or three live neighbours lives on to the next generation.
elif (count == 2 or count == 3) and self.cells[x][y]:
newCells[x][y] = True
# Any live cell with more than three live neighbours dies, as if by overpopulation.
elif count > 3 and self.cells[x][y]:
newCells[x][y] = False
elif not self.cells[x][y]:
# print("Dead: ", x, y)
newCells[x][y] = False
elif self.cells[x][y]:
print("Alive: ", x, y)
newCells[x][y] = True
self.cells = newCells
def run(self):
while True:
self.print()
self.calculate()
sleep(self.timeBetweenGenerations)
system("clear")
g = Game()
g.width = 60
g.height = 60
g.randomize()
g.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment