How to properly clear all images that were "blitted" onscreen using pygame?

StackOverflow https://stackoverflow.com/questions/13420914

  •  29-11-2021
  •  | 
  •  

Question

I was wondering how does pygame.blit manages the images blitted on screen. When I blit an multiple images on the screen, I see that each image is stacked on top the previous one.

How do I clear all these images? Wouldn't(somehow) there be a big problem when there are LOTS of images stacking on top of each other on the screen? Currently, I'm just blitting a white bg or custom bg on the whole screen to "clear" the screen. So far no problems or anything since the app I am working on is very small.

Était-ce utile?

La solution

When you blit an image to a surface, it basicly draws it on the surface. The location of the blitting or the object blitted is not saved and cannot be changed. It's like if you were painting the images onto a canvas. The new ones would go over the old ones and there would be no way to get rid of one image if it were colliding with another image.

The most common approach to solving this is to just completly clear the screen using surface.fill(), and redraw the images each frame.

To answer your question about if there woudl be problems when there are lots of images, no. The window will only be saved as each individual pixel being a certain color, much like a regular picture you would take a camera, so no matter how many objects you blit, the game will always take the same amount of time.

Autres conseils

There are multiple approaches:

  • Clean the whole background, as you are doing. If the computer keeps up with the fps, perhaps it's better to leave it like this.

  • Clean only the areas where you blitted objects (see pygame.sprite.RenderUpdates)

  • In your case, if you have many stacked objects, perhaps it's better to write your own solution, trying to find the union between colliding rectangles, to avoid reblitting the same background over and over.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top