Pygame: Responding to the mouse event Cheat Sheet

Pygame’s event loop registers an event any time the mouse moves, or a mouse button is pressed or released.

Responding to the mouse button

for event in pg.event.get():
    if event.type == pg.MOUSEBUTTONDOWN:
        ship.fire_bullet()

Finding the mouse position

The mouse position is returned as a tuple

mouse_pos = pg.mouse.get_pos()

Clicking a button

You might want to know if the cursor is over an object such as a button. The rect.collidepoint() method returns true when a point is inside a rect object.

if button_rect.collidepoint(mouse_pos):
     start_game()

Hiding the mouse

pg.mouse.set_visible(False)

Leave a Reply

Your email address will not be published. Required fields are marked *