英文:
what is different that get_pressed() is under for event or not?
问题
在下面的while循环中,'pressed_key = pygame.key.get_pressed()'位于for循环之外,这个语句仍然有效,那么它在for循环内和外有什么不同之处?
在下面的代码示例中,'pressed_key = pygame.key.get_pressed()'语句分别位于for循环内和外:
while 1:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
pressed_key = pygame.key.get_pressed()
无论将该语句放置在for循环内或外,它的作用是获取当前按下的键盘按键状态。这意味着无论在哪里获取键盘按键状态,它都会返回相同的结果。在这种情况下,将其放置在for循环之外是更好的做法,因为这样只需要获取一次键盘状态,而不是在每次迭代循环时都获取一次,这样可以提高代码的效率。
请注意,代码示例中还包含了事件处理,用于检测是否有关闭窗口事件。无论如何,'pressed_key = pygame.key.get_pressed()'都可以独立于for循环工作,而不会受到事件处理的影响。
英文:
in the below while sentence, 'pressed_key = pygame.key.get_pressed()' is out of for area, this sentence also work well, what is different it under for or not?
while 1:
clock.tick(60)
for event in pygame.event.get()
if event.type == pygame.QUIT
sys.exit()
pressed_key = pygame.key.get_pressed()
I added 'pressed_key = pygame.key.get_pressed()' under for and put it out.
答案1
得分: 1
这个差异在于,在for循环内,此语句会多次执行(与pygame.event.get()
返回的Eventlist的长度一样多次),可能总是返回相同的值。
只需在每个clock.tick
中获取一次key_pressed就足够了,否则你会创建一个当前按下键的“子帧”分辨率,这可能不是你要寻找的。
因此,将其放在事件循环之外(根据你的游戏逻辑是在之前还是之后)应该是更好的(也是更节省资源的)方式。
英文:
The difference is, that within the for loop, this statement is executed multiple times (as often as the length of Eventlist returned by pygame.event.get()
), presumably always returing the same value.
It is sufficient to get the key_pressed only once per clock.tick
, elsewise you would create a "sub-frame" resolution of the currently pressed keys, which might not be what you are looking for.
So posititioning it outside the event for loop (either before or after, depending on your game logic) should be the better (and less resource-hungry) way.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论