Menu
CoddyTech

Drag the Crate

Part of the The Game Loop section of Coddy's Pygame journey. Lesson 16 of 32.

A drag takes three events. The button goes down on the crate (MOUSEBUTTONDOWN), the pointer moves (MOUSEMOTION, many times), and the button comes up (MOUSEBUTTONUP). A variable remembers whether a drag is going on in between:

elif event.type == pygame.MOUSEBUTTONDOWN:
    if crate.collidepoint(event.pos):
        dragging = True
elif event.type == pygame.MOUSEBUTTONUP:
    dragging = False
elif event.type == pygame.MOUSEMOTION and dragging:
    crate.move_ip(event.rel)

A MOUSEMOTION event's event.rel is how far the pointer moved since the last one, as (x, y). crate.move_ip(event.rel) moves the crate by the same amount, so the spot you grabbed stays under the pointer.

The crate is drawn after the gem, so it can hide it. A press on the crate must then not collect the gem under it: test the crate first, and the gem with elif, so only one of them takes the press.

challenge icon

Challenge

Medium
  1. Before the loop, make crate = pygame.Rect(40, 230, 60, 60) and dragging = False.
  2. On MOUSEBUTTONDOWN, set dragging = True when the press is on the crate; otherwise (elif) test the gem as before.
  3. Set dragging = False on MOUSEBUTTONUP. On MOUSEMOTION while dragging, move the crate by event.rel.
  4. After the gem's outline, draw the crate in brown (150, 100, 50), with a (110, 70, 35) edge 3 pixels wide.

Try it yourself

import random
import pygame

pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Gem Hunt")
clock = pygame.time.Clock()

gem = pygame.Rect(225, 165, 30, 30)
score = 0

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if gem.collidepoint(event.pos):
                score += 1
                gem.x = random.randint(15, 435)
                gem.y = random.randint(55, 315)

    screen.fill((30, 30, 46))
    gem_points = [gem.midtop, gem.midright, gem.midbottom, gem.midleft]
    pygame.draw.polygon(screen, (80, 220, 255), gem_points)
    if gem.collidepoint(pygame.mouse.get_pos()):
        pygame.draw.rect(screen, (255, 196, 0), gem.inflate(10, 10), 2)
    for i in range(score):
        pygame.draw.rect(screen, (240, 110, 180), (10 + 10 * i, 14, 8, 8))
    mouse_x, mouse_y = pygame.mouse.get_pos()
    pygame.draw.circle(screen, (240, 240, 240), (mouse_x, mouse_y), 10, 2)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in The Game Loop

Practice on your own: Pygame playground