我在为A Level计算项目制作的太空侵略者程序中显示了一个额外的精灵,这是一个问题。

看起来像这样:python - 正在显示额外的 Sprite ?-LMLPHP

我的代码如下所示:

class Enemy(pygame.sprite.Sprite):

    def __init__(self,x,y,direction,enemy_type):
        pygame.sprite.Sprite.__init__(self)

        self.EnemyType = enemy_type
        self.Direction = direction

        if enemy_type == 1:
            enemy_image = pygame.image.load("sprites\\enemy1_1.png")
            self.Speed = 1
            self.Score = 5

        if enemy_type == 2:
            enemy_image = pygame.image.load("sprites\\enemy1_1.png")
            self.Score = 15
            self.Speed = 1

        if enemy_type == 3:
            enemy_image = pygame.image.load("sprites\\enemy1_1.png")
            self.Score = 10
            self.Speed = 1

        if enemy_type == 4:
            enemy_image = pygame.image.load("sprites\\enemy1_1.png")
            self.Score = 20
            self.Speed = 1

        if enemy_type == 5:
            enemy_image = pygame.image.load("sprites\\enemy1_1.png")
            self.Score = 25
            self.Speed = 1

        self.image = pygame.Surface([100, 100])
        self.image.set_colorkey(BLACK)
        self.image.blit(enemy_image,(0,0))
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

    def move_enemy(self):
        if self.Direction == "right":
            self.rect.x += self.Speed
        if self.Direction == "left":
            self.rect.x -= self.Speed

    #draw image
    def draw(self, screen):
        screen.blit(self.image, self.rect)


allEnemies = pygame.sprite.Group()
a_enemies = Enemy(50,50,"right",1)
allEnemies.add(a_enemies)


#For X coords
    spawnPositions = [100,200,300,400,500,600,700]

    yCoord = 10
#creating enemies
    for n in range(5):
        for i in range(len(spawnPositions)):
            xCoord = spawnPositions[i]
            enemy_type = random.randint(1,5)
            enemy = Enemy(xCoord, yCoord,"right", enemy_type)
            allEnemies.add(enemy)
        yCoord = yCoord + 50
#update enemy positions
        loop = 0


        for enemy in (allEnemies.sprites()):
            if enemy.rect.x < 5:
                enemy.rect.y = enemy.rect.y + 15
                enemy.Direction = "right"
            if enemy.rect.x > 750:
                enemy.rect.y = enemy.rect.y + 15
                enemy.Direction = "left"
            loop =+1

        for enemy in (allEnemies.sprites()):
            enemy.move_enemy()
#draw enemies
        allEnemies.draw(gameDisplay)


我从程序中删去了无关的代码,以使您更容易理解。我不太确定为什么要这样做,但我只是想让敌人的班级在如图所示的行中移动,但是旁边会出现一个额外的精灵。

最佳答案

多余的敌人是由辛格尔敌人造成的,该敌人在被主动化时会添加到组中:


  

a_enemies = Enemy(50,50,"right",1)
allEnemies.add(a_enemies)



删除该代码,以解决该问题。

关于python - 正在显示额外的 Sprite ?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60436953/

10-10 18:20