I cant get key presses in pygame

Hi I’m doing the freecodecamp’s ‘pygame in 2 hours course’ . At one point the instructor teaches me on how to get key presses but when I tried it didnt work.

Here my code:

import pygame

pygame.init()

screen = pygame.display.set_mode((800, 600))

pygame.display.set_caption("Space Invaders")
icon = pygame.image.load("ufo (1).png")
pygame.display.set_icon(icon)

playerImg = pygame.image.load("arcade-game (1).png")
playerX = 370
playerY = 480
playerX_change = 0


def player(x, y):
    screen.blit(playerImg, (x, y))


running = True
while running:
    screen.fill((0, 0, 0))
    
    for event in pygame.event.get():
      if event.type == pygame.QUIT:
        running = False

    if event.type == pygame.KEYDOWN:
      if event.key == pygame.K_LEFT:
        playerX_change -= 0.1
      if event.key == pygame.K_RIGHT:
        playerX_change += 0.1
    if event.type == pygame.KEYUP:
      if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
        playerX_change = 0.1
          
    playerX += playerX_change        
    player(playerX,playerY)
    pygame.display.update()

Hi @JustinYeo, you need to indent the if even.type == ... lines once more so that they are inside the for event loop

2 Likes

Like this:

import pygame

pygame.init()

screen = pygame.display.set_mode((800, 600))

pygame.display.set_caption("Space Invaders")
icon = pygame.image.load("ufo (1).png")
pygame.display.set_icon(icon)

playerImg = pygame.image.load("arcade-game (1).png")
playerX = 370
playerY = 480
playerX_change = 0


def player(x, y):
    screen.blit(playerImg, (x, y))


running = True
while running:
    screen.fill((0, 0, 0))
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
          running = False

        if event.type == pygame.KEYDOWN:
          if event.key == pygame.K_LEFT:
            playerX_change -= 0.1
          if event.key == pygame.K_RIGHT:
            playerX_change += 0.1
        if event.type == pygame.KEYUP:
          if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
            playerX_change = 0.1
          
    playerX += playerX_change        
    player(playerX,playerY)
    pygame.display.update()

Correct that is what I said

1 Like

It still doesn’t work

I tested it when answering the question and it did

My bad . I didn’t know that I had to click on the game window :open_mouth:. Many thanks to you for helping me.

1 Like