Countdown timer for pygame

Lucas Murphy picture Lucas Murphy · Aug 2, 2013 · Viewed 13.9k times · Source

I asked a question earlier about a multiple collision detection but I don't have the skill to create code to fix that problem instead I am just adding a second wall and trying to put in a timer.

My question is how do I put a timer into my code?

It needs to count down and when it hits 00:00 show the text: GAME OVER and end the game. I am putting in the main line of my code if that helps. If you need more code such as classes etc. I am happy to post it.

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

            #This makes the player move
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                player.changespeed(-6,0)
            if event.key == pygame.K_RIGHT:
                player.changespeed(6,0)
            if event.key == pygame.K_UP:
                player.changespeed(0,-6)
            if event.key == pygame.K_DOWN:
                player.changespeed(0,6)

        #This stops the player from moving
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                player.changespeed(6,0)
            if event.key == pygame.K_RIGHT:
                player.changespeed(-6,0)
            if event.key == pygame.K_UP:
                player.changespeed(0,6)
            if event.key == pygame.K_DOWN:
                player.changespeed(0,-6)

    player.updateWall(wall_list)

    window.fill(black)

    movingsprt.draw(window)
    wall_list.draw(window)

    pygame.display.flip()

    clock.tick(40)

pygame.quit()            

Answer

The-IT picture The-IT · Aug 3, 2013

Like Hans Then said, you can use the pygame.time.set_timer() method to call a function after a specific amount of time has passed. But in terms of showing how much time has passed you are probably better off using another method.

Using the pygame.time.Clock.tick_busy_loop method, you can controll how many FPS your game runs at and track how much time has gone by, since it returns how many millisecons have passed since the last call:

clock = pygame.time.Clock()
minutes = 0
seconds = 0
milliseconds = 0

while True: #game loop
    #do stuff here
    if milliseconds > 1000:
        seconds += 1
        milliseconds -= 1000
    if seconds > 60:
        minutes += 1
        seconds -= 60

    print ("{}:{}".format(minutes, seconds))

    milliseconds += clock.tick_busy_loop(60) #returns the time since the last time we called the function, and limits the frame rate to 60FPS