是否可以从pygame.key.get_pressed()获取每个键的更改状态?例如,如果一个键已经启动但是已经关闭,那么将其设置为1,或者关闭但是向上,否则为0。
我的想法是使用类似下面的代码,但这不起作用,因为pygame.key.get_pressed()不是可迭代的。
last_pressed = pressed
pressed = pygame.key.get_pressed()
changed = {key: pressed[key] != last_pressed[key] for key in pressed}
我打算用它来切换几个功能,而宁愿使用一种可读性的方法。
答案 0 :(得分:5)
for key in pressed
提供列表,而不是字典,因此0
会为此列表中的值提供1
或False
(True
或changed = [idx for idx in range(len(pressed)) if pressed[idx] != last_pressed[idx]]
)
只获取改变状态的密钥号码,您可以使用
zip()
或使用enumerate()
和changed = [idx for idx, (a, b) in enumerate(zip(last_pressed, pressed)) if a != b]
import pygame
pygame.init()
screen = pygame.display.set_mode((300, 200))
pressed = pygame.key.get_pressed()
clock = pygame.time.Clock()
is_running = True
while is_running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
is_running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
is_running = False
last_pressed = pressed
pressed = pygame.key.get_pressed()
changed = [idx for idx in range(len(pressed)) if pressed[idx] != last_pressed[idx]]
# or
changed = [idx for idx, (a, b) in enumerate(zip(last_pressed, pressed)) if a != b]
print(changed)
clock.tick(25)
pygame.quit()
完整代码
KEYDOWN
与KEYUP
和import pygame
pygame.init()
screen = pygame.display.set_mode((300, 200))
clock = pygame.time.Clock()
is_running = True
while is_running:
changed = []
for event in pygame.event.get():
if event.type == pygame.QUIT:
is_running = False
elif event.type in (pygame.KEYDOWN, pygame.KEYUP):
changed.append(event.key)
print(changed)
clock.tick(25)
pygame.quit()
True/False
获取所有密钥的changed = [pressed[idx] != last_pressed[idx] for idx in range(len(pressed))]
:
zip()
或使用changed = [a != b for a, b in zip(last_pressed, pressed)]
char_id = tf.placeholder(dtype=tf.int32, shape=[None, word_max_len])