Stimulate bouncing game using Pygame

In this tutorial, we will see how can Python be used to implement a little more than just a normal program. How Python can be used to implement a small level graphical output such as bouncing of a ball.

This can be implemented with the help of Python packages. Python is famous for its range of packages that make the computations or work much easier and help us do complex actions with just a few lines of code.

Here one such package is the Pygame.

  • It is a cross-platform module.
  • It has inbuilt graphical components.
  • This package can be used when we want to create something with visual effects.


import sys,pygame
size = width, height=320,240
speed =[2,2]
black = 0, 0, 0
screen = pygame.display.set_module(size)
ball = pygame.image.load("ball.bmp")
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(black), color,, radius)

The second package used here is sys:

  • This module is used for interaction of variables and function with interpreter.
  • Some examples are:

1.sys.version (used to say the version of Python interpreter).

2.sys.exit(used to exit from the current working program due to an exception that might occur or exit from the console/prompt).

The init() function is used to import all the module that is present in the Python package. It is like a constructor in OOPS that is used to call all the methods in its class.

Thinking of creating a bouncing ball, we would need to consider few parameters such as the ball size, its speed, the background color and so on. Python has inbuilt modules that help us determine these attributes. In the above-mentioned code, we are creating a circular ball with a backdrop of black color.

  • When the ball hits the horizontal boundary of the screen, it reverses the speed in x direction to be visible on the screen.
  • When the ball hits the vertical boundary of the screen, it reverses the speed in y direction to be visible on the screen.

Thus, a bouncing ball is stimulated.


Leave a Reply

Your email address will not be published. Required fields are marked *