What is the canonical way of making your sprites respond to mouse clicks in PyGame ?
Here's something simple, in my event loop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit_game()
[...]
elif ( event.type == pygame.MOUSEBUTTONDOWN and
pygame.mouse.get_pressed()[0]):
for sprite in sprites:
sprite.mouse_click(pygame.mouse.get_pos())
Some questions about it:
Thanks in advance
I usually give my clickable objects a click function, like in your example. I put all of those objects in a list, for easy iteration when the click functions are to be called.
when checking for which mousebutton you press, use the button property of the event.
import pygame
from pygame.locals import * #This lets you use pygame's constants directly.
for event in pygame.event.get():
if event.type == MOUSEBUTTONDOWN: #Better to seperate to a new if statement aswell, since there's more buttons that can be clicked and makes for cleaner code.
if event.button == 1:
for object in clickableObjectsList:
object.clickCheck(event.pos)
I would say this is the recommended way of doing it. The click only registers once, so it wont tell your sprite if the user is "dragging" with a button. That can easily be done with a boolean that is set to true with the MOUSEBUTTONDOWN event, and false with the MOUSEBUTTONUP. The have "draggable" objects iterated for activating their functions... and so on.
However, if you don't want to use an event handler, you can let an update function check for input with:
pygame.mouse.get_pos()
pygame.mouse.get_pressed().
This is a bad idea for larger projects, since it can create hard to find bugs. Better just keeping events in one place. Smaller games, like simple arcade games might make more sense using the probing style though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With