Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Pygame Pacman幽灵,随机改变方向_Python_Pygame_Pacman - Fatal编程技术网

Python Pygame Pacman幽灵,随机改变方向

Python Pygame Pacman幽灵,随机改变方向,python,pygame,pacman,Python,Pygame,Pacman,我正在制作一个吃豆人游戏,到目前为止,除了鬼魂之外,所有的东西都能正常工作,当一个鬼魂撞到墙上时,我们称之为“吼叫”。但是正如你所看到的,self.a返回一个str,但是我需要将它应用到我的鬼精灵,Ghost1,Ghost2,等等。所以它调用Ghost1.a,鬼就会相应地移动 任何帮助都将不胜感激,谢谢 class Ghost_move(object): def __init__(self,g_speed): super(Ghost_move, self).__init_

我正在制作一个吃豆人游戏,到目前为止,除了鬼魂之外,所有的东西都能正常工作,当一个鬼魂撞到墙上时,我们称之为“吼叫”。但是正如你所看到的,self.a返回一个str,但是我需要将它应用到我的鬼精灵,Ghost1,Ghost2,等等。所以它调用Ghost1.a,鬼就会相应地移动

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

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)

正如abccd已经指出的那样,将希望执行的源代码放入字符串中是一个坏主意。最接近您的解决方案是为左、右、上、下定义函数。然后,您可以按方向存储这些函数,并执行随机选择的函数:

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只设置了一次,因此是鬼影1。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]

用法和以前一样,你只需要调用一个幽灵。

为什么你甚至需要super?我不需要,sublime text在创建新类时会自动添加它,我只是忘了删除它这是一个可怕的想法,将文本保存在字符串中,只需使用多个if语句或其他什么