【问题标题】:Pygame Pacman ghost, random change directionPygame吃豆鬼,随机改变方向
【发布时间】:2017-04-02 00:58:39
【问题描述】:

我正在创建一个吃豆人游戏,到目前为止,除了鬼魂之外一切正常,当鬼魂撞到墙上时,会调用下面的类。但是,正如您所见,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)

【问题讨论】:

  • 为什么还需要 super() ?
  • 我没有,sublime text新建类的时候会自动添加,我只是忘记删除了
  • 将文字保存在字符串中是一个糟糕的主意,只需使用多个 if 语句或其他东西

标签: python pygame pacman


【解决方案1】:

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

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()即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 2011-04-01
    • 1970-01-01
    • 2019-08-16
    • 2013-07-22
    • 1970-01-01
    相关资源
    最近更新 更多