Table of contents
1.
Introduction 
2.
Creating a Bouncing Ball Boundary
2.1.
Step-1: Creating Pygame Window
2.2.
Step-2: Creating the ball
2.3.
Step-3: Starting the game loop. 
2.4.
Step-4: Making the ball Bounce off the walls
3.
Frequently Asked Questions
3.1.
What does Flip () do in pygame?
3.2.
What does clock tick do in Python?
3.3.
What is Doublebuf?
3.4.
What is pygame surface?
4.
Conclusion
Last Updated: Mar 27, 2024

Adding boundary to an object in pygame

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction 

The importance of boundaries in any game cannot be overstated. The border condition is highly significant in snake games, space invaders, ping pong games, and other similar games. In ping pong games, the ball bounces off the screen's edges. As a result, the goal behind these boundaries is to reverse the position of the ball or item as soon as it collides with the wall.

Let's look at how to make a barrier for a game where a ball bounces off it.

Creating a Bouncing Ball Boundary

Step-1: Creating Pygame Window

# importing the module
import pygame
  
# instantiating the class
pygame.init()
  
# dimension of the screen
width = 700
height = 550
  
# colours
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
black = (0, 0, 0)
  
# creating a Screen
screen = pygame.display.set_mode((width, height))
  
# title of the screen
pygame.display.set_caption("Bouncy Ball")
You can also try this code with Online Python Compiler
Run Code

Step-2: Creating the ball

We're making a ball right now. The ball is nothing more than a circle on the screen. A while loop will be used to write this. We're announcing its location and speed here. The ball will be positioned in the centre (width/2 and height/2) at first. The ball's speed will then be increased by the respective values of XChange and YChange. The ball will move in a diagonal manner as both the X and Y axes change, and its further route will be determined by the impacting body.

# importing the module
import random
  
# declaring variables for the ball
ball_X = width/2 - 12
ball_Y = height/2 - 12
ball_XChange = 3* random.choice((1, -1))
ball_YChange = 3
ballPixel = 24
You can also try this code with Online Python Compiler
Run Code

Step-3: Starting the game loop. 

# gaming Loop
running = True
while running:
    # background color
    screen.fill(red)
    # to exit the loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
You can also try this code with Online Python Compiler
Run Code

Step-4: Making the ball Bounce off the walls

The most important part of our game is about to begin. If the ball's X Position is more than the width of the screen or less than 0 (i.e. if the ball collides or approaches the right or left end of the screen), then the X direction speed is multiplied by negative 1. It denotes a reversal of the direction. If the ball is travelling at 3 pixels per second, when it collides with the left or right wall, its speed will be -3 pixels per second, i.e. in the opposite direction, and when it collides with the walls again, its speed will be positive 3, i.e. the opposite of -3. As a result, a ball will have a boundary.

The upper and lower walls will also be treated in the same way.

Reverse the direction of the ball if its Y value is more than the screen's height or less than 0.

The ball is then moved by incrementing its position by XChange and YChange, respectively.

This is the whole code: 

# importing the modules
import pygame
import random
  
# instantiating the class
pygame.init()
    
# dimension of the screen
width = 700
height = 550
    
# colours
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
black = (0, 0, 0)
    
# creating a Screen
screen = pygame.display.set_mode((width, height))
  
# title of the screen
pygame.display.set_caption("Bouncy Ball")
  
# declaring variables for the ball
ball_X = width/2 - 12
ball_Y = height/2 - 12
ball_XChange = 3* random.choice((1, -1))
ball_YChange = 3
ballPixel = 24
  
# gaming Loop
running = True
while running:
    # background color
    screen.fill(red)
    # to exit the loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    # bouncing the ball
    if ball_X + ballPixel >= width or ball_X <= 0:
        ball_XChange *= -1
    if ball_Y + ballPixel >= height or ball_Y <= 0:
        ball_YChange *= -1
    # moving the ball
    ball_X += ball_XChange
    ball_Y += ball_YChange
    # drawing the ball
    ballImg = pygame.draw.circle(screen, (0,0,255), (int(ball_X), int(ball_Y)), 15)
    pygame.display.update()
You can also try this code with Online Python Compiler
Run Code

Now you will be able to make the boundaries around a ball and the ball will bounce off those boundaries. 

Frequently Asked Questions

What does Flip () do in pygame?

For software displays, use flip(). It just permits a section of the screen to be refreshed, rather than the complete screen. If no argument is given, the Surface area is updated in the same way as pygame. display does.

What does clock tick do in Python?

tick():Once per frame, this method should be invoked. It will calculate the number of milliseconds since the previous call. If you pass the optional framerate argument, the function will delay the game so that it runs slower than the ticks per second specified.

What is Doublebuf?

As stated in the tag's description, double-buffering involves applying all of the draw routines to a separate block of memory and then copying that block (buffer) to video memory in one operation. If you don't do this, you'll end up with graphical artefacts.

What is pygame surface?

A pygame Surface can represent any image. Surface has a set pixel format and resolution. Colour palettes are used to map 8-bit pixels to 24-bit colour on surfaces.Call pygame. Surface() pygame object for representing images to create a new image object.

Conclusion

So, in a nutshell, We saw how we can create boundaries in the pygame library and even make balls to bounce off that boundary. 

Check out our Coding Ninjas Studio Guided Path to learn about Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and more, Take a look at the mock test series and participate in the contests hosted by Coding Ninjas Studio if you want to improve your coding skills. If you are new to preparation and want to work for firms such as Amazon, Microsoft, Uber, and others, you should review the problemsinterview experiences, and interview bundle for placement preparations.

Consider taking one of our paid courses to give yourself and your profession an edge!

Please vote for our blogs if you find them valuable and exciting.

Happy Learning!!

Live masterclass