Skip to content

Instantly share code, notes, and snippets.

@ReeceHub
Created July 21, 2017 16:06
Show Gist options
  • Save ReeceHub/200f6b0ad2c9c1e7a4d82957c8e6ebce to your computer and use it in GitHub Desktop.
Save ReeceHub/200f6b0ad2c9c1e7a4d82957c8e6ebce to your computer and use it in GitHub Desktop.
import time
def next_generation(input):
mygrid = Grid(input)
mygrid.pretty_print()
nex_gen_grid = mygrid._next_generation()
return nex_gen_grid.dump()
class Grid:
def __init__(self, input):
self.rows = input.split('\n')[1:]
@staticmethod
def from_rows(rows):
new_grid = Grid('')
new_grid.rows = rows
return new_grid
def _next_generation(self):
g = []
for i, row in enumerate(self.rows):
new_grid = ''
for j, cell in enumerate(row):
new_grid += self.find_cell_results(i, j)
g.append(new_grid)
return Grid.from_rows(g)
def find_cell_results(self, i, j):
list_of_coords = self.get_neighbour_coords(i ,j)
count = sum([self.check_for_life(coord) for coord in list_of_coords])
if count in [2, 3] and self.check_for_life((i ,j)):
return '*'
elif count == 3 and not self.check_for_life((i, j)):
return '*'
else:
return '.'
def get_neighbour_coords(self, i, j):
all_directions = [
(1, 1),
(-1, -1),
(1, -1),
(-1, 1),
(1, 0),
(-1, 0),
(0, 1),
(0, -1)
]
all_neighbour_coords = map (lambda (x, y): (i + x, j + y) , all_directions)
return all_neighbour_coords
def check_for_life(self, coord):
try:
if coord[0] < 0 or coord[1] < 0:
return 0
if self.rows[coord[0]][coord[1]] == '*':
return 1
else:
return 0
except IndexError:
return 0
def dump(self):
size = str(len(self.rows[0])) + ' ' + str(len(self.rows))
gridstr = '\n'.join(self.rows)
return "\n".join([size, gridstr])
def pretty_print(self):
print('-' * (len(self.rows)) * 2)
for row in self.rows:
print(' '.join(row))
print('-' * (len(self.rows)) * 2)
if __name__ == '__main__':
game_in = "10 10\n..*..***.*\n**********\n.**..**.*.\n****......" + \
"\n......*...\n..*..***.*\n**********\n.**..**.*.\n****......\n......*..."
for t in range(100):
next_gen = next_generation(game_in)
game_in = next_gen
time.sleep(0.1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment