Skip to content

Instantly share code, notes, and snippets.

@MBlore
Created January 18, 2023 18:35
Show Gist options
  • Save MBlore/13d0c50a5cf9f95abd47f895e05aff72 to your computer and use it in GitHub Desktop.
Save MBlore/13d0c50a5cf9f95abd47f895e05aff72 to your computer and use it in GitHub Desktop.
Bouncing Balls
import sys, pygame
import random
pygame.display.init()
size = width, height = 1000, 1000
background = 0, 0, 0
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Balls")
file = open('ball.txt', 'r')
lines = file.readlines()
balls = []
class Ball:
def __init__(self):
self.x = 0
self.y = 0
self.size = 0
self.x_velocity = random.randint(0, 100) / 100
self.y_velocity = 0
self.force_loss = 0.0
self.colour = (random.randint(100,255), 0, 0)
for line in lines:
if (len(line.strip()) == 0):
# The line is empty, skip this line.
continue
parts = line.split()
if (parts[0] == "Ball"):
# The line is a ball command, lets create a ball.
new_ball = Ball()
new_ball.x = int(parts[1])
new_ball.y = int(parts[2])
new_ball.size = int(parts[3])
new_ball.force_loss = float(parts[4])
balls.append(new_ball)
file.close()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Clear the screen, render the balls and display.
screen.fill(background)
for ball in balls:
# Lets apply gravity to the balls.
ball.y_velocity += 0.0005 # Gravity
ball.y += ball.y_velocity
ball.x += ball.x_velocity
# Lets detect the ball hits the bottom.
if (ball.y > 1000 - ball.size):
ball.y = 1000 - ball.size
ball.y_velocity = -ball.y_velocity
ball.y_velocity *= ball.force_loss # Lose 10% of the balls force when it bounces.
if (ball.x > 1000 - ball.size):
ball.x = 1000 - ball.size
ball.x_velocity = -ball.x_velocity
if (ball.x < 0 + ball.size):
ball.x = 0 + ball.size
ball.x_velocity = -ball.x_velocity
pygame.draw.circle(screen, ball.colour, (ball.x, ball.y), ball.size)
pygame.display.flip()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment