""" by Kristina Striegnitz May 7, 2009 """ import pygame import random def initialize(): """ This function sets some global constants (i.e., the values of these global variables never change). """ pygame.init() # set up the display window global width, height, screen width = 800 height = 800 screen = pygame.display.set_mode((width,height)) def create_grid(rows, cols): """ Creates a list of lists representing a rows x cols sized grid. Each cell holds an integer of value 0. Returns the grid. """ grid = [] for r in range(0,rows): row = [0] * cols grid = grid + [row] return grid def run_game(): # size of grid rows = 30 cols = 30 grid = create_grid(rows, cols) # values for drawing the grid. cell_width = 20 x_offset = 20 y_offset = 20 padding = 3 clock = pygame.time.Clock() keepGoing = True while (keepGoing): dt = clock.tick() # go through all events that happened and check ... for event in pygame.event.get(): # ... whether the event was a quit event if event.type == pygame.QUIT: keepGoing = False # ... whether the event was a mouse click elif event.type == pygame.MOUSEBUTTONDOWN: (mouse_x, mouse_y) = event.pos # Find out whether mouse click was over one of the grid cells. # If so, flip the value of that cell. if (mouse_x >= x_offset and mouse_x <= x_offset + (padding + cell_width) * rows and mouse_y >= y_offset and mouse_x <= y_offset + (padding + cell_width) * cols): col = (mouse_x - x_offset) / (cell_width + padding) row = (mouse_y - y_offset) / (cell_width + padding) if grid[row][col] == 0: grid[row][col] = 1 else: grid[row][col] = 0 screen.fill(pygame.color.Color("navy")) # draw the grid # cell value 0, becomes orange; cell value 1 becomes darkred for r in range(0,rows): for c in range(0,cols): if grid[r][c] == 0: color = pygame.color.Color("orange") else: color = pygame.color.Color("darkred") x = x_offset + (padding + cell_width) * c y = y_offset + (padding + cell_width) * r pygame.draw.rect(screen, color, (x, y, cell_width, cell_width)) pygame.display.update() def done(): pygame.quit() def main(): initialize() run_game() done() main()