Skip to content
Advertisement

How does Pygame know what is layer 1 (background) vs the sprites displayed on the screen?

My teacher was looking over my code today and wanted me to explain to him why I could use

WIDTH, HEIGHT = 900, 500
PLAYER, SIZE = 34, 34
WIN = pygame.display.set_mode((WIDTH,HEIGHT))

Player_1 = pygame.transform.scale(pygame.image.load(os.path.join('skins', 'player.png')), (PLAYER,SIZE))
P1 = pygame.transform.rotate(Player_1, 270)
Player_2 = pygame.transform.scale(pygame.image.load(os.path.join('skins', 'enemy.png')), (PLAYER,SIZE))
P2 = pygame.transform.rotate(Player_2, 270)
SKY = pygame.transform.scale(pygame.image.load(os.path.join('skins', 'bg.png')), (WIDTH,HEIGHT))
#this will search our folder 'skins' for the file 'bg' to make our background
BULLET_SPEED = 5
BULLET_NUMBER = 5

BULLET_FIRE_SOUND = pygame.mixer.Sound(os.path.join('soundEffects', 'tiro.wav'))
BULLET_DAMAGE_SOUND = pygame.mixer.Sound(os.path.join('soundEffects', 'batida.wav'))


def draw(yellow, blue, yellow_bullets, blue_bullets, yellow_health, blue_health):
    WIN.blit(SKY, (0,0)) 
    pygame.draw.rect(WIN, WHITE, MID_BORDER)
    WIN.blit(P1, (yellow.x, yellow.y))
    WIN.blit(P2, (blue.x, blue.y))
    #pygame starts tracking at the top left with 0,0
    for bullet in blue_bullets:
        pygame.draw.rect(WIN, BLUE, bullet)
    for bullet in yellow_bullets:
        pygame.draw.rect(WIN, YELLOW, bullet)
    yellow_health_txt = HEALTH_FONT.render("Health: " + str(yellow_health), 1, WHITE)
    blue_health_txt = HEALTH_FONT.render("Health: " + str(blue_health), 1, WHITE)
    WIN.blit(yellow_health_txt,(10,10))
    WIN.blit(blue_health_txt,(WIDTH - blue_health_txt.get_width() - 10, 10))


    pygame.display.update()

and pygame knew to make the bg.png file the background and the player/enemy.png in the foreground.

I explained that maybe it was due to bg.png taking the HEIGHT and WIDTH arg therefore stretching the whole screen, but almost immediately I saw a flaw in this logic as player/enemy.png could easily be behind the bg.png and be hidden completely.

Obviously it’s not taking the order I declare them as I declare bg.png last.

So is there any way to understand the logic behind how pygame makes the distinction between background and foreground or does it go even deeper

IE: layer {1..100+}

I’m sorry if this is a silly question or has been answered I couldn’t find it when researching.

EDIT

After further review I think I also get that I initialize SKY at (0,0) which is the top left corner.

Is that what defined this as a background? And (yellow.x, yellow.y) is that indicating the position my sprites appear?

Advertisement

Answer

Pygame draws surfaces in the order you .blit() them, so as SKY (which is the bg.png image) is blit first, it is the background.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement