How to properly apply OOP in the bouncing ball code

Tommy C tommyc168168 at gmail.com
Fri May 8 11:40:34 EDT 2015


I'm trying to apply OOP in this bouncing ball code in order to have multiple balls bouncing around the screen. The objective of this code is to create a method called settings, which controls all the settings for the screen and the bouncing behaviour of multiple balls, under the class Ball. However, I keep on getting errors related to attributes (e.g., speed). I'm new to OOP in Python so your help will be much appreciated. Thanks in advance.


import pygame
import random
import sys

pygame.init()

class Ball:
    def __init__(self, X, Y):
        self.velocity = [1,1]
        self.ball_image = pygame.image.load ("ball.jpg")
        self.ball_boundary = self.ball_image.get_rect ()
        self.black = [0,0,0]
        self.width = 800
        self.height = 600
        self.num = 8
        self.X = random.randint(0, self.width)
        self.Y = random.randint(0, self.height)

    def settings(self):
        #X = random.randint(0, self.width)
        #Y = random.randint(0, self.height)
        clock = pygame.time.Clock()
        size = self.width, self.height
        screen = pygame.display.set_mode(size)
        ball_boundary = self.ball_image.get_rect()
        speed = self.velocity
        pic = self.ball_image
        pygame.display.set_caption("Balls")
        num_balls = self.num
        ball_list = []

        for i in range(num_balls):
           ball_list.append( Ball(random.randint(10, self.width-10),random.randint(10, self.height-10)) )

        while 1:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit(0)

            screen.fill(self.black)
            for balls in ball_list:
                if balls.ball_boundary.left < 0 or balls.ball_boundary.right > self.width:
                    balls.speed[0] = -balls.speed[0]
                if balls.ball_boundary.top < 0 or balls.ball_boundary.bottom > self.height:
                    balls.speed[1] = -balls.speed[1]
                balls.ball_boundary = balls.ball_boundary.move (self.velocity)
                screen.blit (balls.ball_image, balls.ball_boundary)
            pygame.display.flip()

play = Ball(random.randint(0, 800), random.randint(0, 600))

play.settings()




Message	File Name	Line	Position	
Traceback				
    <module>	C:\....\Multiple_balls_TC.py	63		
    settings	C:\....\Multiple_balls_TC.py	56		
AttributeError: Ball instance has no attribute 'speed'				



More information about the Python-list mailing list