Skip to main content
 首页 » 编程设计

python之按下 Pygame 键

2025年05月04日33mayingbao

在 pygame 的以下循环中 我做了以下循环来检查按键。 如何使用 pygame 检查按键是否仍在按下以及重复操作的频率?例如,如果我希望每一秒都按下向下键 - 它会重复 print("something") 命令不同的次数。

for event in pygame.event.get(): 
        if event.type == pygame.QUIT: 
            game_running = False 
        if event.type == pygame.KEYDOWN: 
            if event.key == pygame.K_DOWN: 
                print("something") 

请您参考如下方法:

您可以在按下键处理程序中将 bool 值设置为 true,然后在新的按下键处理程序中将其设置为 false。像这样的东西:

for event in pygame.event.get(): 
        if event.type == pygame.QUIT: 
            game_running = False 
        if event.type == pygame.KEYDOWN: 
            if event.key == pygame.K_DOWN: 
                down_pressed = True 
        elif event.type == pygame.KEYUP: 
            if event.key == pygame.K_DOWN: 
                down_pressed = False 
 
if down_pressed: 
  print("Down is pressed") 

然后您可以在游戏逻辑中使用该 bool 值,例如移动角色。 如果按下:move_character_down()