How to add Custom Events in Pygame?
In this article, we will see how to add custom events in PyGame.
PyGame library can be installed using the below command:
pip install pygame
Although PyGame comes with a set of events (Eg: KEYDOWN and KEYUP), it allows us to create our own additional custom events according to the requirements of our game. Custom events increase the control and flexibility we have over our game. A custom event is the same as creating a User-defined event.
<event_name> = pygame.USEREVENT + 1
# Here ADDITION and SUBTRACTION is the event name
ADDITION = pygame.USEREVENT + 1
SUBTRACTION = pygame.USEREVENT + 2
Now, how do we publish our custom events once they are created? This can be done in two ways:
- Using pygame.event.post() method.
- Using pygame.time.set_timer() method.
Using pygame.event.post() method
We can directly post our events using pygame.event.post() method. This method adds our event to the end of the events on the queue. In order to execute this, we need to convert our event to Pygame’s event type inorder to match the attributes of the post method and avoid errors.
# Step 1 – Convert event into event datatype of pygame
ADD_event = pygame.event.Event(event)
# Step 2 – Post the event
pygame.event.post(ADD_event) # event_name as parameter
Using pygame.time.set_timer() method
Broadcasting the event periodically by using PyGame timers. Here, we’ll be using another method to publish the event by using set_timer() function, which takes two parameters, a user event name and time interval in milliseconds.
# event_name, time in ms
Note: In this, we don’t need to convert the user-defined event into PyGame event datatype.
Now to create a plot with custom events firstly the attributes for the screen should be set as per requirement. Then create an event and convert it to PyGame event datatype. Now add code for your operations that will generate a custom event.
In the given implementation both of the approaches have been handled.
In the above implementation, we have used the .post() method to inflate/deflate the box when the cursor is on the top of the box and .set_timer() method to switch background color after every 500ms.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course