Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Countdown timer in Pygame

Tags:

python

pygame

I started using pygame and I want to do simple game. One of the elements which I need is countdown timer. How can I do the countdown time (eg 10 seconds) in PyGame?

like image 627
adamo94 Avatar asked Jun 08 '15 23:06

adamo94


People also ask

What is Pygame time clock ()?

pygame.time.ClockThis function is used to create a clock object which can be used to keep track of time. The various methods of clock object are below: tick():This method should be called once per frame. It will compute how many milliseconds have passed since the previous call.

How do you set a time delay on Pygame?

For Pygame, however, using pygame. time. delay() will pause for a given number of milliseconds based on the CPU clock for more accuracy (as opposed to pygame. time.


1 Answers

Another easy way is to simply use pygame's event system.

Here's a simple example:

import pygame
pygame.init()
screen = pygame.display.set_mode((128, 128))
clock = pygame.time.Clock()

counter, text = 10, '10'.rjust(3)
pygame.time.set_timer(pygame.USEREVENT, 1000)
font = pygame.font.SysFont('Consolas', 30)

run = True
while run:
    for e in pygame.event.get():
        if e.type == pygame.USEREVENT: 
            counter -= 1
            text = str(counter).rjust(3) if counter > 0 else 'boom!'
        if e.type == pygame.QUIT: 
            run = False

    screen.fill((255, 255, 255))
    screen.blit(font.render(text, True, (0, 0, 0)), (32, 48))
    pygame.display.flip()
    clock.tick(60)

enter image description here

like image 117
sloth Avatar answered Sep 28 '22 00:09

sloth