Liczenie czasu w PyGame za pomocą time.get_ticks()
W Pygame nie ma specjalnej funkcji do liczenia ile czasu minęło od
jakiegoś wydarzenia.
Wszelkie działania z czasem opierają się na funkcji
pygame.time.get_ticks()
, która podaje ilość milisekund (tyknięć) od
wywołania pygame.init()
.
Nie da się tej liczby wyzerować więc podstawowym sposobem liczenia czasu jest odejmowanie
# kiedy zaczynasz grę
start = time.get_ticks()
# w trakcie gry
current = time.get_ticks()
# czas trwania gry - w milisekundach lub sekundach
milisekundy = current - start
sekundy = (current - start)/1000
Przykład klasy Timer wykorzystującej powyższy sposób
class Timer():
def __init__(self):
self._start = 0
def start(self):
self._start = pygame.time.get_ticks()
def current(self):
return (pygame.time.get_ticks() - self._start)/1000
Przykład użycia
import pygame
#-----------------------------------------------
class Timer():
def __init__(self):
self._start = 0
def start(self):
self._start = pygame.time.get_ticks()
def current(self):
return (pygame.time.get_ticks() - self._start)/1000
#-----------------------------------------------
pygame.init()
t = Timer()
t.start() # start timera
pygame.time.wait(3000) # dla testów
print t.current() # wypisanie sekund: 3
pygame.time.wait(2000) # for test only
print t.current() # wypisanie sekund: 5
t.start() # restart timera
pygame.time.wait(3000) # dla testów
print t.current() # wypisanie sekund: 3
If you like it
Buy a Coffee
