2016-06-08 56 views
0

我有一些代码,我试图让一个精灵动画。但是,我需要在方法(动画)中使用方法(步行)中定义的属性(方向)。这可能吗?你可以给pygame中的同一个类中的另一个方法创建一个属性的方法吗?

class character(): 

init和动画在这里

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) 

回答

1

当然,

您可以初始化在__init__属性,

改变它在walk

,并使用叫它Character.animate(Character.direction)

一个例子:

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) 

此外,如果方向将始终是相同的对象(BOB)的属性, 你没有传递方向,因为该函数有它inherant访问:

def animate(self): 
    print self.direction 

bob.animate() 

所有这些可能看起来很混乱,所以如果您需要任何澄清请求。

希望这会有所帮助。

相关问题