## ## gol_display.py ## ## by Kristina Striegnitz ## ## version 2/18/2010 ## ## A helper function for visualizing the game of life. ## import pygame def run_game(grid, cell_size, on_click, next_gen): """ This function takes a grid of dead and life cells (represented as a list of lists; dead cells contain a 0, life cells a 1), the size that we want to use to represent each cell, the name of a function to be called when the user clicks on the grid, and the function to be called to calculate what the next generation looks like. """ ## Initialize the pygame submodules and set up the display window. pygame.init() margin = 2 width = 200 height = 200 go_button_radius = 20 if len(grid) > 0: height = len(grid) * (cell_size + margin) + margin if len(grid[0]) > 0: width = len(grid[0]) * (cell_size + margin) + 2*margin + 2*go_button_radius # some grid features rows = len(grid) if rows > 0: cols = len(grid[0]) # the go button go_radius = go_button_radius go_x = width - go_radius - margin go_y = go_radius + margin go = False my_win = pygame.display.set_mode((width,height)) clock = pygame.time.Clock() timer = 0 ## The game loop starts here. keepGoing = True while (keepGoing): ## Handle events. for event in pygame.event.get(): if event.type == pygame.QUIT: keepGoing = False elif event.type == pygame.MOUSEBUTTONDOWN: mousex, mousey = pygame.mouse.get_pos() # mouse click on the grid if (mousex >= margin and mousex <= (margin + cell_size) * cols and mousey >= margin and mousey <= (margin + cell_size) * rows): col = (mousex - margin) / (cell_size + margin) row = (mousey - margin) / (cell_size + margin) # on mouse click call event handler function on_click grid = on_click(grid, row, col) # mouse click on the start/stop button if (mousex > go_x - go_radius and mousex < go_x + go_radius and mousey > go_y - go_radius and mousey < go_y + go_radius): if go: go = False else: go = True ## Update game objects. dt = clock.tick() timer = timer + dt if go and timer > 200: grid = next_gen(grid) #, rows, cols) timer = 0 ## Draw picture and update display. my_win.fill(pygame.color.Color("lightblue")) draw_grid(my_win, grid, cell_size, margin) pygame.draw.circle(my_win, pygame.color.Color("green"), (go_x, go_y), go_radius) pygame.display.update() ## The game loop ends here. pygame.quit() def draw_grid(win, grid, size, margin): """ This function takes a grid representation and draws it. 0 is represented as magenta, 1 as orange. """ for row_index in range(0,len(grid)): for col_index in range(0, len(grid[row_index])): if grid[row_index][col_index] == 0: color = pygame.color.Color("darkmagenta") else: color = pygame.color.Color("orange") x = col_index*(size+margin) + margin y = row_index*(size+margin) + margin pygame.draw.rect(win,color,(x, y, size, size))