Menu
CoddyTech

Click the Gem

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

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:
            print("Got it!")

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".

random.randint(a, b) picks a whole number from a to b, so a caught gem can jump somewhere new.

challenge icon

Challenge

Easy

Make the gem jump away when you click it.

  1. Add import random at the top.
  2. In the event loop, on MOUSEBUTTONDOWN, when event.pos is inside the square from (gx, gy) to (gx + 30, gy + 30), set gx = random.randint(15, 435) and gy = random.randint(55, 315).

Press Play and click the gem: it jumps somewhere new. Then Check.

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