Madushan Pathirana
Madushan Pathirana

Reputation: 37

Rendering vanishing text in pygame

I'm making a small game using pygame. When the game starts I want to display "start" and vanish it after a few seconds. How to do that?

Upvotes: 3

Views: 2177

Answers (2)

user16351537
user16351537

Reputation: 11

Please try adding below code:

for i in range(whatevernumberbutnotover1000):
    mytext.set_alpha(i)

Upvotes: 0

skrx
skrx

Reputation: 20438

First you need a timer variable (there are other questions about timers, so I won't explain them here). I'm just counting the frames in the following example.

To remove the text abruptly you can just keep blitting it until the time is up.

if timer > 0: 
    screen.blit(txt_surf, (position))

The slowly disappearing text can be achieved by filling the text surface with white and the current alpha value (which is reduced each frame) and by passing the pg.BLEND_RGBA_MULT special flag. That will affect only the alpha channel of the surface.

txt_surf.fill((255, 255, 255, alpha), special_flags=pg.BLEND_RGBA_MULT)

Also, use a copy of the original text surface, otherwise it would subsequently reduce the alpha of the previously modified surface and the text would disappear too quickly.

import pygame as pg


def main():
    pg.init()
    clock = pg.time.Clock()
    screen = pg.display.set_mode((640, 480))
    font = pg.font.Font(None, 64)
    orig_surf = font.render('Enter your text', True, pg.Color('royalblue'))
    txt_surf = orig_surf.copy()
    alpha = 255  # The current alpha value of the surface.
    timer = 20  # To get a 20 frame delay.

    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                return

        if timer > 0:
            timer -= 1
        else:
            if alpha > 0:
                # Reduce alpha each frame, but make sure it doesn't get below 0.
                alpha = max(0, alpha-4)
                # Create a copy so that the original surface doesn't get modified.                
                txt_surf = orig_surf.copy()
                txt_surf.fill((255, 255, 255, alpha), special_flags=pg.BLEND_RGBA_MULT)

        screen.fill((30, 30, 30))
        screen.blit(txt_surf, (30, 60))
        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    main()
    pg.quit()

enter image description here

Upvotes: 4

Related Questions