PyGame:处理游戏循环的经济方式 [英] PyGame: Economic way of handling game loops

查看:59
本文介绍了PyGame:处理游戏循环的经济方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 pygame 编写了一个小脚本(实际上不是视频游戏,而是模拟结果的图形显示,如果这很重要)但我对它等待用户事件的方式并不满意(在我的情况下,我是只对键盘上的几个键感兴趣).

I coded a small script using pygame (actually not a video game, but a graphical display for simulation results if that matters) but I'm not really satisfied with it's way of waiting for user events (in my case I'm only interested in a few keys on the keyboard).

它使用:

running = True
while running:
    for event in pygame.event.get():
        #tests and hypothetical actions

即使用户什么都不做,这个循环也会使 CPU 内核饱和,这意味着对 CPU 的无用压力、热量、风扇噪音,可能是滞后.有没有更聪明的,即.更经济的方法是将程序置于事件等待模式,而不使用无限循环,但仍使用 pygame.

This loops will saturate a CPU core even if the users doesn't do anything, which means useless stress on the CPU, heat, fan noise, maybe lags. Is there a smarter, ie. more economic, way of putting the program in waiting mode for events without using an infinite loop, but still using pygame.

推荐答案

你唯一能做的就是阻止你不打算使用的事件:

The only thing that you can do is to block events that you are not going to use:

pygame.event.set_allowed(None)
pygame.event.set_allowed([pygame.QUIT, pygame.KEYDOWN])

这只会将诸如 pygame.QUITpygame.KEYDOWN 之类的事件发布到队列中.

This will only post events such as pygame.QUIT and pygame.KEYDOWN onto the queue.

如果没有新的按键按下,则事件队列中没有任何内容,因此不会执行循环.

If there are no new key presses, there is nothing in the event queue, so the loop is not executed.

正如 sshashhank124 在评论中所说,您还可以通过调用

As sshashhank124 said in the comments, you can also slow the the main loop, by calling

clock.tick(frames)

这将导致 pygame 休眠一段时间,以便方法 tick 将被每秒调用帧次.

This will cause pygame to sleep for some time so that the method tick will be called frames times per second.

这篇关于PyGame:处理游戏循环的经济方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆