0

I am trying to make a simple game with pygame module, and for it, I need to know every frame what buttons are pressed. For this I used pygame.key.get_pressed() method. However I had problems with it, so I created a simple test program to check where the mistake is. Here is the code:

import pygame
import time
pygame.init()
screen = pygame.display.set_mode((1400, 700))
pygame.event.pump()
pygame.draw.rect(screen, "white", (0, 0, 1400, 700), 0)
while True:
    time.sleep(0.1)
    pygame.draw.rect(screen, "white", (0, 0, 1400, 700), 0)
    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_d]:
        pygame.draw.rect(screen, "red", (0, 0, 1400, 700), 0)
        pygame.display.update()
        print("yes")
    else:
        pygame.draw.rect(screen, "white", (0, 0, 1400, 700), 0)
        pygame.display.update()
        print("no")

It is meant to run a continious loop of checking button states and if "d" is pressed, paint the screen red, otherwise keeping it white. Howerver, the color doesn't change at all, and after running some tests, I saw that pressed[pygame.K_d] is always 0, and pressed consists of zeroes only. I have tried virtually any solution suggested both on this site and on some others, but it doesn't seem to work. I have the pygame window on and active at the time of the checks. Thank you for your time in advance!

1 Answers1

2

The simplest solution is simply to add a call to pygame.event.pump() in your while loop. get_pressed() isn't working because pygame isn't getting any updates from the event system, because nothing is getting called.

However, there are some other strange things in your program. Here's a new version:

import pygame

pygame.init()

screen = pygame.display.set_mode((1400, 700))

clock = pygame.time.Clock()

while True:
    screen.fill("white")

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            raise SystemExit
    
    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_d]:
        screen.fill("red")
        print("yes")
    else:
        print("no")

    pygame.display.update()

    clock.tick(60) #FPS

This version uses a pygame.time.Clock object to regulate your framerate, and uses the pygame event queue to detect and respond to someone clicking on your window to close it (a pygame.QUIT event). The call to pygame.event.get() replaces the pump() as the call to the event system.

I also replaced the pygame.draw.rect calls with screen.fill, which means the colors will now fill the whole screen even if you change the screen size in the future.

Starbuck5
  • 1,649
  • 2
  • 7
  • 13