Menu
CoddyTech

Gem Hunt

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

A round of Gem Hunt lasts 30 seconds. Count the time in frames: at 60 frames a second, 10 seconds are 600 frames.

time_left = 600

while running:
    # events
    if time_left > 0:
        time_left -= 1

When time_left reaches 0, the game stops taking clicks and drags, and the score row shows the result: add and time_left > 0 to an event's test.

A bar at the top shows the time left. Its width is the share of the round still to go: for a bar up to 200 pixels in a 600-frame round, 200 * time_left // 600 is 200 at the start, 100 halfway and 0 at the end.

challenge icon

Challenge

Medium

Give each round 30 seconds.

  1. Before the loop, set time_left = 1800. After the events, take 1 from it while it is above 0.
  2. Add and time_left > 0 to the MOUSEBUTTONDOWN and MOUSEMOTION tests.
  3. After the score row, draw a green (120, 200, 120) rect at (0, 0, 480 * time_left // 1800, 6).

Press Play: the green bar shrinks, and after 30 seconds clicks do nothing. 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)
crate.center = gem.center
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)
                crate.center = gem.center
        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()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in The Game Loop

Practice on your own: Pygame playground