Skip to content

Instantly share code, notes, and snippets.

@eightbitraptor
Created November 27, 2012 07:28
Show Gist options
  • Save eightbitraptor/4152943 to your computer and use it in GitHub Desktop.
Save eightbitraptor/4152943 to your computer and use it in GitHub Desktop.
A Naive (and broken) derp of the Game of Life in Python.
import time
import copy
from itertools import *
class Cell(object):
alive = False
def __str__(self):
return 'o' if self.alive else '.'
def live(self):
self.alive = True
def die(self):
self.alive = False
def dead(self):
return False if self.alive else True
class Board(object):
board = []
width = None
height = None
def __init__(self, width=40, height=40):
self.width = width
self.height = height
self.board = [[Cell() for c in xrange(width)] for x in xrange(height)]
self.activate_starting()
def __str__(self):
return str('\n'.join([''.join([str(c) for c in row]) for row in
self.board]))
def activate_starting(self):
self.board[self.height/2][self.width/2].live()
self.board[self.height/2][self.width/2 + 1].live()
self.board[self.height/2 + 1][self.width/2].live()
self.board[self.height/2 + 1][self.width/2 - 1].live()
self.board[self.height/2 + 2][self.width/2].live()
def take_turn(self):
self.board_copy = copy.deepcopy(self.board)
for x in range(self.width - 1 ): #width
for y in range(self.height - 1): #height
self.analyze_surroundings_in_board(x, y)
self.board = self.board_copy
def checking_grid(self, x, y):
coords_x = [x-1, x, x+1]
coords_y = [y-1, y, y+1]
return product(coords_y, coords_x)
def analyze_surroundings_in_board(self, x, y):
grid = self.checking_grid(x,y)
live_neighbours = 0
for coords in grid:
if coords == (x,y) or coords[0] < 0 or coords[1] < 0:
pass
else:
if self.board[coords[0]][coords[1]].alive:
live_neighbours += 1
self.transition(x, y, live_neighbours)
def transition(self, x, y, live_neighbours):
cell = self.board_copy[y][x]
if cell.dead():
if live_neighbours == 3:
cell.live()
else:
if live_neighbours < 2:
cell.die()
elif live_neighbours > 3:
cell.die()
class Game(object):
def __init__(self):
self._board = Board()
def play(self, turns=5):
#exit(0)
for i in range(turns):
print chr(27) + "[2J"
self._board.take_turn()
print self._board
time.sleep(0.2)
if __name__ == '__main__':
game = Game()
game.play()
exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment