0

When I run this code, only pressing the 'a' key doesn't work. I'm not sure what I did wrong and I can't find out why it won't work.

import pygame, sys
from pygame.locals import QUIT

pygame.init()
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Hello World!')
while True:
        for event in pygame.event.get():
                if event.type == QUIT:
                        pygame.quit()
                        sys.exit()
        if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_a:
                        a_down = True
        else:
                a_down = False
        if a_down == True:
                print("Held down 'a'")
        pygame.display.update()
ColoredHue
  • 59
  • 7

1 Answers1

1

You have issues with indentation, these may just be due to incorrect formatting.

You should probably use the pygame.KEYUP event to set the a_down to False. This code might do what you want:

import pygame, sys

pygame.init()
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption("Hello World!")
a_down = False  # initialise
clock = pygame.time.Clock()  # Clock to limit FPS
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_a:
                a_down = True
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_a:
                a_down = False
    if a_down == True:
        print("Held down 'a'")
    pygame.display.update()
    clock.tick(30)
import random
  • 3,054
  • 1
  • 17
  • 22