2013-04-30 26 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编码。

相关问题