Michael Chen
Michael Chen

Reputation: 13

Error when referencing attributes established in initialization

I'm making a third person shooter game, and I have a player object for the player. I set the x and y values in the initialization like

class Player():
def ____init____(self):
    self.x = 500
    self.y = 300

and then reference them in a later function involving movement:

    def move(self):
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT and self.x < 720:
                self.x += 2.5
            if event.key == pygame.K_LEFT and self.x > 280:
                self.x -= 2.5
            if event.key == pygame.K_UP and self.y > 80:
                self.y -= 2.5
            if event.key == pygame.K_DOWN and self.y < 520:
                self.y += 2.5

When I run the program, I get the error

AttributeError: 'Player' object has no attribute 'x'

Could someone please explain why I get the error? I defined x in the initialization, so I don't know why. Thanks in advance.

Upvotes: 0

Views: 33

Answers (1)

Ogs
Ogs

Reputation: 166

note that def __init__() should only have two underscores before and after the init word. also, i think you have to properly indent def __init__() block under the class Player(), indent the for iteration under the move function, and same thing for your if conditions.

class Player():
    def __init__(self):
        self.x = 500
        self.y = 300
    def move(self):
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT and self.x < 720:
                    self.x += 2.5
                if event.key == pygame.K_LEFT and self.x > 280:
                    self.x -= 2.5
                if event.key == pygame.K_UP and self.y > 80:
                    self.y -= 2.5
                if event.key == pygame.K_DOWN and self.y < 520:
                    self.y += 2.5

/ogs

Upvotes: 2

Related Questions