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?
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With