[Tutor] Weird Python Error

Alan Gauld alan.gauld at btinternet.com
Fri Oct 18 10:42:52 CEST 2013


On 17/10/13 21:09, Zaid Saeed wrote:
> class YellowCar(pygame.sprite.Sprite):
>
>      def __init__(self):
>          pygame.sprite.Sprite.__init__(self)
>          self.image = pygame.image.load("yellow.png")
>          self.image = pygame.transform.scale(self.image,(50, 75))
>          self.rect = self.image.get_rect()
>
>      def update(self):
>          self.rect.centery += self.dy
>          if self.rect.top > screen.get_height():
>              self.reset()
>
>      def reset(self):
>          self.rect.bottom = 0
>          self.rect.centerx = random.randrange(190, screen.get_width())
>          self.dy = random.randrange(10, 30)

Update uses dy but it is only set in reset(). If you call update
before reset you will get the error.

Now in your Game() code we find:

         if hitCar:
             redCar.sndThunder.play()
             scoreboard.lives -= 1
             if scoreboard.lives <= 0:
                 keepGoing = False
             for theCar in hitCar:
                 theCar.reset()

         # allSprites.clear(screen, background)
         goodSprites.update()
         badSprites.update()
         scoreSprite.update()

So any updated car not in hitcar will not have
been reset and so you will have an error.

It's best (for your sanity) to initialise all class
attributes in __init__.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list