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

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

 1# Lists in pygame
 2
 3import pygame
 4from pygame.constants import MOUSEBUTTONDOWN
 5from pygame.locals import K_ESCAPE, KEYDOWN, QUIT
 6
 7pygame.init()
 8
 9WIDTH = 640
10HEIGHT = 480
11SIZE = (WIDTH, HEIGHT)
12
13screen = pygame.display.set_mode(SIZE)
14clock = pygame.time.Clock()
15
16# ---------------------------
17# Initialize global variables
18
19# position [int, int] -> [x, y]
20
21squares = [
22    [50, 50],
23    [200, 300],
24    [500, 400],
25    [200, 50],
26    [500, 100]
27]
28
29# ---------------------------
30
31running = True
32while running:
33    # EVENT HANDLING
34    for event in pygame.event.get():
35        if event.type == KEYDOWN:
36            if event.key == K_ESCAPE:
37                running = False
38        elif event.type == QUIT:
39            running = False
40        elif event.type == MOUSEBUTTONDOWN:
41            mouse_x = event.pos[0]
42            mouse_y = event.pos[1]
43            print(mouse_x, mouse_y)
44
45            new_square = [mouse_x, mouse_y]
46            squares.append(new_square)
47
48    # GAME STATE UPDATES
49
50
51    # DRAWING
52    screen.fill((255, 255, 255))  # always the first drawing command
53
54    for square in squares:
55        x = square[0]
56        y = square[1]
57        pygame.draw.rect(screen, (200, 0, 0), (x, y, 30, 30))
58
59    # Must be the last two lines
60    # of the game loop
61    pygame.display.flip()
62    clock.tick(30)
63    #---------------------------
64
65
66pygame.quit()