简体   繁体   English

如何在Python 2.7中创建计时器?

[英]How do you create a timer in Python 2.7?

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'(ie longer paddle, faster paddle movement, a larger ball). 我目前正在使用Pyglet库编程一个打砖块克隆,我想制作一个计时器,该计时器最多可为游戏的“奖励”计时20秒(例如,更长的拨片,更快的拨片运动,更大的球)。 I've been digging the internet as hard as I can but I couldn't find the answer. 我一直在努力地挖掘互联网,但找不到答案。

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. 好吧,我不知道您计算奖金的逻辑,但是我认为您可以通过创建一个每20秒执行一次的线程来实现20秒计时器。

Here i have created function count_bonuses that will contain your game logic and get executed after every 20 seconds. 在这里,我创建了一个函数count_bonuses ,它将包含您的游戏逻辑并每20秒执行一次。

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. 如果要停止该线程,或者可以根据您的游戏逻辑创建一个KeyboardInterrupt来通过键盘中断来停止线程,则可以创建自己的stopflag

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

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM