2

I am just starting out on pygame, and wondering how a message can linger in pygame without affecting the loop. Let's say I want the message to display for 5 seconds then disappear, but the game loop will still keep running when it happens. I tried using time.sleep and clock, but those will completely pause the loop until the message stops appearing. How do I make it so that the message will display while the game loop is still running?

Simplified example:

def message_linger():
    #message output code here
    time.sleep(4)

def game_loop():
    #some pygame junk
    message_linger
    pygame.display.update()
    clock.tick(60)

game_loop()
istupidguy
  • 23
  • 1
  • 3

1 Answers1

0

Just keep track of the passed time and use a conditional statement like if passed_time < 5000: FONT.render_to(...).

import pygame as pg
from pygame import freetype


pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
BLUE = pg.Color('dodgerblue')
FONT = freetype.Font(None, 42)
start_time = pg.time.get_ticks()

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True

    screen.fill(BG_COLOR)
    if pg.time.get_ticks() - start_time < 5000:  # 5000 ms
        FONT.render_to(screen, (100, 100), 'the message', BLUE)
    pg.display.flip()
    clock.tick(60)

pg.quit()
skrx
  • 19,980
  • 5
  • 34
  • 48