我试图让敌人向我的玩家移动,但出现属性错误

I am trying to make an enemy move toward my player, but am getting an Attribute Error

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

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

根据提供的代码,您似乎将 classobject(实例) class.

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

因此,我认为您需要三方面的东西:

  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_player 传递给您创建的 enemy 对象。

(值得一提的是,许多人都遵守将 class 名称大写,实例小写的惯例。这有助于在阅读代码时使其区别明显——你会得到类似 my_player = Player( . . . ),如果你曾经写过 Player.foo,它有助于指出你在谈论 class 属性,而不是成员变量。)

您的代码有误

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

所以解决这个问题的方法是。

You either declare the x and y values as global variables as below and access those x and y variables as global ones in the constructor as given below.

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

or Pass a player instance to the method moveTowardsPlayer() within the enemy class if you don't want to keep the x and y variables (of player class) as global/class variables. Code is given below.

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