Gem Under the Crate
Part of the The Game Loop section of Coddy's Pygame journey. Lesson 19 of 35.
Now the crate becomes the game. Each gem appears under the crate: drag the crate off and click the gem, and the crate moves onto the next one.
A Rect has a center, the point in its middle. Give one Rect another's centre and it sits right on top of it, whatever their sizes:
gem = pygame.Rect(300, 120, 30, 30)
crate = pygame.Rect(0, 0, 60, 60)
crate.center = gem.centerOnly crate moves, to (285, 105, 60, 60). Do this once before the loop for the first gem, and again each time a gem gets a new place.
Challenge
EasyHide each gem under the crate.
- Right after making
crate, setcrate.center = gem.center. - In the gem branch, after the new
gem.y, setcrate.center = gem.centeragain.
Press Play, drag the crate off and click the gem: the crate jumps onto the next one. 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)
crate = pygame.Rect(40, 230, 60, 60)
dragging = False
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 crate.collidepoint(event.pos):
dragging = True
elif gem.collidepoint(event.pos):
score += 1
gem.x = random.randint(15, 435)
gem.y = random.randint(55, 315)
elif event.type == pygame.MOUSEBUTTONUP:
dragging = False
elif event.type == pygame.MOUSEMOTION and dragging:
crate.move_ip(event.rel)
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)
pygame.draw.rect(screen, (150, 100, 50), crate)
pygame.draw.rect(screen, (110, 70, 35), crate, 3)
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