Pygame – Random Movement of Object
Prerequisite: How to draw rectangle in Pygame?
In this article, we will learn how we can add random movements in objects using PyGame in Python.
Random movement in a single object
Syntax: random.randint(a, b)
a and b : Two integers
Returns: Return a random integer that lies between a and b.
First, a frame with necessary adjustments is created, then an object is placed on the window to depict movement. Now by using randint() and setting other relevant parameters we can change the position of the object randomly.
Example: Random movement in one object
Random movement in more than one object
To add random movement in more than one object we are going to create separate speed and direction variables for the objects. Then we are going to check if the objects are colliding or not with the help of colliderect() method.
Syntax: pygame.Rect.colliderect(rect1 , rect2)
It will take two rects as its parameters.
Returns true if any portion of either rectangle overlap.
Example: Random movement in two objects
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