In this python game tutorial, I want to show you on How To Create A Bouncing Ball In Python Using PyGame.
Which we can learn with the help of example source codes.
So let’s get started…
What is A Ball Game?
Ball games, also called ball sports, are any game or sport that involves a ball.
Games like football, cricket, baseball, basketball, and American football are among these.
Most of these games came from different places and have different rules and histories.
Bouncing Ball Game Project Software Information
| Project Name: | Bouncing Ball Game in Python |
| Abstract: | Bouncing Ball Game was developed In Python using Pygame. |
| Language Used: | Python Programming Language |
| Python Version: | 2.x or 3.x |
| Database: | None |
| Type: | GUI (Graphical User Interface) |
| Developer: | Angel Jude Suarez |
About The Project
A Bouncing Ball is a simple game code in python to use in different python games that use balls. like pong games, basketball games and etc.
Steps On How To Create A Simple Bouncing Ball Game In Python
Here’s a step-by-step guide on how to make a ball bounce off walls in python with source code.
Step 1: Install Libraries
First, we will install all required libraries for the bouncing ball game functions.
import sys, pygameStep 2: Declaring and Assigning Values To The Variables
Next, we will declare and assign values in different variables.
size = width, height = 500, 400
x, y = 500, 400
moveX, moveY = 0, 0
speed = [moveX, moveY]
black = 0, 0, 0
grey = 246, 246, 246
FullScreen = False
Step 3: Create A Screen Display And Ball Image
Next, we will create a screen display and its sizes and display ball.
screen = pygame.display.set_mode(size, 0, 32)
pygame.display.set_caption('Bouncing ball')
ball = pygame.transform.scale(pygame.image.load('ball.png'), (70, 70))
gravityAcceleration = 0.3
horizontalAcceleration = 0
verticalSpeed = [0, 0]
horizontalSpeed = [0, 0]
ballrect = ball.get_rect()
clock = pygame.time.Clock()Step 4: Create A Main Function Of The Game
Lastly, we will create a main function of the bouncing ball game in python.
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_f:
FullScreen = not FullScreen
if FullScreen:
screen = pygame.display.set_mode(size, pygame.HWSURFACE|pygame.FULLSCREEN, 32)
else:
screen = pygame.display.set_mode(size, 0, 32)
keys = pygame.key.get_pressed()
# Provide controls from keyboard, even when key is held down
if keys[pygame.K_LEFT]:
horizontalSpeed[0] = 0
horizontalSpeed[1] = -10
if keys[pygame.K_RIGHT]:
horizontalSpeed[0] = 0
horizontalSpeed[1] = 10
if keys[pygame.K_UP]:
verticalSpeed[0] = 0
verticalSpeed[1] = -10
verticalSpeed[0] = gravityAcceleration + verticalSpeed[1]
y += verticalSpeed[0]
verticalSpeed[1] = verticalSpeed[0]
horizontalSpeed[0] = horizontalAcceleration + horizontalSpeed[1]
x += horizontalSpeed[0]
horizontalSpeed[1] = horizontalSpeed[0]
if x < 0:
x = 0
horizontalSpeed = [-horizontalSpeed[0] * 0.7, -horizontalSpeed[1] * 0.7]
if x > (width- ballrect.right):
x = width- ballrect.right
horizontalSpeed = [-horizontalSpeed[0] * 0.7, -horizontalSpeed[1] * 0.7]
if y < 0:
y = 0
verticalSpeed = [0, 0]
if y > (height - ballrect.bottom):
y = height - ballrect.bottom
verticalSpeed = [-verticalSpeed[0] * 0.7, -verticalSpeed[1] * 0.7]
if (y == (height - ballrect.height)):
horizontalSpeed = [horizontalSpeed[0] * 0.95, horizontalSpeed[1] * 0.95]
clock.tick(60)
screen.fill(grey)
screen.blit(ball, (x, y))
pygame.display.update()Complete Source Code
Here’s the complete source code of Bouncing Ball in Python using Pygame.
import sys, pygame
pygame.init()
size = width, height = 500, 400
x, y = 500, 400
moveX, moveY = 0, 0
speed = [moveX, moveY]
black = 0, 0, 0
grey = 246, 246, 246
FullScreen = False
screen = pygame.display.set_mode(size, 0, 32)
pygame.display.set_caption('Bouncing ball')
ball = pygame.transform.scale(pygame.image.load('ball.png'), (70, 70))
gravityAcceleration = 0.3
horizontalAcceleration = 0
verticalSpeed = [0, 0]
horizontalSpeed = [0, 0]
ballrect = ball.get_rect()
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_f:
FullScreen = not FullScreen
if FullScreen:
screen = pygame.display.set_mode(size, pygame.HWSURFACE|pygame.FULLSCREEN, 32)
else:
screen = pygame.display.set_mode(size, 0, 32)
keys = pygame.key.get_pressed()
# Provide controls from keyboard, even when key is held down
if keys[pygame.K_LEFT]:
horizontalSpeed[0] = 0
horizontalSpeed[1] = -10
if keys[pygame.K_RIGHT]:
horizontalSpeed[0] = 0
horizontalSpeed[1] = 10
if keys[pygame.K_UP]:
verticalSpeed[0] = 0
verticalSpeed[1] = -10
verticalSpeed[0] = gravityAcceleration + verticalSpeed[1]
y += verticalSpeed[0]
verticalSpeed[1] = verticalSpeed[0]
horizontalSpeed[0] = horizontalAcceleration + horizontalSpeed[1]
x += horizontalSpeed[0]
horizontalSpeed[1] = horizontalSpeed[0]
if x < 0:
x = 0
horizontalSpeed = [-horizontalSpeed[0] * 0.7, -horizontalSpeed[1] * 0.7]
if x > (width- ballrect.right):
x = width- ballrect.right
horizontalSpeed = [-horizontalSpeed[0] * 0.7, -horizontalSpeed[1] * 0.7]
if y < 0:
y = 0
verticalSpeed = [0, 0]
if y > (height - ballrect.bottom):
y = height - ballrect.bottom
verticalSpeed = [-verticalSpeed[0] * 0.7, -verticalSpeed[1] * 0.7]
if (y == (height - ballrect.height)):
horizontalSpeed = [horizontalSpeed[0] * 0.95, horizontalSpeed[1] * 0.95]
clock.tick(60)
screen.fill(grey)
screen.blit(ball, (x, y))
pygame.display.update()Download Full Source Code
You can visit this site to download the full source code of Bouncing Ball Game for free.
Conclusion
We have completely discussed a step-by-step process on How To Create A Simple Bouncing Ball In Python, which we learned with the help of source codes. I hope this PyGame Tutorial will help you a lot.
Related Python Tutorials
- How To Reverse A String In Python
- How To End A Program In Python
- How To Sort A List In Python
- How To Add To A Dictionary In Python
- How To Print In Python
- How To Comment In Python
Common use cases for How to Create a Bouncing Ball
- Data pipelines. Python is the standard for ETL, data analysis, and ML workflows.
- Web development. Django and FastAPI power modern web backends and APIs.
- Automation and scripting. System administration, file processing, web scraping, and cron jobs.
- Machine learning. scikit-learn, PyTorch, TensorFlow, Hugging Face for AI/ML projects.
- Educational tools. Python’s readability makes it the go-to teaching language.
Working code example
from typing import Optional
def process_data(items: list[dict]) -> Optional[dict]:
"""Process a list of items and return summary stats."""
if not items:
return None
return {
"count": len(items),
"total": sum(item.get("value", 0) for item in items),
"avg": sum(item.get("value", 0) for item in items) / len(items),
}
# Usage
data = [{"value": 10}, {"value": 20}, {"value": 30}]
summary = process_data(data)
print(summary) # {'count': 3, 'total': 60, 'avg': 20.0}
Best practices
- Use type hints. list[dict], Optional[str], and TypedDict make code self-documenting and enable static analysis.
- Follow PEP 8. Consistent style improves readability. Use black or ruff to auto-format.
- Prefer f-strings. f”{value}” is cleaner than str.format() or % formatting.
- Write tests with pytest. Aim for 70%+ coverage on business-critical modules.
- Use ruff or pylint. Static analysis catches many bugs before code runs.
Common pitfalls
- Mutable default arguments. def f(x=[]) reuses the same list across calls. Use x=None then check.
- Integer division. 5/2 gives 2.5 in Python 3. Use // for floor division.
- Missing self on methods. Class methods need self as first parameter.
- Late binding closures. Loops that create lambdas can capture variables late.

As a regular reader, I want to express my gratitude for this tutorial on creating a bouncing ball game in Python using PyGame. The step-by-step guide and source code provided are very helpful, especially for beginners like me who are just starting to learn Python programming. I appreciate the author’s efforts in making the instructions clear and easy to follow, as well as providing the necessary code snippets to complete the project. However, I have a question: Is it possible to modify the code to add sound effects when the ball bounces off the walls or other objects? Thank you again for this tutorial, and I’m looking forward to learning more about game development using Python.
Yes, you can edit it as you want after you downloaded the source code