# https://gist.github.com/bennuttall/6952575 # modified a lot import random, simplegui # cells width = 15 height = 15 scale = 9 # pixels per cell neighbour_cells = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] def evolve_cell(alive, neighbours): return neighbours == 3 or (alive and neighbours == 2) def count_neighbours(grid, x, y): count = 0 for ox,oy in neighbour_cells: dx = x + ox dy = y + oy # no wrap if dx >= 0 and dx < width and dy >= 0 and dy < height: count += grid[dx][dy] return count def make_random_grid(x, y): grid = [] for r in range(x): row = [] for c in range(y): row.append(random.randint(0,1)) grid.append(row) return grid # use the old grid as the new one def evolve(grid, new_grid): for r in range(width): for c in range(height): cell = grid[r][c] neighbours = count_neighbours(grid, r, c) new_grid[r][c] = 1 if evolve_cell(cell, neighbours) else 0 # store the outgoing world for next time return (new_grid, grid) # Handler to draw on canvas def draw(canvas): global world, oldworld for x in range(width): for y in range(height): alive = world[x][y] col = 'black' if alive else 'white' try: # canvas.draw_circle(center_point, radius, line_width, line_color, fill_color) canvas.draw_circle([x * scale + scale//2, y * scale + scale//2], scale//2, 1, '#ccc', col) except Exception as e: # I don't get this! Says that col has no value col = 'red' canvas.draw_circle([x * scale + scale//2, y * scale + scale//2], scale//2, 1, col, col) # store the outgoing world for next time world, oldworld = evolve(world, oldworld) def init(): global world, oldworld # make two arrays which we use alternately world = make_random_grid(width, height) oldworld = make_random_grid(width, height) def main(): # Create a frame and assign callbacks to event handlers frame = simplegui.create_frame("Conway Life", width * scale, height * scale) frame.set_canvas_background('white') frame.set_draw_handler(draw) init() # Start the frame animation frame.start() if __name__ == '__main__': main()