Create a Basic Ball Bounce Game with Pygame
Building a Simple Ball Bounce Game in Pygame
This beginner Pygame tutorial teaches how to animate a bouncing ball using motion logic, screen boundaries, and collision response.
Project Overview
The ball bounce game is a classic beginner project for learning motion physics and event-based logic in Pygame. You’ll create a ball that moves across the screen and bounces off the window edges.
Setting Up the Game Window
Start by importing Pygame and initializing the game window:
import pygame
pygame.init()
screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Ball Bounce")
clock = pygame.time.Clock()
Creating the Ball
Set initial position, size, and movement direction:
ball_pos = [300, 200]
ball_radius = 20
ball_speed = [3, 3]
Main Game Loop with Bounce Logic
This loop handles movement, screen updates, and bouncing at window edges:
running = True
while running:
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Move the ball
ball_pos[0] += ball_speed[0]
ball_pos[1] += ball_speed[1]
# Bounce off walls
if ball_pos[0] < ball_radius or ball_pos[0] > 600 - ball_radius:
ball_speed[0] = -ball_speed[0]
if ball_pos[1] < ball_radius or ball_pos[1] > 400 - ball_radius:
ball_speed[1] = -ball_speed[1]
pygame.draw.circle(screen, (255, 0, 0), ball_pos, ball_radius)
pygame.display.flip()
clock.tick(60)
pygame.quit()
What You Learned
- How to draw and animate shapes in Pygame
- How to detect and respond to collisions with screen boundaries
- How to structure a basic game loop using `pygame.time.Clock()`
Next Steps
Try adding sound effects when the ball bounces, or add a paddle and transform this into a basic Pong clone. You can also change the ball’s speed or color randomly after every bounce!