Home>

The ball does not bounce well. What am I doing wrong?

import sys
import pygame
from pygame.locals import QUIT
from pygame.locals import Rect
import math
pygame.init ()
SURFACE = pygame.display.set_mode ((400,300))
pygame.display.set_caption ("Game Window")
FPSCLOCK = pygame.time.Clock ()
class Ball:
     def __init __ (self, color, rect):
          self.color = color
          self.rect = rect
          self.dir = 320
     def draw (self):
          pygame.draw.ellipse (SURFACE, self.color, self.rect)
     def move (self):
          speed = 10
          if rect.centerx<0 or rect.centerx>400:
                dir = 180-dir
          if rect.centery<0 or rect.centery>300:
                dir = -dir
          self.rect.centerx + = math.cos (math.radians (dir)) * speed
          self.rect.centery-= math.sin (math.radians (dir)) * speed
rect = Rect (150,100,10,10)
color = (255,255,0)
ball = Ball (color, rect)
while True:
    for event in pygame.event.get ():
         if event.type == QUIT:
              pygame.quit ()
              sys.exit ()
    SURFACE.fill ((0,0,0))
    ball.draw ()
    ball.move ()
    pygame.display.update ()
    FPSCLOCK.tick (30)
code


line 45, in
ball.move ()
line 32, in move
self.rect.centerx + = math.cos (math.radians (dir)) * speed
UnboundLocalError: local variable'dir' referenced before assignment
fixed. Is the error message