Tyler
Tyler

Reputation: 55

Can you give a method an attribute created by another method in the same class in pygame?

I have some code where I am trying to animate a sprite. However, I need to use an attribute (direction) defined in a method (walk) in my method (animate). Is this possible?

class character():

init and animate are here

    def walk(self, x, y, direction):
        if event.type == KEYDOWN:

            if (event.key == K_LEFT):
                self.x-=1
                self.direction = 2
                print(self.direction)

            elif (event.key == K_RIGHT):
                self.x+=1
                self.direction = 3

            elif (event.key == K_UP):
                self.y-=1
                self.direction = 0

            elif (event.key == K_DOWN):
               self.y+=1
               self.direction = 1



Character.animate(direction)

Upvotes: 0

Views: 26

Answers (1)

DCA-
DCA-

Reputation: 1292

Sure,

You can initialise the attribute in __init__,

change it in walk,

and call it using Character.animate(Character.direction)

an example:

class Character():
    def __init__(self):
        self.direction = 0

    def walk(self, x, y, direction):
        if event.type == KEYDOWN:

            if (event.key == K_LEFT):
                self.x-=1
                self.direction = 2
                print(self.direction)

            elif (event.key == K_RIGHT):
                self.x+=1
                self.direction = 3

            elif (event.key == K_UP):
                self.y-=1
                self.direction = 0

            elif (event.key == K_DOWN):
               self.y+=1
               self.direction = 1
     def animate(self, driection):
         print direction

#### Create the character object ####
bob = Character()


####  Call the animate function  ####
bob.animate(bob.direction)

Also if the direction will always be the attribute of the same object (bob), you don't have to pass the direction in because the function has inherant access to it:

 def animate(self):
     print self.direction

 bob.animate()

All this may seem confusing so ask away if you need any clarification.

Hope this helps.

Upvotes: 1

Related Questions