Sprite Group - 添加多个对象

时间:2013-12-09 11:05:16

标签: python pygame

我正在尝试创建一个精灵类,用户可以使用this教程从随机位置定义并向屏幕添加任意数量的精灵。但是,当我尝试运行当前程序时,它会输出错误

  

AttributeError:类型对象'Sprite'没有属性'sprite'

但我不明白为什么,所有逻辑似乎都是正确的。

有什么建议吗?

继承我的代码:

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()

1 个答案:

答案 0 :(得分:0)

您定义类方法(@classmethod)但self.sprite仅存在于不在类中的对象/实例中 - 当您创建新对象/实例时,它在__init__中创建。

删除@classmethod以获得对象/实例方法,并且self.sprite没有问题。

或在sprite之外创建__init__以获取类属性

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