How to display an image after a time interval?
Start the timer when the user clicks a mouse button, then calculate the passed time in the main loop and if it's >= 3
, blit the image.
import pygame as pg
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
font = pg.font.Font(None, 40)
img = pg.Surface((100, 100))
img.fill((190, 140, 50))
click_time = 0
passed_time = 0
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
# Start the timer.
elif event.type == pg.MOUSEBUTTONDOWN:
click_time = pg.time.get_ticks()
screen.fill((30, 30, 30))
if click_time != 0: # If timer has been started.
# Calculate the passed time since the click.
passed_time = (pg.time.get_ticks()-click_time) / 1000
# If 3 seconds have passed, blit the image.
if passed_time >= 3:
screen.blit(img, (50, 70))
txt = font.render(str(passed_time), True, (80, 150, 200))
screen.blit(txt, (50, 20))
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()