In this guide, we will be taking a look at how to utilize mouse input with PyGame.
To retrieve the position of the mouse, you can use the following line:
mousex, mousey = pygame.mouse.get_pos()
Of course, with the above line, you can access the x position of the mouse with mousex, and the y position of the mouse with mousey. Ensure this line is executed within the game loop, either in a dedicated update function, or directly within the loop.
Mouse clicks can be listened to by capturing the pygame.MOUSEBUTTONUP event. Let’s try this. In your update function/game loop, add the following code:
for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONUP: print("Mouse click detected.")
However, what if you want to distinguish which mouse button you clicked? You can use the event.button property to determine which mouse button was clicked. Here is a list of possible integers event.button can be:
For example, to detect mouse right clicks, you could add the following inside your pygame.MOUSEBUTTONUP if statement:
if event.button == 3: print("Right mouse button clicked")
If you wanted to check if the user is scrolling up, you can add the following code:
if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 4: print("Scrolling up")
To scroll up, you can check if event.button is equal to five.
if event.button == 5: print("Scrolling down")
Hopefully you have found this guide helpful. Mouse input can be extremely useful for adding interaction to your PyGame. If you would like to check out the rest of this series, you take a look at it here. To receive news regarding our latest tutorials and courses, you can subscribe to our newsletter here. Sharing this tutorial on your favorite social media platform would also be much appreciated, of course only if you found this guide useful.