我对Python的类继承有问题

2024-06-16 15:40:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个游戏,你在屏幕底部有一艘船,你在射击从屏幕顶部落下的岩石得分。从天而降的岩石有两种,大的和小的。我决定使用1类作为Rock,并将两个def标记为smallRock和bigRock。我以为我在主程序中的代码是正确的,但我不断地得到错误。 以下是我用于Rock类的代码:

class Rock(pygame.sprite.Sprite):
    def __init__(self,bigRock,smallRock):
        pygame.sprite.Sprite.__init__(self)
        self.width = 20
        self.height = 20
        self.x_change = 0
        self.y_change = yChange
        self.image.set_colorkey([255,255,255])
        self.rect = self.image.get_rect()
        self.rect.left = x
        self.rect.top = y

    def bigRock(self):
        self.image = pygame.image.load('rockLarge.png').convert()

    def smallRock(self):
        self.image = pygame.image.load('rockSmall.png').convert()

以下是主程序的代码块:

# How many big rocks falling------------------

    Rock = pygame.sprite.RenderPlain()
    bigRockRandomizer = rockRandomizer
    bigRockQuantity = 0
    while bigRockQuantity < bigRockRandomizer:
        bigRockXLocation = xLocation
        brock = Rock.bigRock(black,bigRockXLocation)
        Rock.bigRock.add(brock)
        bigRockQuantity = bigRockQuantity + 1

# How many small rocks falling-----------------

    Rock = pygame.sprite.RenderPlain()
    smallRockRandomizer = rockRandomizer
    smallRockQuantity = 0
    while smallRockQuantity < smallRockRandomizer:
        smallRockXLocation = xLocation
        srock = smallRock(black,smallRockXLocation)
        smallRock.add(srock)
        smallRockQuantity = smallRockQuantity + 1

以下是我得到的当前错误代码:

Traceback (most recent call last):
  File "C:\Users\Steve\Desktop\Project April\Alien Metor Storm v1_5\main.py", line 561, in <module>
    main()
  File "C:\Users\Steve\Desktop\Project April\Alien Metor Storm v1_5\main.py", line 58, in main
    brock = Rock.bigRock(black,bigRockXLocation)
AttributeError: 'Group' object has no attribute 'bigRock'

有人能告诉我我做错了什么,并指出我回到正确的轨道吗?你知道吗


Tags: 代码rectimageselfmaindefpygamerock
1条回答
网友
1楼 · 发布于 2024-06-16 15:40:17
Rock = pygame.sprite.RenderPlain() # OOPS: Overwrote class name Rock

    brock = Rock.bigRock(black,bigRockXLocation) ## OOPS: Even if Rock was still the class, this call is invalid because bigRock is an instance method.

我建议您尝试使用子类,而不是在Rock中创建方法。像这样的

class Rock:
    def __init__(self, imagefn):
        self.image = pygame.image.load(imagefn).convert()
        ...

class BigRock(Rock):
    def __init__(self):
        Rock.__init__(self, 'rockLarge.png')

class SmallRock(Rock):
    def __init__(self):
        Rock.__init__(self, 'rockSmall.png')

然后根据需要创建BigRockSmallRock实例。你知道吗

相关问题 更多 >