Python SpriteGroup-添加多个对象
我正在尝试创建一个精灵类,用户可以在其中使用教程从随机位置定义任意数量的精灵并将其添加到屏幕上。但是,当我尝试运行当前程序时,它会将错误 AttributeError:类型对象“Sprite”没有属性“Sprite” 但我不明白为什么,所有的逻辑似乎都是正确的 有什么建议吗 这是我的密码:Python SpriteGroup-添加多个对象,python,pygame,Python,Pygame,我正在尝试创建一个精灵类,用户可以在其中使用教程从随机位置定义任意数量的精灵并将其添加到屏幕上。但是,当我尝试运行当前程序时,它会将错误 AttributeError:类型对象“Sprite”没有属性“Sprite” 但我不明白为什么,所有的逻辑似乎都是正确的 有什么建议吗 这是我的密码: import pygame, sys, random pygame.init() black = (0, 0, 0) image = pygame.image.load("resources/images/
import pygame, sys, random
pygame.init()
black = (0, 0, 0)
image = pygame.image.load("resources/images/img.png")
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 400
sprite_width = 5
sprite_height = 5
sprite_count = 5
# no changes here when using sprite groups
class Sprite(pygame.sprite.Sprite):
def __init__(self, Image, pos):
pygame.sprite.Sprite.__init__(self)
self.image =pygame.image.load("resources/images/img.png")
self.rect = self.image.get_rect()
self.rect.topleft = pos
self.pygame.display.set_caption('Sprite Group Example')
self.clock = pygame.time.Clock()
# this is a how sprite group is created
self.sprite = pygame.sprite.Group()
def update(self):
self.rect.x += 1
self.rect.y += 2
if self.rect.y > SCREEN_HEIGHT:
self.rect.y = -1 * sprtie_height
if self.rect.x > SCREEN_WIDTH:
self.rect.x = -1 * sprite_width
@classmethod
def sprites(self):
for i in range(actor_count):
tmp_x = random.randrange(0, SCREEN_WIDTH)
tmp_y = random.randrange(0, SCREEN_HEIGHT)
# all you have to do is add new sprites to the sprite group
self.sprite.add(Sprite(image, [tmp_x, tmp_y]))
@classmethod
def game_loop(self):
screen = pygame.display.set_mode([640, 400])
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill(black)
# to update or blitting just call the groups update or draw
# notice there is no for loop
# this will automatically call the individual sprites update method
self.sprite.update()
self.sprite.draw(screen)
self.pygame.display.update()
self.clock.tick(20)
Sprite.sprites()
Sprite.game_loop()
您定义了类方法(@classmethod
),但self.sprite
仅存在于对象/实例中,而不存在于类中-它是在装入新对象/实例时在\uuuuuuu init\uuuuuu
中创建的
删除@classmethod
以拥有对象/实例方法,并且对self.sprite
没有问题
或者在\uuuu init\uuuu
外部创建sprite
以获取类属性
class Sprite(pygame.sprite.Sprite):
sprite = pygame.sprite.Group()
def __init__(self, Image, pos)
# instance variable - value copied from class variable
print self.sprite
# class variable
print self.__class__.sprite
@classmethod
def sprites(self):
# instance variable not exists
# class variable
print self.sprite
精灵通常是单数的,因此不应将精灵组作为成员变量。精灵组应容纳所有单个精灵。就像在你发布的链接中一样。我如何在其他方法(如sprites)中引用sprite变量,因为它现在不是全局变量。sprite-它是类和实例中的全局变量。若要更改类属性的值,请使用
self.\uuuu class\uuu
前缀,self.\uu class\uuu.sprite=pygame.sprite.Group()
一如既往地感谢Furas