我試圖創建一個簡單的遊戲,其中的重點是在一定的時間內收集儘可能多的塊,比如說10秒。我怎樣才能讓秒錶開始在程序開始時開始滴答滴答,當它達到10秒時,做一些事情(在這種情況下,退出一個循環)?Python中的秒錶
回答
import time
now = time.time()
future = now + 10
while time.time() < future:
# do stuff
pass
另外,如果你已經得到了你的循環:
while True:
if time.time() > future:
break
# do other stuff
這種方法與pygame效果很好,因爲它非常需要你有一個大的主循環。
在這個例子中,循環運行每秒十秒鐘:
import datetime, time
then = datetime.datetime.now() + datetime.timedelta(seconds=10)
while then > datetime.datetime.now():
print 'sleeping'
time.sleep(1)
的threading.Timer
對象(documentation)可以算十秒鐘,然後把它設置一個事件標誌,指示循環應退出。
該文檔指出時間可能不準確 - 您必須測試它是否足夠準確以適合您的遊戲。
如果系統時間改變,使用time.time()/ datetime.datetime.now()將會中斷(用戶更改時間,它會通過NTP等時間同步服務進行更正或從日期保存切換到日期保存時間!)。
time.monotonic()或time.perf_counter()似乎是正確的方法,但它們只能從python 3.3獲得。另一種可能是使用threading.Timer。這是否比time.time()和朋友更可靠取決於內部實現。另外請注意,創建新線程在系統資源方面並不完全免費,因此在需要並行運行大量定時器的情況下,這可能是一個不好的選擇。
時間是嘈雜的,所以time.time工作足夠好,他不需要它完美otherwice他會說我的時間需要..,.... 1完美或別的東西。定時10秒就足夠了。 – 2015-10-20 06:09:51
從夏令時切換到夏令時時,時間將會減少一小時,並且可能會倒退。如果系統時間改變了呢?這到底是如何「足夠精確」? – poizan42 2016-02-29 15:36:51
作爲一個學習鍛鍊我自己,我創建了一個類可以創建多個秒錶計時情況下,你可能會發現有用的(我敢肯定,在時間的模塊周圍有更好/更簡單的版本或類似)
import time as tm
class Watch:
count = 0
description = "Stopwatch class object (default description)"
author = "Author not yet set"
name = "not defined"
instances = []
def __init__(self,name="not defined"):
self.name = name
self.elapsed = 0.
self.mode = 'init'
self.starttime = 0.
self.created = tm.strftime("%Y-%m-%d %H:%M:%S", tm.gmtime())
Watch.count += 1
def __call__(self):
if self.mode == 'running':
return tm.time() - self.starttime
elif self.mode == 'stopped':
return self.elapsed
else:
return 0.
def display(self):
if self.mode == 'running':
self.elapsed = tm.time() - self.starttime
elif self.mode == 'init':
self.elapsed = 0.
elif self.mode == 'stopped':
pass
else:
pass
print "Name: ", self.name
print "Address: ", self
print "Created: ", self.created
print "Start-time: ", self.starttime
print "Mode: ", self.mode
print "Elapsed: ", self.elapsed
print "Description:", self.description
print "Author: ", self.author
def start(self):
if self.mode == 'running':
self.starttime = tm.time()
self.elapsed = tm.time() - self.starttime
elif self.mode == 'init':
self.starttime = tm.time()
self.mode = 'running'
self.elapsed = 0.
elif self.mode == 'stopped':
self.mode = 'running'
#self.elapsed = self.elapsed + tm.time() - self.starttime
self.starttime = tm.time() - self.elapsed
else:
pass
return
def stop(self):
if self.mode == 'running':
self.mode = 'stopped'
self.elapsed = tm.time() - self.starttime
elif self.mode == 'init':
self.mode = 'stopped'
self.elapsed = 0.
elif self.mode == 'stopped':
pass
else:
pass
return self.elapsed
def lap(self):
if self.mode == 'running':
self.elapsed = tm.time() - self.starttime
elif self.mode == 'init':
self.elapsed = 0.
elif self.mode == 'stopped':
pass
else:
pass
return self.elapsed
def reset(self):
self.starttime=0.
self.elapsed=0.
self.mode='init'
return self.elapsed
def WatchList():
return [i for i,j in zip(globals().keys(),globals().values()) if '__main__.Watch instance' in str(j)]
這是我知道這樣做的最短途徑:
def stopWatch():
import time
a = 0
hours = 0
while a < 1:
for minutes in range(0, 60):
for seconds in range(0, 60):
time.sleep(1)
print(hours,":", minutes,":", seconds)
hours = hours + 1
新的蟒蛇世界!
我需要一個系統時間獨立秒錶所以我沒有翻譯我的舊的C++類成Python:
from ctypes.wintypes import DWORD
import win32api
import datetime
class Stopwatch:
def __init__(self):
self.Restart()
def Restart(self):
self.__ulStartTicks = DWORD(win32api.GetTickCount()).value
def ElapsedMilliSecs(self):
return DWORD(DWORD(win32api.GetTickCount()).value-DWORD(self.__ulStartTicks).value).value
def ElapsedTime(self):
return datetime.timedelta(milliseconds=self.ElapsedMilliSecs())
這有由於DWORD數學,但注意碾過問題沒有49天是GetTickCount
具有約15毫秒的粒度所以如果您需要1-100毫秒的時間範圍,請不要使用此類。
歡迎任何改進或反饋!
我在我的python程序中使用這個函數。該函數的輸入是例如:
值=了time.time()
def stopWatch(value):
'''From seconds to Days;Hours:Minutes;Seconds'''
valueD = (((value/365)/24)/60)
Days = int (valueD)
valueH = (valueD-Days)*365
Hours = int(valueH)
valueM = (valueH - Hours)*24
Minutes = int(valueM)
valueS = (valueM - Minutes)*60
Seconds = int(valueS)
print Days,";",Hours,":",Minutes,";",Seconds
start = time.time() # What in other posts is described is
***your code HERE***
end = time.time()
stopWatch(end-start) #Use then my code
提示語法錯誤,並引用行中的天'valueH =(valueD-days)* 365' – jxramos 2015-05-27 23:49:00
現在解決了 – 2015-10-14 12:04:18
- 1. 在Python代表微秒2.7
- 2. recyclerView中的秒錶
- 3. java中的秒錶
- 4. 毫秒級的jQuery秒錶
- 5. 秒錶。數秒。 javafx
- 6. Java中的Swing Timer秒錶
- 7. Xcode中的秒錶問題
- 8. 在JS秒錶中格式化毫秒
- 9. 的NSTimer - 秒錶
- 10. 的jQuery:秒錶
- 11. 使用python讀取excel表格中的秒數
- 12. 在python中編寫提醒/秒錶程序的最佳方式?
- 13. 重新格式化Python中的秒錶.csv
- 14. 的Python秒鐘小時
- 15. Python的指定由毫秒
- 16. 秒ImageMagick的過程在Python
- 17. 如何在C#中使秒錶顯示秒和毫秒?
- 18. 從秒錶中返回十分之一秒百分之一秒
- 19. 的Thread.Sleep與秒錶
- 20. 如何從python中的日期時間字符串中刪除秒和毫秒
- 21. 在TextBlock中運行秒錶
- 22. Java中是否有秒錶?
- 23. 如何將秒錶刻度轉換爲納秒,毫秒和秒?
- 24. 裝飾納秒在Python納秒的100的(大熊貓)
- 25. Python中沒有運行每秒
- 26. 在python matplotlib.dates中繪製毫秒
- 27. Asp.Net秒錶C#
- 28. 反應秒錶
- 29. 多個秒錶
- 30. RDTSC與秒錶
在Python 3.3+'time.monotonic()'可能是[避免一些時間調度問題](HTTP有用:/ /stackoverflow.com/a/20529909/4279)。 – jfs 2013-12-11 21:27:42