Skip to content

Instantly share code, notes, and snippets.

@krsnvijay
Last active August 24, 2018 03:38
Show Gist options
  • Save krsnvijay/05a41a00eac0eebb8593d1b8027cc9f8 to your computer and use it in GitHub Desktop.
Save krsnvijay/05a41a00eac0eebb8593d1b8027cc9f8 to your computer and use it in GitHub Desktop.
John Conway's Game Of Life
import copy
import itertools
class GameOfLife:
def __init__(self, grid: list, width: int, height: int):
self.grid = grid
self.width = width
self.height = height
def game(self, iterations=5):
game_iter = itertools.islice(self.generations(), iterations)
for i, generation in enumerate(game_iter):
print(f'generation:{i + 1}')
self.display_grid(generation)
def generations(self):
current_grid = copy.deepcopy(self.grid)
while True:
next_grid = copy.deepcopy(current_grid)
for i, row in enumerate(current_grid):
for j, cell in enumerate(row):
position = i, j
neighbours = list(
self.get_neighbours(current_grid, position))
count = len(neighbours)
if cell:
# Death
if count < 2 or count > 3:
next_grid[i][j] = False
else:
# Birth
if count == 3:
next_grid[i][j] = True
yield next_grid
current_grid = next_grid
def get_directions(self, position: tuple):
i, j = position
# Top-Left
yield i - 1, j - 1
# Top
yield i - 1, j
# Top-Right
yield i - 1, j + 1
# Left
yield i, j - 1
# Right
yield i, j + 1
# Bottom-Left
yield i + 1, j - 1
# Bottom
yield i + 1, j
# Bottom-Right
yield i + 1, j + 1
def get_neighbours(self, grid, position: tuple):
for neighbour in self.get_directions(position):
i, j = neighbour
# Boundaries
if (i < self.height and i >= 0) and (j < self.width and j >= 0):
if grid[i][j]:
yield neighbour
def display_grid(self, grid):
for row in grid:
for column in row:
print(int(column), end=' ')
print()
try:
width = int(input("Width:"))
height = int(input("Height:"))
if width < 0 or height < 0:
raise ValueError("can't be negative")
data = []
print("Enter Initial Matrix:")
for i in range(height):
row = []
rowData = map(int, input().split())
for j, value in enumerate(rowData):
if j >= width:
raise ValueError("width exceeded")
if value == 0:
row.append(False)
elif value == 1:
row.append(True)
else:
raise ValueError("either 1 or 0")
data.append(row)
iterations = int(input("Enter number of iterations:"))
grid = GameOfLife(data, width, height)
grid.game(iterations)
except ValueError as e:
print("Value must be a positive integer,", e)
@sarathsp06
Copy link

Looks good ,will have a look

@sarathsp06
Copy link

data validation is missing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment