【问题标题】:pygame.key.get_pressed() is not working in my code and i don't know whypygame.key.get_pressed() 在我的代码中不起作用,我不知道为什么
【发布时间】:2019-04-19 02:27:44
【问题描述】:

我最近开始使用 python 并决定使用 pygame 创建一个游戏,其中基本上有方块掉落,你必须越过它们。 您可以使用左右键移动,但如果按住它们没有任何反应,我不知道为什么,因为在我的代码中,我相信我在 114 和 122 之间的行中涵盖了这一点。

虽然不是游戏结束:

for event in pygame.event.get(): 

    if event.type == pygame.QUIT: 
        sys.exit()

    x = player_pos[0]
    y = player_pos[1]

    keys = pygame.key.get_pressed() # Check if a key is pressed

    if keys[pygame.K_LEFT] and x != 0:                                   
      x -= 25             
      print("move left")                                           
    if keys[pygame.K_RIGHT] and x != 750:
      print("move right")                                
      x += 25                                   
    player_pos = [x, y] 

draw_enemies(enemy_list)
pygame.draw.rect(screen, RED, (player_pos[0], player_pos[1], player_size, player_size))

clock.tick(30)
pygame.display.update()

我希望可以在按下左右按钮时移动,但我不能我只能在按下然后释放时移动。

【问题讨论】:

    标签: python pygame


    【解决方案1】:

    这个问题是因为位置的改变是在事件循环中完成的,但是事件循环仅在事件发生时执行,例如pygame.KEYDOWNpygame.KEYUP。 因此位置不会连续变化,如果按下任何键或释放任何键,它只会更改一次。

    请注意,如果按住 K_LEFTK_RIGHT,则位置甚至会改变,并且会发生其他事件,例如 MOUSEMOTION。您可以验证,按下K_LEFT 并移动鼠标,播放器会移动。

    将更改位置的代码移出事件循环并在主循环范围内执行:

    for event in pygame.event.get(): 
    
        if event.type == pygame.QUIT: 
            sys.exit()
    
    #<--
    #<--
    x = player_pos[0]
    y = player_pos[1]
    
    keys = pygame.key.get_pressed() # Check if a key is pressed
    
    if keys[pygame.K_LEFT] and x != 0:                                   
        x -= 25             
        print("move left")                                           
    if keys[pygame.K_RIGHT] and x != 750:
        print("move right")                                
        x += 25                                   
    player_pos = [x, y]
    #<--
    #<-- 
    

    【讨论】:

    • @tomasdomingues 不客气。请注意,如果您的问题的答案完全解决了您的问题,那么您应该接受该答案。 (答案左侧的复选标记)。
    猜你喜欢
    • 2020-09-19
    • 2014-01-17
    • 2021-10-19
    • 2019-05-21
    • 2020-02-05
    • 2021-03-11
    • 1970-01-01
    • 2016-08-25
    • 2022-01-22
    相关资源
    最近更新 更多