为什么 Pygame .blit() 函数不起作用?

Why is the Pygame .blit() function not working?

我想把敌人blit到屏幕上但是 enemy() 中的 .blit() 无效。我尝试打印 enemies 列表并添加了它,但它仍然没有将敌人传送到屏幕上。我也没有收到任何错误

这是我的代码

def enemy(enemies):
    enemy = pygame.Rect(width//2, height//2, 100, 100)
    enemies.append(enemy)
    for enemy in enemies:
        window.blit(enemy_transform, enemy)
        enemy.x -= enemy_vel

def main():
    running = True
    clock = pygame.time.Clock()

    player = pygame.Rect(50, height//2 - 50, 150, 150)

    enemies = []

    while running:
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
                pygame.quit
                sys.exit

        keys_pressed = pygame.key.get_pressed()
        player_movement(player, keys_pressed)
        draw_window(player)
        enemy(enemies)

if __name__ == "__main__":
    main()

您必须在应用程序循环中绘制敌人。在应用程序循环之前创建敌人,在应用程序循环中移动它们并在 draw_window.

中绘制它们

确保函数和变量具有不同的名称。在您的代码中,您将名称 enemy 用于函数和变量。此时使用不同的名称。例如:

def draw_window(player, enemies):
    window.blit(background, (0, 0))
    for enemy in enemies:
        window.blit(enemy_transform, enemy)
    window.blit(player_transform, player)
    pygame.display.update()

def move_enemies(enemies):
    for enemy_rect in enemies:
        enemy_rect.x -= enemy_vel
def main():
    running = True
    clock = pygame.time.Clock()

    player = pygame.Rect(50, height//2 - 50, 150, 150)

    enemies = []
    enemy_rect = pygame.Rect(width//2, height//2, 100, 100)
    enemies.append(enemy_rect)

    while running:
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        keys_pressed = pygame.key.get_pressed()
        player_movement(player, keys_pressed)
        move_enemies(enemies)
        
        draw_window(player, enemies)

    pygame.quit()
    sys.exit()