0

So I'm making a code where there are a bunch of circles that are going across the screen. When it hits the edge of the screen they have to bounce back and go in the opposite direction. Although it's not working in the sense that I just get a blank screen with nothing on it.

My Code:

import random
import pygame
pygame.init()
from pygame.locals import *
screen = pygame.display.set_mode((500,500))
pygame.display.set_caption("THING")
blue = (0,0,255)
black = (0,0,0)
listy = []
x = 25
y = 25

clock = pygame.time.Clock()
class Circle:
    def __init__(self,radius,x,y,color):
        self.radius = radius
        self.x = x
        self.y = y
        self.color = color
    def draw_circle(self):
        pygame.draw.circle(screen,self.color,(self.x,self.y),self.radius,3)
for thingamabobber in range(1,4,1):
    x = 25
    for loop in range(1,11,1):
        circleobj = Circle(25,x,y,blue)
        listy.append(circleobj)
        x = x + 50
    y = y + 50
        
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            exit()
    clock.tick(60)
    screen.fill(black)
    for circleobj in listy:
        circleobj.draw_circle()
        thingymabobber = random.randint(1,5)
        circleobj.x = circleobj.x + thingymabobber
        if circleobj.x >= 475: #Detecting if hitting edge of screen
            while True:
                circleobj.x = circleobj.x - 1 #Making it bounce back
    pygame.display.update()

I would appreciate a fixed code and what the error was. Thanks!

acw1668
  • 40,144
  • 5
  • 22
  • 34
Ravishankar D
  • 131
  • 10

1 Answers1

1

The inner while True loop will block the application when circleobj.x >= 475 is True.

You don't need the inner while loop at all. But you need to add an attribute inside Circle class to determine the current moving direction, for example dx for horizontal movement:

class Circle:
    def __init__(self,radius,x,y,color):
        self.radius = radius
        self.x = x
        self.y = y
        self.color = color
        self.dx = 1  # initial moving direction horizontally
    def draw_circle(self):
        pygame.draw.circle(screen,self.color,(self.x,self.y),self.radius,3)

Then rewrite the while loop as below:

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            exit()
    clock.tick(60)
    screen.fill(black)
    for circleobj in listy:
        thingymabobber = random.randint(1,5)
        # change circle object moving direction if it hits boundaries
        if circleobj.x <= 25:
            circleobj.dx = 1
        elif circleobj.x >= 475:
            circleobj.dx = -1
        # move the circle object
        circleobj.x += circleobj.dx * thingymabobber
        circleobj.draw_circle()
    pygame.display.update()
acw1668
  • 40,144
  • 5
  • 22
  • 34