俄罗斯方块计时问题
我正在用PyGame写一个俄罗斯方块的程序,遇到了一个有趣的问题。
在我提问之前,这里有一段伪代码:
while True:
# In this part, the human controls the block to go left, right, or speed down
if a key is pressed and the block isnt touching the floor:
if the key is K-left:
move piece left one step
if the key is K-right:
move piece right one step
if the key is K-down:
move piece down one step
# This part of the code makes the piece fall by itself
if the block isnt touching the floor:
move block down one step
# This part makes the while loop wait 0.4 seconds so that the block does not move
# down so quickly
wait 0.4 seconds
问题在于,由于代码中有“等待0.4秒”这一部分,玩家控制的方块只能每0.4秒移动一次。我希望方块能跟着玩家按键的速度移动,同时每0.4秒掉落一次。请问我该如何安排代码才能实现这个效果呢?谢谢!
4 个回答
1
你可以试着去问问 gamedev.stackexchange.com。在这个网站上查找“游戏循环”,还可以看看其他的pygame项目,看看他们是怎么做的。一个好的游戏循环非常重要,它能帮你处理用户输入和保持稳定的帧率。
补充:https://gamedev.stackexchange.com/questions/651/tips-for-writing-the-main-game-loop
1
你也可以这样做...
...
# This part of the code makes the piece fall by itself
if the block isn't touching the floor and
the block hasn't automatically moved in the last 0.4 seconds:
move block down one step
...
不过要注意,如果用户没有按任何键,你会一直在不停地检查状态。
4
我看到的主要问题是,你在用0.4秒的等待时间来限制帧率。
其实你不应该限制帧率,而是应该限制方块下落的速度。
如果我没记错的话,有一个公式可以用来做到这一点。这个公式是根据自上一个帧经过的时间来计算的。它看起来像这样:
fraction of a second elapsed since last frame * distance you want your block to move in a second
这样一来,你就可以保持主循环不变,并且每一帧都会进行移动处理。