Here's a simple example of bouncing balls using Python with the Pygame library.
Prerequisites
You need to have Python and the Pygame library installed. You can install Pygame using pip:
bash
pip install pygame
Code
python
import pygame
import sys
# Pygame Initialization
pygame.init()
# Screen size
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# Colors
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
# Ball class
class Ball:
def __init__(self, x, y, radius, color, speed_x, speed_y):
self.x = x
self.y = y
self.radius = radius
self.color = color
self.speed_x = speed_x
self.speed_y = speed_y
def draw(self, screen):
pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius)
def update(self):
self.x += self.speed_x
self.y += self.speed_y
if self.x - self.radius < 0 or self.x + self.radius > SCREEN_WIDTH:
self.speed_x *= -1
if self.y - self.radius < 0 or self.y + self.radius > SCREEN_HEIGHT:
self.speed_y *= -1
# Create balls
balls = [
Ball(100, 100, 20, RED, 3, 3),
Ball(300, 300, 30, BLUE, -2, -2),
Ball(500, 100, 40, RED, 1, 4),
Ball(100, 500, 50, BLUE, -3, -1),
]
# Game loop
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill(WHITE)
for ball in balls:
ball.update()
ball.draw(screen)
pygame.display.update()
clock.tick(60)
Explanation
This code creates a window with multiple bouncing balls. Each ball has its own position, radius, color, and speed. The Ball class encapsulates the properties and behavior of a ball. The game loop updates the position of each ball, checks for collisions with the edges of the screen, and redraws the screen.
Running the Code
Save this code in a file (e.g., bouncing_balls.py) and run it using Python:
bash
python bouncing_balls.py
This will launch the game window with bouncing balls. You can close the window by clicking the close button.