0

这是我遇到问题的代码的相关部分。player.x 和 player.y 在调试控制台中出现“AttributeError: type object 'player' has no attribute 'x'”错误。我有一个名为“玩家”的单独类,我想在它四处移动时获得它的 x 和 y 坐标,以便敌人可以向它移动。这也是相关的播放器类开始部分:

class player(object):
    def __init__(self, x, y, sprintMultiplier, fps):
        self.x = x
        self.y = y
        self.vel = 1/fps * 150


class enemy(object):
    def __init__(self, fps, difficulty):
      pass

    def draw(self, window):
        self.moveTowardsPlayer()
        window.blit(self.downStanding, (self.x, self.y))

    def moveTowardsPlayer(self):
        dx, dy = self.x - player.x, self.y - player.y
        dist = math.hypot(dx, dy)
        dx, dy = dx/dist, dy/dist
        self.x += dx * self.vel
        self.y += dy * self.vel
4

2 回答 2

1

根据提供的代码,您似乎正在将一个与该类的一个对象(实例)混合在一起。

player这是一个类,您可以在其中创建对象。player类本身没有类属性(即类的所有成员共享的变量;它只有实例属性(类的各个实例独有的变量)。因此,预期用途是您创建一个或多个实例(可能对您的程序来说是全局的)并对其进行操作。

因此,我认为你需要的是三个方面:

  1. 像这样创建一个player对象:the_player = player(starting_x, starting_y, multiplier, starting_fps)
  2. player为您enemy的初始化程序添加一个参数,如下所示:

    class enemy(object):
        def __init__(self, player_to_track, fps, difficulty):
            self.player_to_track = player_to_track
    
  3. 传递the_playerenemy您创建的对象。

(对于它的价值,许多人坚持将类名大写,实例小写的约定。这有助于在阅读代码时区分明显 - 你会得到类似的东西my_player = Player( . . . ),如果你曾经写过Player.foo,它有助于指出您说的是属性,而不是成员变量。)

于 2018-12-09T02:41:34.903 回答
0

您的代码中的错误

  • 您将类 player 的 x 和 y 变量声明为私有实例变量,而在敌人类中,您将这些 x 和 y 值作为全局变量访问。

所以解决这个问题的工作是。

您可以将 x 和 y 值声明为如下全局变量,并在构造函数中将这些 x 和 y 变量作为全局变量访问,如下所示。

class player(object):
     x = 0
     y = 0
     def __init__(self, x, y, sprintMultiplier, fps):
       player.x = x
       player.y = y
       self.vel = 1/fps * 150

或者,如果您不想将(玩家类的)x 和 y 变量保留为全局/类变量,则将玩家实例传递给敌人类中的方法 moveTowardsPlayer()。代码如下。

def moveTowardsPlayer(self, player1):
    dx, dy = self.x - player1.x, self.y - player1.y
    dist = math.hypot(dx, dy)
    dx, dy = dx/dist, dy/dist
    self.x += dx * self.vel
    self.y += dy * self.vel
于 2018-12-09T02:51:20.303 回答