0
\$\begingroup\$

Consider the following code:

import pygame
pygame.init()

MAGENTA, CYAN = (255, 0, 255), (0, 255, 255)

screen = pygame.display.set_mode((800, 800))

box = pygame.Surface((600, 600))
box.fill(MAGENTA)
screen.blit(box, (0, 0))

subbox = pygame.Surface((400, 400))
subbox.fill(CYAN)
box.blit(subbox, (0, 0))

#box.blit(subbox, (0, 0))
#screen.blit(box,(0,0))

pygame.display.flip()
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            pygame.quit()

I would expected to get a cyan square in a magenta square in the window. However, the cyan square is not visible. When blitting the cyan square first, and the magenta square after, the intended result is achieved (see comment blocks). It seems to me more logical, and useful to be able to blit surfaces 'from bottom to top'.

Is this possible, and how? Why does my approach not work?

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

You just have to blit the surfaces inside the main loop and also update the display at the end of it. Keep in mind that you should never blit to the screen outside of the main loop.

If you run this code below, everything will work as wanted :

import pygame
pygame.init()

MAGENTA, CYAN = (255, 0, 255), (0, 255, 255)

screen = pygame.display.set_mode((800, 800))

box = pygame.Surface((600, 600))
box.fill(MAGENTA)
subbox = pygame.Surface((400, 400))
subbox.fill(CYAN)
running = True

while running:
    screen.blit(box, (0, 0))
    box.blit(subbox, (0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            pygame.quit()
    pygame.display.flip()

And concerning the order of blitting surfaces, just think of the screen as layers that are blitted on each other, so the first surface you blit to the screen inside the main loop will be the background, the next one will be on top of it and so on.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Awesome. Thanks! \$\endgroup\$
    – Erithax
    Commented Jul 31, 2021 at 16:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .