Menu
CoddyTech

Drag the Crate

Part of the The Game Loop section of Coddy's Pygame journey. Lesson 17 of 35.

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.

challenge icon

Challenge

Medium

Let the player drag the crate.

  1. Before the loop, make crate = pygame.Rect(40, 230, 60, 60) and dragging = False.
  2. On MOUSEBUTTONDOWN, set dragging = True when crate.collidepoint(event.pos). On MOUSEBUTTONUP, set it to False.
  3. On MOUSEMOTION while dragging, call crate.move_ip(event.rel).
  4. Before drawing the gem, draw crate in brown (150, 100, 50).

Press Play and drag the crate: it follows the pointer. Then Check.

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