pygame我的敌人阶级移动后消失

时间:2018-11-09 12:43:18

标签: python class pygame

当您第一次加载游戏时,两个矩形都在那里,但是当玩家移动时,敌人矩形消失了。该代码可以正常工作。

扩展我试图让敌人的阶级不断地上下移动而无需按下任何键。

reduce()

2 个答案:

答案 0 :(得分:1)

您仅在hailSeq(11)

中将类设置为静态时绘制精灵。

您需要在[11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1] 之前的[11, 34] 函数的每个循环中绘制它们。

由于当前情况,玩家和敌人都不应在第一帧之外显示

答案 1 :(得分:0)

您必须每帧清除屏幕-您可以通过使背景模糊来完成此操作-然后绘制精灵。将运动与图形代码分开,以便在清除屏幕后可以使精灵变白。

class Player(pygame.sprite.Sprite):
    def __init__(self):
        self.rect = pygame.draw.rect(screen, (0,0,128), (50,560,50,25))
        self.dist = 100

    # Separate the movement and the drawing.
    def move(self, x, y):
        self.rect = self.rect.move(x*self.dist, y*self.dist)

    def draw(self, screen):
        pygame.draw.rect(screen, (0, 0, 128), self.rect)

    def handle_keys(self):
        keys = pygame.key.get_pressed()
        if keys[K_LEFT]:
            self.move(-0.05,0)
        elif keys[K_RIGHT]:
            self.move(0.05,0)
        elif keys[K_UP]:
            self.move(0,-0.05)
        elif keys[K_DOWN]:
            self.move(0,0.05)
        elif keys[K_SPACE]:
            self.move(0.05,-0.05)
        if self.rect.right > 1280:
            self.rect.right = 1280
        if self.rect.left < 0:
            self.rect.left = 0
        if self.rect.bottom > 720:
            self.rect.bottom = 720
        if self.rect.top < 0:
            self.rect.top = 0


class Enemy(pygame.sprite.Sprite):

    def __init__(self):
        self.x = random.randint(50,450)  # x is now an attribute.

    def draw(self, screen):
        self.rect = pygame.draw.rect(screen, (128,0,0), (300, self.x, 50, 25))


def main():
    clock = pygame.time.Clock()  # A clock to limit the frame rate.
    player = Player()
    enemy = Enemy()

    running = True
    while running:
        player.handle_keys()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        # Clear the screen every frame by blitting the background.
        screen.blit(background, (0, 0))
        # Then draw the enemy and the player.
        enemy.draw(screen)
        player.draw(screen)
        pygame.display.flip()
        clock.tick(60)  # Limit the frame rate to 60 FPS.

我还建议您检查Sprite组的工作方式,然后您可以摆脱draw方法,只需调用sprite_group.draw(screen)即可绘制每个包含的Sprite。这是tutorial