Cameron Burrows
Cameron Burrows

Reputation: 37

Creating multiple instances of bouncing ball pygame

So I am new to pygame and I made a program that will make a ball bounce according to gravity, and it works perfectly but now I want to be able to make infinite of them by creating one wherever I click. I know how to get the coordinates of the click, but I don't know how to create multiple circles. Would I somehow use a function or a class? Here's my code, sorry if it's a little messy.

import pygame,random,time
pygame.init()
infoObject = pygame.display.Info()
side = pygame.display.Info().current_h
side = side - ((1.0/12)*(pygame.display.Info().current_h))
side = int(side)
screen = pygame.display.set_mode([side, side])
pygame.display.set_caption("")
clock = pygame.time.Clock()
done = False
BLACK = (0,0,0)
WHITE = (255,255,255)
RED = (250,30,25)
GREEN = (25, 240, 25)
YELLOW = (250,240,25)
FPS = 60
x=100
y=100
t=0
r=10
direction=0
count = 0
def faller(x,y,color,size):
    pygame.draw.circle(screen,color,(x,y),size,0)
def reverse():
    global t,direction
    if direction == 0:
        direction = 1
        t=t*4/5
    elif direction == 1:
        direction = 0
        t=1
while not done:
        clock.tick(FPS)
        events = pygame.event.get()
        screen.fill(BLACK)
        for event in events:
            if event.type == pygame.QUIT or  (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
                done = True
        if direction==0:
            t+=1
            y+=int((9.8/FPS)*t)
        elif direction==1:
            t-=1
            y-=int((9.8/FPS)*t)
        if t==0:
            reverse()
        if y+r>side:
            y=side-r
            faller(x,y,RED,r)
            reverse()
        else:
            faller(x,y,RED,r)
        if y==side-r:
            count+=1
        else:
            count=0
        if count>=3:
            done = True
        pygame.display.flip()
pygame.quit()

Upvotes: 0

Views: 936

Answers (1)

Fabced
Fabced

Reputation: 63

I would encourage you to experiment with classes and methods. Once you have a class Ball, you can make a list of the Ball objects and process them all at once. You could then use the .append() list method to add a new Ball on mouse click.

I would suggest you use variables such as: pos_x, pos_y, vel_x, vel_y,

This will make things much easier to understand if you wanted to implement collisions. Dont forget to comment your code :)

Upvotes: 1

Related Questions