Certainly! Below is a simple Python implementation of bouncing balls using the pygame library. This code creates a window where multiple balls bounce around the screen, reflecting off the edges.
First, make sure you have pygame installed. You can install it using pip:
bash
pip install pygame
Now, here’s the code:
python
import pygame
import random
import math
# Initialize pygame
pygame.init()
# Screen dimensions
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Bouncing Balls")
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# 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 move(self):
self.x += self.speed_x
self.y += self.speed_y
# Bounce off walls
if self.x - self.radius < 0 or self.x + self.radius > WIDTH:
self.speed_x = -self.speed_x
if self.y - self.radius < 0 or self.y + self.radius > HEIGHT:
self.speed_y = -self.speed_y
def draw(self):
pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), self.radius)
# Function to create random balls
def create_balls(num_balls):
balls = []
for _ in range(num_balls):
x = random.randint(50, WIDTH - 50)
y = random.randint(50, HEIGHT - 50)
radius = random.randint(10, 30)
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
angle = random.uniform(0, 2 * math.pi)
speed = random.randint(2, 5)
speed_x = math.cos(angle) * speed
speed_y = math.sin(angle) * speed
balls.append(Ball(x, y, radius, color, speed_x, speed_y))
return balls
# Main loop
def main():
clock = pygame.time.Clock()
balls = create_balls(10) # Create 10 balls
running = True
while running:
screen.fill(BLACK)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
for ball in balls:
ball.move()
ball.draw()
pygame.display.flip()
clock.tick(60) # 60 FPS
pygame.quit()
if __name__ == "__main__":
main()
Explanation:
Ball Class: Represents a ball with properties like position, radius, color, and speed. The move method updates the ball's position and handles bouncing off the walls. The draw method renders the ball on the screen.
create_balls Function: Generates a list of balls with random positions, sizes, colors, and speeds.
Main Loop: Initializes the game, creates balls, and enters the main loop where balls move and are redrawn on each frame. The loop runs at 60 FPS.
Run the code, and you should see multiple balls bouncing around the screen!