我有一個遊戲,我已經寫了我的第一個項目,我想有一個系統,我可以玩和暫停遊戲。當你點擊取消暫停按鈕時,我希望它每1秒鐘調用一次函數來提前計算日期。 Time.sleep會停止整個程序,所以對我沒有用處,而且我無法在啓動線程後重新啓動線程。這是推進日的功能。Python每秒鐘都會調用一個函數?
def time():
global timer
timer = threading.Timer(1.0, time)
timer.start()
thirtyonemonths = [1, 3, 5, 7, 8, 10, 12]
thirtymonths = [4, 6, 9, 11]
globalvars.day = globalvars.day + 1
for self in thirtyonemonths:
if self == globalvars.month:
print "hi"
if globalvars.day == 32:
globalvars.day = 1
globalvars.month = globalvars.month + 1
for self in thirtymonths:
if self == globalvars.month:
print "hi"
if globalvars.day == 31:
globalvars.day = 1
globalvars.month = globalvars.month + 1
if globalvars.month == 2:
print "hi"
if globalvars.day == 29:
globalvars.day = 1
globalvars.month = globalvars.month + 1
if globalvars.month == 13:
globalvars.month = 1
globalvars.year = globalvars.year + 1
threading.Thread.time(self)
timer = threading.Timer(1.0, time)
後來我當按鈕被點擊檢查它是否暫停或直到我按下按鈕第三次
if b.collidepoint(pos):
if globalvars.ispaused == 1:
globalvars.ispaused = 0
timer.start()
break
if globalvars.ispaused == 0:
globalvars.ispaused = 1
timer.cancel()
break
一切完美彌補了代碼。有誰知道一種方式,我可以重新啓動線程或可能使用不同的方法來做我想要的?
@Apero:他正在使用線程。這就是'threading.Timer'的意思。 – abarnert 2014-10-28 19:09:00
http://stackoverflow.com/questions/8600161/executing-periodic-actions-in-python – 2014-10-28 19:11:49
也看看這個:https://docs.python.org/2/library/sched.html – 2014-10-28 19:12:46