简体   繁体   English

我无法让组列表通过它迭代我的方法(pygame.sprite)

[英]I cannot make a Group list iterate my method through it (pygame.sprite)

import pygame
from pygame.sprite import Sprite
from pygame.sprite import Group

class Raindrop(Sprite):

    def __init__(self, screen):
        super().__init__()
        ...
    ...
    def drop(self):
        ...
...
raindrops = Group()
...
raindrops.drop()
...

When I use this code, I end up with an error:当我使用此代码时,最终出现错误:

Traceback (most recent call last):
  File "raindrops.py", line 74, in <module>
    rain()
  File "raindrops.py", line 71, in rain
    update_raindrops.py(screen, raindrops)
  Dile "raindrops.py", line 57, in update_raindrops
   raindrops.drop()
AttributeError: 'Group' object has no attribute 'drop'

Why does this happen?为什么会发生这种情况? When I was doing some very similar examples from a textbook, it would define a method for a subclass of Sprite, than make a Group list of sprites and then GroupList.ClassMethod() worked just fine.当我在教科书上做一些非常相似的例子时,它会为 Sprite 的子类定义一个方法,而不是创建一个 Sprite 的 Group 列表,然后 GroupList.ClassMethod() 工作得很好。 But not in this case, for some reason.但不是在这种情况下,出于某种原因。 I can provide the whole code, if you need.如果你需要,我可以提供完整的代码。

Your assertion is false - the PyGame Sprite Group does not apply arbitrary methods, just some well known pre-defined methods.您的断言是错误的 - PyGame Sprite Group 不应用任意方法,只应用一些众所周知的预定义方法。 Given your example code, I suspect you're thinking about the Sprite Group method update() (and perhaps draw() ), which does call the update() method of every sprite in the group.鉴于您的示例代码,我怀疑您正在考虑 Sprite Group 方法update() (可能还有draw() ),它确实调用了组中每个精灵的update()方法。

If your example was:如果您的示例是:

import pygame
from pygame.sprite import Sprite
from pygame.sprite import Group

class Raindrop(Sprite):

    def __init__(self, screen):
        super().__init__()
        ...
    ...
    def update(self):                        # <<-- HERE, not "drop()"
        # TODO: move/change sprite shomehow
        ...
...
raindrops = Group()
...
raindrops.update()
...

It would work fine.它会工作得很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM