import pygame 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 + [0] grid = grid + [row] return grid def draw_grid(win, grid, x_offset, y_offset, 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) + x_offset y = row_index*(size+margin) + y_offset pygame.draw.rect(win,color,(x, y, size, size)) def run_game(): ## Initialize the pygame submodules and set up the display window. pygame.init() width = 650 height = 620 my_win = pygame.display.set_mode((width,height)) ## Initialize game objects. rows = 50 cols = 50 x_offset = 0 y_offset = 0 margin = 2 size = 10 grid = create_grid(50, 50) ## 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: (mouse_x, mouse_y) = event.pos # mouse click on the grid if (mouse_x >= x_offset and mouse_x <= x_offset + (margin + size) * rows and mouse_y >= y_offset and mouse_x <= y_offset + (margin + size) * cols): col = (mouse_x - x_offset) / (size + margin) row = (mouse_y - y_offset) / (size + margin) if grid[row][col] == 0: grid[row][col] = 1 else: grid[row][col] = 0 ## Update game objects. ## Draw picture and update display. my_win.fill(pygame.color.Color("lightblue")) draw_grid(my_win, grid, x_offset, y_offset, size, margin) pygame.display.update() ## The game loop ends here. pygame.quit() ## Call the function run_game. run_game()