How to detect mouse clicks in Pygame
Here in this tutorial, we will learn how to detect mouse clicks in Python with the help of pygame which is a very widely used library for making games with a very good graphical user interface.
Creating a basic display using pygame
First of all, we will be importing pygame in our code, it will help us in creating the game screen, exiting it, and updating it in case of any changes.
import pygame background = pygame.display.setmode((500, 350)) def function: while True: for i in pygame.event.get(): if i.type == pygame.QUIT: return pygame.display.update() function() pygame.quit()
This is the basics of any pygame project that includes :
- pygame.display.setmode(): For defining the screen and its dimensions.
- pygame.event.get(): For getting all the events that happen during the game.
- pygame.Quit: Helps us quit the game if it’s not running.
- pygame.display.update(): Will update the game according to the changes made.
- pygame.quit(): To actually exit from the game.
Detecting mouse clicks in pygame
To detect the mouse click we just need to add a simple ‘if’ statement stating if the mouse button is clicked.
def function(): count = 0 while True: for i in pygame.event.get(): if i.type == pygame.QUIT: return #For detecting mouse click if i.type == pygame.MOUSEBUTTONDOWN: count += 1 print('clicked',count) pygame.display.update()
So in the function which was defined earlier, we just added an event that states that if the mouse is pressed then “clicked” is supposed to print on the output screen; Along with that, we have also defined a variable named “count” which will keep a count of how many time the mouse has been clicked.
Suppose the mouse was clicked 4 times so the output will look something like this.
clicked 1 clicked 2 clicked 3 clicked 4
Thus we have detected mouse clicks in Python using pygame.
Also read: Simulate elliptical orbit using Pygame