Adding Boundary to an Object in Pygame
Boundaries to any game are very important. In snake games, space invaders, ping pong game, etc. the boundary condition is very important. The ball bounces at the boundaries of the screen in ping pong games.
So, the idea behind this boundaries is to change the position of the ball or object in reverse direction as soon as it hits the wall.
Let us see how to add boundary for a game in which a ball bounces off that boundary.
1. First of all, we will make the PyGame window.
2. Now, we are creating a ball. The ball is just a circle drawn on the screen. That will be written in a while loop. Here we are declaring its position and its speed. Initially, the ball will be placed at the center (width/2 and height/2). Then we will increase the speed of the ball by respective values of XChange and YChange. As both X and Y directions are changing, the ball will move in a diagonal direction and its further path will be dependent on the colliding body.
3. Now we will start the basic game running loop. We are also giving a background color to our screen.
4. Here comes the major part of our game. We are providing a condition that if the ball’s X Position is greater than the width of the screen or less than 0 (i.e if the ball is colliding or coming at its right or left end of the screen), then we multiply the X direction speed by negative 1. It means that the direction is reversed. If the ball is coming at a speed of 3 pixels, then on colliding at left or right wall, it’s speed will be -3 pixels, i.e in the reverse direction, and again when it hits the walls, then again its speed will be positive 3, i.e reverse of -3. Hence, this will give a boundary to a ball.
Also, the same logic will be applied for the upper and the lower wall.
If the ball’s Y value is greater than the screen’s height or less than 0, then reverse its direction.
And then we move the ball by incrementing the position of the ball by XChange and YChange respectively.
(the code below is under the gaming loop)
5. Now, we will be drawing the ball in the while loop so that it will be displayed in each loop. We are drawing the circle at the ballX and ballY position, so that we the ball’s X and Y position are incrementing in each loop and the ball will be drawn at next position in each loop and hence the ball will move inside the screen. And at the end we update the screen.
This is how we add a boundary to an object in PyGame.
The complete code is as follows :
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