Python program simulate bouncing ball in pygame
Here you will get the program code to write a python program simulate bouncing ball in pygame.
Example code of python program simulate bouncing ball in pygame
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | import pygame import sys # Initialize Pygame pygame.init() # Set up the game window width = 800 height = 600 window = pygame.display.set_mode((width, height)) pygame.display.set_caption("Bouncing Ball") # Ball properties ball_radius = 20 ball_color = (255, 0, 0) ball_pos = [width // 2, height // 2] ball_velocity = [5, 5] # Game loop while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # Update ball position ball_pos[0] += ball_velocity[0] ball_pos[1] += ball_velocity[1] # Check collision with window boundaries if ball_pos[0] <= ball_radius or ball_pos[0] >= width - ball_radius: ball_velocity[0] *= -1 if ball_pos[1] <= ball_radius or ball_pos[1] >= height - ball_radius: ball_velocity[1] *= -1 # Clear the window window.fill((0, 0, 0)) # Draw the ball pygame.draw.circle(window, ball_color, ball_pos, ball_radius) # Update the display pygame.display.update() |
How to Use the Program:
>> Ensure you have Pygame installed. If you haven’t installed, First install :
1 | pip install pygame |
>> Save the script to a file, for example, bouncing_ball.py.
>> Open a terminal or command prompt.
>> Navigate to the directory where the script is saved.
Run the script:
1 | python bouncing_ball.py |
This program demonstrates a simple physics simulation using Pygame, where a ball bounces off the edges of the window.
Check out our other Python programming examples