Rects and Collision

Goals

  • Extract a Rect from a Pygame Surface object (text) to draw a bounding box

  • Use Rect.collidepoint() to detect collision between the rect and the mouse (a point)

  • Use a Rect to keep track of “sprite” size and location

  • Use Rect.colliderect() to detect collision between two Rect objects.

Starter code

Pygame Template

Video Tutorial

What you need to do

  • Add another mouse over effect

  • Add a click event using MOUSEBUTTONDOWN to the text using .collidepoint()

  • Add another enemy, when they collide with the player, the player absorbs the enemies. For each 1 size lost by enemies, the player gains 0.5 size.

  • Come up with a random (related) idea

Final Code

 1# Rects and Collision - Final
 2
 3import pygame
 4from pygame.locals import K_ESCAPE, KEYDOWN, QUIT
 5
 6pygame.init()
 7pygame.font.init()
 8
 9
10WIDTH = 640
11HEIGHT = 480
12SIZE = (WIDTH, HEIGHT)
13
14screen = pygame.display.set_mode(SIZE)
15clock = pygame.time.Clock()
16
17# ---------------------------
18# Initialize global variables
19
20circle_x = 200
21circle_y = 200
22some_font = pygame.font.SysFont('Arial', 50)
23
24some_text = some_font.render('Hello', False, (0, 0, 0))
25text_rect = some_text.get_rect()
26text_rect.x = WIDTH // 2
27text_rect.y = HEIGHT // 2
28
29player = pygame.Rect(50, 50, 100, 100)
30enemy = pygame.Rect(400, 50, 100, 100)
31
32# ---------------------------
33
34running = True
35while running:
36    # EVENT HANDLING
37    for event in pygame.event.get():
38        if event.type == KEYDOWN:
39            if event.key == K_ESCAPE:
40                running = False
41        elif event.type == QUIT:
42            running = False
43    
44    # GAME STATE UPDATES
45    # All game math and comparisons happen here
46    enemy.x -= 1
47
48    if player.colliderect(enemy):
49        enemy.inflate_ip(-1, -1)
50
51    # DRAWING
52    screen.fill((255, 255, 255))  # always the first drawing command
53
54    # BOUNDING BOX
55    mouse_point = pygame.mouse.get_pos()
56
57    if text_rect.collidepoint(mouse_point):
58        pygame.draw.rect(screen, (0, 0, 128), text_rect.inflate(20, 20), 2)
59
60    # DRAW TEXT
61    screen.blit(some_text, text_rect.topleft)
62
63    # ENEMY AND PLAYER
64    pygame.draw.rect(screen, (0, 128, 0), player)
65    pygame.draw.rect(screen, (128, 0, 0), enemy)
66
67
68    pygame.draw.circle(screen, (0, 0, 255), (circle_x, circle_y), 30)
69
70    # Must be the last two lines
71    # of the game loop
72    pygame.display.flip()
73    clock.tick(30)
74    #---------------------------
75
76
77pygame.quit()