I want to make a football game and I want to make it so that the player only gets 10 seconds to get to the end or else the game ends.
How can I do that?
I want to make a football game and I want to make it so that the player only gets 10 seconds to get to the end or else the game ends.
How can I do that?
I would suggest using pygame.time.set_timer()
and pygames event mechanics since you already likely have an event processing loop in your game. See the set_timer docs here.
You do something like this:
pygame.time.set_timer(pygame.USEREVENT, 10000)
to start the a 10 second timer that will trigger a pygame.USEREVENT when it goes off. You would watch for that event in the event loop by adding a test like this:
if event.type == pygame.USEREVENT:
# Countdown expired
I doubt that you require it, but if you need multiple timers and need to be able to tell them apart, you can create an event with an attribute that you can set to different values to track them. Something like this:
my_event = pygame.event.Event(pygame.USEREVENT, {"tracker": "gameover"})
pygame.time.set_timer(my_event , 2000)
[edit]
For other events you just create more of them and change what is set in the "tracker", like this:
my_other_event = pygame.event.Event(pygame.USEREVENT, {"tracker": "something_else"})
Then in your event loop you look for them. Something like this:
for event in pygame.event.get():
...
# You found your event. Do something about it
if event == my_event:
...
# You found your other event. Do something about it
if event == my_other_event:
...
Hope that clarifies things.
You can use the time module (click here for the docs). Here's a program that would print "I'm a replacement for whatever you do in pygame!" until 5 seconds since the start has passed
import time
start = time.time()
seconds = 5
while not time.time() >= start + seconds:
print("I'm a replacement for whatever you do in pygame!")
print(str(seconds)," seconds is up!")
Get the start time from the function pygame.time.get_ticks()
. This gives you the current time (since pygame started) in milliseconds. Store this somewhere.
MAX_EVADE_TIME = 10000 # milliseconds
player_start_time = pygame.time.get_ticks()
Then during the main loop, continually look at the time, and work out if the limit has passed.
while not exiting:
...
time_now = pygame.time.get_ticks()
# is the time limit used-up?
if ( time_now > player_start_time + MAX_EVADE_TIME ):
doGameOver() # or whtever