当 pygame.KEYDOWN 事件太多时,Pygame 事件队列似乎会冻结。如何解决这个问题?

问题描述 投票:0回答:1

我正在尝试用 Python 制作游戏,但在跟踪按下的按键时遇到一些问题。在事件队列完全冻结之前 pygame 可以跟踪的键数量似乎有限制,我不知道如何解决这个问题。

我的代码如下,以及程序启动时按数字“123456789”得到的输出。我预计会看到九个单独的“768-KeyDown”事件,但我只看到四个。

代码:

import pygame as pg
from pygame.locals import *

pg.init()
pg.display.set_mode((600, 600))

clock = pg.time.Clock()
# Track number of keys pressed.
num_keys_pressed = 0
running = True
while running:
    for event in pg.event.get():
        if event.type == QUIT:
            running = False

        if event.type == KEYDOWN:
            # Quit the program on escape.
            if event.key == K_ESCAPE:
                running = False

            # Track number of keys.
            num_keys_pressed += 1

        elif event.type == KEYUP:
            num_keys_pressed -= 1

        # Report event + number of key pressed recorded.
        print(event, num_keys_pressed)

pg.quit()

输出:

pygame 2.5.0 (SDL 2.28.0, Python 3.11.4)
Hello from the pygame community. https://www.pygame.org/contribute.html
<Event(4352-AudioDeviceAdded {'which': 0, 'iscapture': 0})> 0
<Event(4352-AudioDeviceAdded {'which': 0, 'iscapture': 1})> 0
<Event(32774-WindowShown {'window': None})> 0
<Event(32768-ActiveEvent {'gain': 1, 'state': 2})> 0
<Event(32785-WindowFocusGained {'window': None})> 0
<Event(770-TextEditing {'text': '', 'start': 0, 'length': 0, 'window': None})> 0
<Event(32768-ActiveEvent {'gain': 1, 'state': 1})> 0
<Event(32783-WindowEnter {'window': None})> 0
<Event(1024-MouseMotion {'pos': (313, 501), 'rel': (0, 0), 'buttons': (0, 0, 0), 'touch': False, 'window': None})> 0
<Event(32770-VideoExpose {})> 0
<Event(32776-WindowExposed {'window': None})> 0
**<Event(768-KeyDown {'unicode': '1', 'key': 49, 'mod': 0, 'scancode': 30, 'window': None})> 1
<Event(771-TextInput {'text': '1', 'window': None})> 1
<Event(768-KeyDown {'unicode': '2', 'key': 50, 'mod': 0, 'scancode': 31, 'window': None})> 2
<Event(771-TextInput {'text': '2', 'window': None})> 2
<Event(768-KeyDown {'unicode': '3', 'key': 51, 'mod': 0, 'scancode': 32, 'window': None})> 3
<Event(771-TextInput {'text': '3', 'window': None})> 3
<Event(768-KeyDown {'unicode': '4', 'key': 52, 'mod': 0, 'scancode': 33, 'window': None})> 4
<Event(771-TextInput {'text': '4', 'window': None})> 4**
<Event(769-KeyUp {'unicode': '3', 'key': 51, 'mod': 0, 'scancode': 32, 'window': None})> 3
<Event(769-KeyUp {'unicode': '1', 'key': 49, 'mod': 0, 'scancode': 30, 'window': None})> 2
<Event(769-KeyUp {'unicode': '2', 'key': 50, 'mod': 0, 'scancode': 31, 'window': None})> 1
<Event(769-KeyUp {'unicode': '4', 'key': 52, 'mod': 0, 'scancode': 33, 'window': None})> 0
<Event(768-KeyDown {'unicode': '\x1b', 'key': 27, 'mod': 0, 'scancode': 41, 'window': None})> 1

从输出来看,程序仅识别前 4 个击键,然后停止处理任何进一步的键盘输入(我在“1234”之后按了“56789”,但输出并未反映这一点)。关于造成此问题或如何解决此问题的任何想法?

python pygame keyboard-events
1个回答
0
投票

在这里操作;这似乎是一个硬件问题,限制了同时按下的按键数量。唯一的解决方案是购买更好的键盘(又称游戏键盘)。已解决

© www.soinside.com 2019 - 2024. All rights reserved.