Lists in Pygame =============== Goals ----- - Make use of lists to store the locations of multiple objects. - Save some squares in a list - Draw the squares on the screen - Add squares by clicking the locations Starter code ------------ - :doc:`pygame-template` What you need to do ------------------- 1. Better drawing - use pygame.mouse.get_pressed() to check each frame, in game state updates, if a mouse buttin is currently being pressed. Then if it is, get the mouse position with pygame.mouse.get_pos() and draw a square there. 2. Timed squares - Create a variable to record the frame count. In the loop do frame count += 1. If the frame count is divisible by 30 (frames % 30 == 0), random x and y and add that "square" to the list. 3. Move the squares - In the game updates create another loop to change the squares x and y position. 4. ADVANCED Square defense - Separate the randomized moving squares (the enemies) and the user click-generated squares (defenders) into different lists. When an enemy and a defender overlap, they both dissappear. If an enemy reaches a particular side of the screen, you lose or lose a life. You may wish to convert your squares to pygame.Rect so you can use pygame.Rect.colliderect(other_rect). Final Code ---------- .. code-block:: python :linenos: :emphasize-lines: 21-27, 40-46, 54-57 # Lists in pygame import pygame from pygame.constants import MOUSEBUTTONDOWN from pygame.locals import K_ESCAPE, KEYDOWN, QUIT pygame.init() WIDTH = 640 HEIGHT = 480 SIZE = (WIDTH, HEIGHT) screen = pygame.display.set_mode(SIZE) clock = pygame.time.Clock() # --------------------------- # Initialize global variables # position [int, int] -> [x, y] squares = [ [50, 50], [200, 300], [500, 400], [200, 50], [500, 100] ] # --------------------------- running = True while running: # EVENT HANDLING for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_ESCAPE: running = False elif event.type == QUIT: running = False elif event.type == MOUSEBUTTONDOWN: mouse_x = event.pos[0] mouse_y = event.pos[1] print(mouse_x, mouse_y) new_square = [mouse_x, mouse_y] squares.append(new_square) # GAME STATE UPDATES # DRAWING screen.fill((255, 255, 255)) # always the first drawing command for square in squares: x = square[0] y = square[1] pygame.draw.rect(screen, (200, 0, 0), (x, y, 30, 30)) # Must be the last two lines # of the game loop pygame.display.flip() clock.tick(30) #--------------------------- pygame.quit()