简体   繁体   中英

pygame.key.get_pressed() is not working in my code and i don't know why

I recently started working with python and decided to create a game with pygame where basically there are block falling and you have to move past them. You can move using the left and right keys although if you keep them pressed nothing happens and I don't know why since in my code I believe I have that covered in lines between 114 and 122.

while not game_over:

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()

I expected to be able to move while pressing the left and right buttons but I can't I can only move when I press and then release.

The issue is caused because the change of the position is done in the event loop, but the event loop is executed only, when an event occurs, like pygame.KEYDOWN or pygame.KEYUP . So the position does not change continuously, it changes only once if a any key is pressed or any key is released.

Note, the position would even change if K_LEFT or K_RIGHT is hold pressed, and an other event occurs like MOUSEMOTION . You can verify that, press K_LEFT and move the mouse, the player will move.

Move the code wich changes the position out of the event loop and do it in the scope of the main loop:

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]
#<--
#<-- 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM