Question

I get an error from my code and I don't know why, but syntactically, it's correct, I guess

import pygame

class BaseClass(pygame.sprite.Sprite):
    allsprites = pygame.sprite.Group()  
    def __init__(self, x, y, width, height, image_string):
        pygame.sprite.Sprite.__init__(self)
        BaseClass.allsprites.add(self)

        self.image = pygame.image.load("Images\lebron.png")
        self.rectangle = self.image.get_rect()
        self.rectangle.x = x
        self.rectangle.y = y
        self.width = width
        self.height = height

class Lebron(BaseClass):
    List = pygame.sprite.Group()
    def __init__(self, x, y, width, height, image_string):
        BaseClass.__init__(self, x, y, width, height, image_string)
        Lebron.List.add(self)
        self.velx = 0

    def movement(self):
        self.rectangle.x += self.velx

so if i compile this to my main file, code below

import pygame, sys
from classes import *
from process import process

pygame.init()
WIDTH, HEIGHT = 640, 360
screen = pygame.display.set_mode((WIDTH, HEIGHT))

clock = pygame.time.Clock()
FPS = 24

lebron = Lebron(0, 100, 104, 120, "Images\lebron.png")

while True:
    process()
    #LOGIC
    lebron.movement()
    #LOGIC

    #DRAW
    BaseClass.allsprites.draw(screen)
    screen.fill((0,0,0))
    pygame.display.flip()
    #DRAW

    clock.tick(FPS)

I get an error which is attribute error: Lebron object has no attribute rect. what's wrong? The traceback:

Traceback (most recent call last):
 File "MAIN.py", line 24, in <module>
   BaseClass.allsprites.draw(screen)
 File "C:\Python27\lib\site-packages\pygame\sprite.py", line 409, in draw
   self.spritedict[spr] = surface_blit(spr.image, spr.rect)
 AttributeError: 'Lebron' object has no attribute 'rect' 
Was it helpful?

Solution

It appears from the posted traceback (they look much better when you indent them by 4 spaces, and even better when you edit the question to include them) that the PyGame draw() method expects your attribute to provide a rect attribute. At a guess, if you replace every occurrence of rectangle with rect you will make at least some progress.

Basically, PyGame wants to draw your object but it can't find out how.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top