Search code examples
pythonpython-3.xtimetimerpygame

Football pygame, need help on timer


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?


Solution

  • 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.