Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions bouncing_ball.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import pygame

# Initialize Pygame
pygame.init()

# Define screen dimensions
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

# Create the screen object
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

# Set the window title
pygame.display.set_caption("Bouncing Ball")

# Define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 128, 0) # A darker green for trees
RED = (255, 0, 0) # For the ball

# Ball class
class Ball:
def __init__(self, x, y, radius, color, dx, dy):
self.x = x
self.y = y
self.radius = radius
self.color = color
self.dx = dx
self.dy = dy

def draw(self, screen):
pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), self.radius)

def update(self):
self.x += self.dx
self.y += self.dy

# Function to draw a tree
def draw_tree(screen, x, y):
"""Draws a simple pine tree shape.

Args:
screen: The Pygame screen object.
x: The x-coordinate of the top point of the tree.
y: The y-coordinate of the top point of the tree.
"""
point1 = (x, y)
point2 = (x - 40, y + 100) # Bottom-left
point3 = (x + 40, y + 100) # Bottom-right
pygame.draw.polygon(screen, GREEN, [point1, point2, point3])

# Create a ball instance
ball = Ball(x=100, y=SCREEN_HEIGHT // 2, radius=15, color=RED, dx=5, dy=3) # Added dy for Y bounce demo

clock = pygame.time.Clock() # New
# Game loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

ball.update() # Update ball's position

# Bouncing logic
if ball.x + ball.radius > SCREEN_WIDTH or ball.x - ball.radius < 0:
ball.dx *= -1
if ball.y + ball.radius > SCREEN_HEIGHT or ball.y - ball.radius < 0:
ball.dy *= -1

screen.fill(WHITE) # Clear screen

# Draw trees
draw_tree(screen, x=60, y=SCREEN_HEIGHT - 150)
draw_tree(screen, x=SCREEN_WIDTH - 60, y=SCREEN_HEIGHT - 150)

ball.draw(screen) # Draw the ball

pygame.display.flip() # Update the full display
clock.tick(60) # New

pygame.quit()