AttributeError: 'Player' object has no attribute 'rect' (PyGame)

Question:

I made a class called Player. I managed to show it on the screen(as a paddle), but when I’m trying to move it(pressing down arrow on keyboard), game crashes and I’m left with this error:

Traceback (most recent call last): File

“C:/Users/Optimus/Desktop/PongGame.py”, line 37, in

player.controlkeys() File “C:/Users/Optimus/Desktop/PongGame.py”, line 23, in controlkeys

self.rect.move_ip(-50, 0) AttributeError: ‘Player’ object has no attribute ‘rect’

Code(of class):

class Player(object):
    def __init__(self):
        self.playerpaddle = pygame.rect.Rect((40,350,35,100))

    def controlkeys(self):
        key = pygame.key.get_pressed()
        if key[pygame.K_DOWN]:
            self.rect.move_ip(-50, 0)

    def draw(self, screen):
        self.draw = pygame.draw.rect(screen, white, self.playerpaddle)

pygame.display.update()

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

    player = Player()
    player.draw(screen)
    player.controlkeys()
    pygame.display.update()

Full code: http://pastebin.com/inwVgcsk.
What I’m doing wrong?

Asked By: user7437631

||

Answers:

Your Player object has only one attribute that you defined: playerpaddle. There is no element rect. However, note that playerpaddle is of type Rect. I suspect that what you want is something like

self.playerpaddle.move_ip(-50, 0)

You’re not trying to move a particular rectangle — that object will have the attributes of class Rect.

Does that clear things up for you?

Answered By: Prune
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.