import life
A console based implementation of Conway’s Game of Life in Python.
As fascinating as it is useless.
#!/usr/bin/python
import sys
import random
import time
import os
import copy
WIDTH = 32
HEIGHT = 16
class Grid:
def __init__(self, width, height):
self.width = width
self.height = height
self.create_blank_grid()
def create_blank_grid(self):
self.grid = []
for x in range(0, self.width):
self.grid.append([0 for y in range(0, self.height)])
def seed(self, chance = 0.4):
for x in range(0, self.width):
for y in range(0, self.height):
if random.random() < chance:
self.grid[x][y] = 1
else:
self.grid[x][y] = 0
def add_glider(self):
self.grid[1][0] = 1
self.grid[2][1] = 1
self.grid[0][2] = 1
self.grid[1][2] = 1
self.grid[2][2] = 1
def __str__(self):
buffer = ''
for y in range(0, self.height):
for x in range(0, self.width):
str = ' '
if self.grid[x][y] == 1:
str = '#'
buffer += str
buffer += '\n';
buffer += '\n';
return buffer
def get_number_neighbours(self, x, y):
def get_value(i,j):
try:
return self.grid[i][j]
except:
return 0
number_neighbours = get_value(x-1, y-1) + get_value(x, y-1) + get_value(x+1, y-1) + \
get_value(x-1, y) + get_value(x+1, y) + \
get_value(x-1, y+1) + get_value(x, y+1) + get_value(x+1, y+1)
return number_neighbours
def tick(self):
new_grid = copy.deepcopy(self.grid)
for x in range(0, self.width):
for y in range(0, self.height):
number_neighbours = self.get_number_neighbours(x,y)
if self.grid[x][y] == 1:
if number_neighbours < 2:
new_grid[x][y] = 0
elif number_neighbours > 3:
new_grid[x][y] = 0
else:
if number_neighbours == 3:
new_grid[x][y] = 1
self.grid = new_grid
if __name__ == "__main__":
grid = Grid(WIDTH, HEIGHT)
# chance for a cell to be 'alive'
grid.seed(0.2)
# grid.add_glider()
# 100 generations
for x in range(0, 100):
os.system('clear')
print grid
grid.tick()
time.sleep(1)