## ## gol.py ## ## by Kristina Striegnitz ## ## version 2/12/2010 ## ## Conway's game of life. ## from gol_display import run_game ROWS = 20 COLS = 20 DEAD = 0 ALIFE = 1 def create_grid(rows, cols): """ This function creates and returns a list of lists, intended to represent a grid. All of the grid cells are filled with 0. """ grid = [] for r in range(0,rows): row = [] for c in range(0, cols): row = row + [DEAD] grid = grid + [row] return grid def read_grid_from_file(filename): global ROWS global COLS file_obj = open(filename, "r") ## ADD code here. ## Add code that reads the content of the file and builds a grid ## representations (list of lists) from it. 0 indicates DEAD and 1 ## ALIFE. file_obj.close() ROWS = len(grid) if ROWS > 0: COLS = len(grid[0]) return grid def play_gol(): grid = create_grid(ROWS, COLS) cell_size = 10 run_game(grid, cell_size, on_click, next_gen) def play_gol_file_input(filename): grid = read_grid_from_file(filename) cell_size = 10 run_game(grid, cell_size, on_click, next_gen) def on_click(grid, row, col): if grid[row][col] == DEAD: grid[row][col] = ALIFE else: grid[row][col] = DEAD return grid def life_neighbors(board,r,c): """ This function counts how many life neighbors a given cell in a Game of Life grid has. Parameters: the grid representation, the row number and column number we are interested in, the overall number of rows and columns. """ n = 0 for i in range(c-1,c+2): for j in range(r-1,r+2): if board[j%ROWS][i%COLS]==1 and (i != c or j != r): n += 1 return n def next_gen(grid): """ This function applies the Game of Life rules to a given grid. It returns the next generation of the grid. """ new_grid = create_grid(ROWS, COLS) for r in range(0,ROWS): for c in range(0,COLS): n = life_neighbors(grid,r,c) if grid[r][c]==ALIFE: if n < 2 or n > 3: new_grid[r][c] = DEAD else: new_grid[r][c] = ALIFE else: if n == 3: new_grid[r][c] = ALIFE else: new_grid[r][c] = DEAD return new_grid ## Start it: #play_gol_file_input("gol_input_mini.txt") play_gol_file_input("gol_glider_gun.txt")