0% found this document useful (0 votes)
8 views

Text

Code

Uploaded by

inbox.benchoe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Text

Code

Uploaded by

inbox.benchoe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import pygame

import random
import sys

# Initialize Pygame
pygame.init()

# Screen settings
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Bouncing Balls Game")

# Colors
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)

# Ball settings
BALL_RADIUS = 20
BALL_COUNT = 5
balls = []

# Button settings
button_rect = pygame.Rect(WIDTH // 2 - 50, HEIGHT // 2 - 20, 100, 40)

# Ball class to manage properties and movements


class Ball:
def __init__(self, x, y):
self.x = x
self.y = y
self.vx = random.choice([-5, 5])
self.vy = random.choice([-5, 5])

def move(self):
self.x += self.vx
self.y += self.vy

# Bounce off walls


if self.x <= BALL_RADIUS or self.x >= WIDTH - BALL_RADIUS:
self.vx *= -1
if self.y <= BALL_RADIUS or self.y >= HEIGHT - BALL_RADIUS:
self.vy *= -1

# Bounce off button


if button_rect.collidepoint(self.x, self.y):
self.vx *= -1
self.vy *= -1

def draw(self):
pygame.draw.circle(screen, BLUE, (self.x, self.y), BALL_RADIUS)

# Initialize balls
for _ in range(BALL_COUNT):
x = random.randint(BALL_RADIUS, WIDTH - BALL_RADIUS)
y = random.randint(BALL_RADIUS, HEIGHT - BALL_RADIUS)
balls.append(Ball(x, y))

# Main game loop


running = True
while running:
screen.fill(WHITE)

# Draw button
pygame.draw.rect(screen, RED, button_rect)
pygame.draw.rect(screen, (0, 0, 0), button_rect, 2)

# Event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
running = False # Press 'A' to stop the game
elif event.type == pygame.MOUSEBUTTONDOWN:
mx, my = pygame.mouse.get_pos()
for ball in balls:
if (ball.x - mx) ** 2 + (ball.y - my) ** 2 <= BALL_RADIUS ** 2:
ball.vx = (ball.x - mx) // 2 # Throw in x direction
ball.vy = (ball.y - my) // 2 # Throw in y direction

# Move and draw balls


for ball in balls:
ball.move()
ball.draw()

pygame.display.flip()
pygame.time.delay(30)

pygame.quit()
sys.exit()

You might also like