How to properly apply OOP in the bouncing ball code

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue May 12 12:53:23 EDT 2015


On 11 May 2015 at 16:22, Tommy C <tommyc168168 at gmail.com> wrote:
> Thanks for your help.
>
> I have updated the code as follows, there are no more errors but the images will not move at all, as all the images are staying at the upper left corner. Please advice, thanks.
>
>
> import sys, pygame
>
> pygame.init()
>
> size   = width,  height = 800, 600
> black  = [0,0,0]
> screen = pygame.display.set_mode(size)
>
> class BALL:
>     def __init__(self,image):
>         self.ball     = pygame.image.load(image)
>         self.ballrect = self.ball.get_rect()
>         self.speed    = [2, 2]
>
>     def control(self):
>         ballmove = self.ballrect.move(self.speed)
>
>         if ballmove.left < 0 or ballmove.right > width:
>             self.speed[0] = -self.speed[0]
>
>         if ballmove.top < 0  or ballmove.bottom > height:
>             self.speed[1] = -self.speed[1]

The function below should not be a method on a particular ball object
as it is the global event loop for pygame. This needs to be a top
level function that updates the animation for all balls.

>     def settings(self):
>         clock  = pygame.time.Clock()
>         screen.fill(black)
>         screen.blit(self.ball, self.ballrect)
>         pygame.display.flip()
>         clock.tick(60)
>         while 1:
>             for event in pygame.event.get():
>                 if event.type == pygame.QUIT: sys.exit()

In this loop you need to add code that will call the control() method
of each ball and then redraw the screen. At the moment you only draw
the objects once at the top of the settings() method. Then the loop
runs until you quit. So it should be something like:

# The functions below would make sense as methods of an "App" class.

def run():
    while 1:
        for event in pygame.event.get():
            if event.type = pygame.QUIT:
                sys.exit()
        update()
        draw()

def update():
    for ball in balls:
        ball.control()

def draw():
    screen.fill(black)
    for ball in balls:
        ball.draw()  # You need to add this method to BALL
    pygame.display.flip()

balls = [BALL("spongebob.png"), BALL("jaws.jpg")]

run()  # Actually runs the program's event loop.


--
Oscar



More information about the Python-list mailing list