[英]What's the proper way to write a game loop in Python?
I'm trying to write a python game loop that hopefully takes into account FPS. 我正在尝试编写一个python游戏循环,希望考虑到FPS。 What is the correct way to call the loop?
调用循环的正确方法是什么? Some of the possibilities I've considered are below.
我考虑过的一些可能性如下。 I'm trying not to use a library like pygame.
我试图不使用像pygame这样的库。
1. 1。
while True:
mainLoop()
2. 2。
def mainLoop():
# run some game code
time.sleep(Interval)
mainLoop()
3. 3。
def mainLoop():
# run some game code
threading.timer(Interval, mainLoop).start()
4. Use sched.scheduler? 4.使用sched.scheduler?
If I understood correctly you want to base your game logic on a time delta. 如果我理解正确,您希望将游戏逻辑建立在时间增量上。
Try getting a time delta between every frame and then have your objects move with respect to that time delta. 尝试在每个帧之间获得时间增量,然后让对象相对于该时间增量移动。
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;
If you also want to limit your frames per second, an easy way would be sleeping the appropriate amount of time after every update. 如果您还希望每秒限制帧数,那么在每次更新后,一种简单的方法就是在适当的时间内休眠。
FPS = 60
while True:
sleepTime = 1./FPS - (currentTime - lastFrameTime)
if sleepTime > 0:
time.sleep(sleepTime)
Be aware thought that this will only work if your hardware is more than fast enough for your game. 请注意,只有当您的硬件对游戏来说足够快时才会有效。 For more information about game loops check this .
有关游戏循环的更多信息,请检查此项 。
PS) Sorry for the Javaish variable names... Just took a break from some Java coding. PS)抱歉Javaish变量名称......刚从Java编码中休息了一下。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.