实例变量和继承

时间:2019-05-28 22:14:56

标签: python python-3.x pygame

目前,我正在尝试在main()中计算Image1和Player类之间的距离。我感兴趣的变量是Bx,By,Px和Py,如下所示。目前,我可以在Pygame窗口中获取图像,以实时更新和打印它们各自的坐标。但是,我想访问各个变量,以便实现距离变量。


class Image1(pygame.sprite.Sprite):
    def __init__(self, img, all_active_sprites):
        super().__init__()

        #scale player image
        self.image = pygame.transform.scale(ImageOne, (100, 100))
        self.image.set_colorkey(BLACK)
        self.rect = self.image.get_rect()

        #set spawn location for image
        self.rect.x = random.randrange(25, WINDOWWIDTH - 25)
        self.rect.y = random.randrange(25, WINDOWHEIGHT - 25)

        #set speed/direction
        self.speed_x = random.choice([-1,1])
        self.speed_y = random.choice([-1,1])

    def update(self):
        ''' update Image1 class '''
        self.rect.y += self.speed_y
        self.rect.x += self.speed_x

        #simulate zigzag movement

        "Omitted for Space - Movement Rules"

        #calculate coordinates
        Bx = self.rect.x
        By = self.rect.y
        coordinates_Image1 = (Bx,By)
        print("Image1 Position:",coordinates_Image1)

class Player(pygame.sprite.Sprite):
    def __init__(self, player_img,all_active_sprites):
        super().__init__()
        #scale player image
        self.image = pygame.transform.scale(player_img, (25, 25))
        self.image.set_colorkey(BLACK)
        self.rect = self.image.get_rect()

        #player starting location
        self.rect.x = WINDOWWIDTH / 2
        self.rect.y = WINDOWHEIGHT/ 2

        #player speed
        self.speed_x = 0
        self.speed_y = 0

    def update(self):
        '''update the Player class'''
        #arrow controls
        "Omitted for Space - Key Commands"

        #update movement, stop at boundaries
        self.rect.x += self.speed_x
        self.rect.y += self.speed_y

        "Omitted for Space - Movement Rules"

        #calculate coordinates
        Px = self.rect.x
        Py = self.rect.y
        coordinates_player = Px,Py
        print("Player Position:",coordinates_player)

我的想法是我需要找到一种在语言环境之外访问这些实例变量的方法,因此,作为解决方案,我尝试了如下方法。我在每个类中将坐标分为各自的函数,而不进行运动计算。然后,在我的main()中,为每个类创建一个实例,例如p = Player(args)。然后,我从main()中调用了坐标函数,成对的坐标(x,y)会像以前一样打印,但是我仍然无法访问/打印所需的各个变量。不知道我在做什么错。谢谢,身体健康!

1 个答案:

答案 0 :(得分:0)

变量PxPy仅在update()函数中。它们被称为“局部变量”。另一方面,您有一个名为p的变量,代表整个玩家。它的字段p.rect是其边界矩形。从那里,您可以访问p.rect.xp.rect.y