Menu
CoddyTech

Click the Gem

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

get_pos says where the pointer is. A click is an event: when a mouse button goes down, the event loop receives one pygame.MOUSEBUTTONDOWN event in that frame. Its event.pos is where the click landed.

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        running = False
    elif event.type == pygame.MOUSEBUTTONDOWN:
        x, y = event.pos
        if gx <= x <= gx + 30 and gy <= y <= gy + 30:
            score += 1

The gem fits in a 30 by 30 square from (gx, gy). A click is on it when x is between the square's left and right sides and y between its top and bottom. Python lets you write gx <= x <= gx + 30 for "x is from gx to gx + 30".

A collected gem jumps somewhere new with random.randint, and a for loop draws the score as a row of small pink squares, one per point.

challenge icon

Challenge

Easy
  1. Add import random at the top and score = 0 before the loop.
  2. On MOUSEBUTTONDOWN, when event.pos is inside the square from (gx, gy) to (gx + 30, gy + 30): add 1 to score, set gx to random.randint(15, 435) and gy to random.randint(55, 315).
  3. After the gem, draw the score: for each i in range(score), a pink (240, 110, 180) rect at (10 + 10 * i, 14, 8, 8).

Try it yourself

import pygame

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

gx, gy = 225, 165

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((30, 30, 46))
    gem_points = [(gx + 15, gy), (gx + 30, gy + 15), (gx + 15, gy + 30), (gx, gy + 15)]
    pygame.draw.polygon(screen, (80, 220, 255), gem_points)
    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