I develop a game, and I blit a text to the screen as follow:
message = font.render( "Hello World" , True)
surface_1.blit(message, some_rect)
So on the screen a message "Hello World" is appearing now. What I need is a way of holding this message for some seconds and then to hide it. An easy way that I think is to create a variable that counts each turn of the loop, when the counter reach a number of rounds (which will be equal to time, 100 rounds = 1 sec) and then to hide the message by just alter the message to null string, like: ""
.
I try this method and works but I need something different, first of all a way to really delete the message from the surface and a better way to hold time for the message BUT this better way I don't want to stop other things that I will add (later) in the game.
For instance, a sprite that will animated using various different states of the picture, to make the animation (man walking). So to sleep/pause the game for some seconds is not a good idea.
There is no way to delete something from a surface. Since the surface has no information about the objects that were blited onto it.
This is roughly how a pygame structure should be:
Let's say you want to show the string "Hello World" for 5 seconds.
What I would do, is create a VolatileSprite class, that will have a Sprite along with a timer object. Then loop to see if the time has passed, and if, I schedule the object for removal.
Since we need a way to know how much time has passed, we can use the pygame.time.Clock(). This class has a method
tick()
that returns the amount of ms after the last call totick()
. This so called time delta, can be passed to various functions to update the sprites.Going back to our VolatileSprite. In the
update(delta)
method of the VolatileSprite, you can check if the time has passed, and if so you can set it as removed. This way, in your main code you can loop through all your sprites and remove the ones that should be removed.Same principle goes for animation, the AnimatedSprite will have a timer, that when a certain amount of ms passes, it will change the picture to be drawn.