2013-04-30 77 views
3

我想寫一個python遊戲循環,希望考慮到FPS。什麼是調用循環的正確方法?我考慮過的一些可能性如下。我試圖不使用像pygame這樣的庫。在Python中編寫遊戲循環的正確方法是什麼?

1.

while True: 
    mainLoop() 

2.

def mainLoop(): 
    # run some game code 
    time.sleep(Interval) 
    mainLoop() 

3.

def mainLoop(): 
    # run some game code 
    threading.timer(Interval, mainLoop).start() 

4. 使用sched.scheduler?

+0

第二個和第三個選項,從自身開始同樣的方法,所以會有越來越多的東西隨着時間的推移... – eumiro 2013-04-30 13:33:28

+0

「我不希望使用一個框架像pygame的」 - 那你想用什麼? 'Tkinter'?我想你需要告訴我們你的計劃,然後才能給你任何建議。 – mgilson 2013-04-30 13:33:44

+0

另外,1應該寫成'while True:':) – mgilson 2013-04-30 13:34:48

回答

7

如果我理解正確,您希望將您的遊戲邏輯基於時間增量。

嘗試讓每一幀之間的時間差,然後讓對象移動到尊重那個時間差。

import time 

while True: 
    # dt is the time delta in seconds (float). 
    currentTime = time.time() 
    dt = currentTime - lastFrameTime 
    lastFrameTime = currentTime 

    game_logic(dt) 


def game_logic(dt): 
    # Where speed might be a vector. E.g speed.x = 1 means 
    # you will move by 1 unit per second on x's direction. 
    plane.position += speed * dt; 

如果你也想爲每秒一個簡單的辦法就是每次更新後睡覺的時間此時,相應的金額限制你的幀。

FPS = 60 

while True: 
    sleepTime = 1./FPS - (currentTime - lastFrameTime) 
    if sleepTime > 0: 
     time.sleep(sleepTime) 

請注意,只有當您的硬件對於您的遊戲來說足夠快時纔會有效。有關遊戲循環的更多信息,請查詢this

PS)對不起,我Javaish變量名...只是採取了制動一些Java編碼。

相關問題