2017-04-01 84 views
0

我正在创建一个pacman游戏,到目前为止,所有的东西都是从鬼魂那里开始工作的,当一个幽灵撞在墙上时,这个类的贝娄被称为。然而,如你所见,self.a会返回一个str,但我需要将它应用于我的幽灵精灵,Ghost1,Ghost2等。所以它调用Ghost1.a并且幽灵会相应地移动。Pygame Pacman幽灵,随机改变方向

任何帮助将不胜感激,谢谢。

class Ghost_move(object): 
    def __init__(self,g_speed): 
     super(Ghost_move, self).__init__() 
     self.left=".rect.x-=g_speed" 
     self.right=".rect.x+=g_speed" 
     self.up=".rect.y-=g_speed" 
     self.down=".rect.y+=g_speed" 
     self.direction=self.left,self.right,self.up,self.down 
     self.a=random.choice(self.direction) 
+0

为什么你甚至需要super()? – abccd

+0

我没有,崇高的文本创建一个新的类时自动添加它,我只是忘了删除它 – Jack

+0

这是一个可怕的想法,字符串中保存文字,只是使用多个if语句或东西 – abccd

回答

1

正如abccd已经指出的那样,把源代码放到你想要执行的字符串中是一个坏主意。距离您最近的解决方案是定义leftright,up,down的功能。然后,你可以存储方向的功能,并执行一个随机选择的一个:

class Ghost_move(object): 
    def __init__(self,g_speed): 
     super(Ghost_move, self).__init__() 
     self.g_speed = g_speed 
     self.directions = self.left, self.right, self.up, self.down 
     self.a = random.choice(self.directions) 
    def left(self): 
     self.rect.x -= self.g_speed 
    def right(self): 
     self.rect.x += self.g_speed 
    def up(self): 
     self.rect.y -= self.g_speed 
    def down(self): 
     self.rect.y += self.g_speed 

现在self.a是,你可以调用一个函数。例如ghost1.a()会在四个方向之一中随机移动ghost1。但要小心,因为a只设置一次,因此ghost1.a()总是将该鬼影移向相同的方向,并且每次调用它时都不会随机选择一个方向。


一种不同的方法是用向量来做到这一点:

class Ghost_move(object): 
    def __init__(self,g_speed): 
     super(Ghost_move, self).__init__() 
     self.left = (-g_speed, 0) 
     self.right = (g_speed, 0) 
     self.up = (0, -g_speed) 
     self.down = (0, g_speed) 
     self.directions = self.left, self.right, self.up, self.down 
     self.random_dir = random.choice(self.directions) 
    def a(): 
     self.rect.x += self.random_dir[0] 
     self.rect.y += self.random_dir[1] 

用法和以前一样,你只需调用a()的鬼。