Search code examples
pythontimerpygamesleep

How to make a timer in python without freezing up the entire code


I am coding Mario using Pygame and I'm coding the blocks right now. I want to make a timer so when I hit the block after a second the block goes back to its original position to make the hitting animation. The problem is when making the timer with sleep it freezer the entire game for the duration of the timer. I need the code to run and after a second that previous block of code to kick in.

I have tried using sleep to make the timer but it freezes the entire game. can anyone drop me some knowledge? Thanks!


Solution

  • I would suggest you use the threading module and thread two functions.

    At the end, you can format as such:

    from threading import Thread
    if __name__ == '__main__':
        Thread(target = game()).start()
        Thread(target = timer()).start()
    

    Another option is the timeit module. You can set a timer and check when a certain time is hit with a if/while statement.

    A third option is with the time module you used for sleep:

    import time
    
    max_time = #the time you want
    start_time = time.time()
    while (time.time() - start_time) < max_time:
        game()