im a python and pygame beginner and i dont know what i did wrong here

Question:

import pygame
running = True
BLACK = (0, 0, 0)
GRAY = (127, 127, 127)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
CYAN = (0, 255, 255)
MAGENTA = (255, 0, 255)
background = GRAY 
pygame.init()

screen = pygame.display.set_mode((640, 240))

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_r:
            background = RED
        elif event.key == pygame.K_g:
            background = GREEN
    
    screen.fill(background)
    pygame.display.update()
    
pygame.quit()

it should be a gray background and change color when you press r or g but it just starts and doesn’t change the color on a key press.

Asked By: Lord_of_the_apes

||

Answers:

Its a matter of Indentation. The event must be evaluated in the event loop, but not in the application loop:

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # INDENATION
    #-->|
    
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_r:
                background = RED
            elif event.key == pygame.K_g:
                background = GREEN
    
    screen.fill(background)
    pygame.display.update()
Answered By: Rabbid76
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.