Menu
CoddyTech

Follow the Pointer

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

This chapter builds Gem Hunt, a game you play with the mouse. The light blue diamond is the gem: a polygon whose four corners are worked out from gx and gy.

pygame.mouse.get_pos() gives the pointer's position in the window as (x, y), measured from the top left corner like everything else. Read it in the loop and it is up to date in every frame:

mouse_x, mouse_y = pygame.mouse.get_pos()
pygame.draw.circle(screen, (240, 240, 240), (mouse_x, mouse_y), 10, 2)

The first line unpacks the tuple into two variables. The second draws a ring there, so the player sees what they point at. Draw it last, after the gem, or the gem covers it.

Read the position once, before the loop, and the ring stays where the pointer was when the game started.

challenge icon

Challenge

Easy
  1. In the loop, after drawing the gem, read the pointer's position with pygame.mouse.get_pos().
  2. Draw a white (240, 240, 240) ring there: a circle with radius 10 and width 2.

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)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in The Game Loop

Practice on your own: Pygame playground