How do you create a timer in Python 2.7?

2019-08-09 03:59发布

问题:

I'm currently programming a brick-breaker clone using the Pyglet library and I would like to make a timer that counts up to 20 seconds for the game's 'bonuses'(i.e. longer paddle, faster paddle movement, a larger ball). I've been digging the internet as hard as I can but I couldn't find the answer.

回答1:

Try this.

import mx.DateTime as mt
import time
def settime():
    st=mt.now()
    while(True):
        time.sleep(1)
        tt=mt.now()
        if (int((tt-st).seconds)==20):
            print 'level up'
            st=mt.now()
        elif (int((tt-st).seconds)>20):
            print 'logic error'
        else:
            print int((tt-st).seconds)


回答2:

import threading

bonuses_count = 0

def count_bonuses():
    global bonuses_count
    # paddle = count(paddle) # something your logic part here
    bonuses_count += 20
    print "counting bonuses :- ", (bonuses_count) 
    t = threading.Timer(20.0, count_bonuses).start()

t = threading.Timer(20.0, count_bonuses)
t.start()

Well i don't know your logic of counting bonuses but i think you can acheive 20 seconds timer by creating a thread which will executing after every 20 seconds.

Here i have created function count_bonuses that will contain your game logic and get executed after every 20 seconds.

You can create your own stopflag if you want to stop this thread or create an KeyboardInterrupt to stop the thread with keyboard intruption based on your gamming logic.

counting bonuses :-  20
counting bonuses :-  40
counting bonuses :-  60
counting bonuses :-  80