Why do I get an error message when trying to assign a rect to a surface?

Question:

I’m making a game and adding enemies to them, but for some reason, when I try to use the .get_rect() method, I get an error message saying "invalid rect assignment". I’ve tried many ways, if you can find a way to fix it, please let me know. Also, please, do feel free to criticise my work, as long as you provide me with solutions to fix that. I really want to improve.

python
class enemy():
    def __init__(self, x, y, eid):
        self.x = x
        self.y = y
        self.eid = eid
        self.enemysurf = pygame.image.load("graphics/enemy.png")
        self.enemyrect = self.enemysurf.get_rect(center=(self.x, self.y) # I get the error message here
        screen.blit(self.enemysurf, self.enemyrect)
Asked By: bix

||

Answers:

The issue is just a missing close parenthesis. This code should work:

self.enemyrect = self.enemysurf.get_rect(center=(self.x, self.y)

self.enemyrect = self.enemysurf.get_rect(center=(self.x, self.y))

Also, calling .convert() on pygame.image.load("graphics/enemy.png") makes the code faster. Lastly, if I remember your initial code correctly, you should always put the ‘import’ statements at the beginning of your code. More on the python style guide

Answered By: nonlinear
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.