0

I have the following code for an application I am developing in pygame. When I click the down key or any key for that matter, "here" is not being printed. The code is as follows:

while True:
 for event in pygame.event.get():
   if event.type == pygame.QUIT:
      pygame.quit()
      sys.exit()
   if event.type == pygame.KEYDOWN:
      print("here")
      if event.key == pygame.K_DOWN:
         player_speed += 7
      if event.key == pygame.K_UP:
         player_speed -= 7
    
   if event.type == pygame.KEYUP:
      print("here")
      if event.key == pygame.K_DOWN:
         player_speed -= 7
      if event.key == pygame.K_UP:
         player_speed += 7

Where is the error here (it is not a syntax one as the code runs fine - it is just indented weirdly on this post)? Is there another requisite prior to taking in keyboard input.

1 Answers1

0

It's not clear what the error is without more of your code, preferably a Minimal, Reproducible Example.

Here's what such an example could look like:

import pygame
import random

screen = pygame.display.set_mode((480, 320))
pygame.init()

player_speed = 0
run = True
clock = pygame.time.Clock()
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        elif event.type == pygame.KEYDOWN:
            print(f"Key {pygame.key.name(event.key)} pressed")
            if event.key == pygame.K_DOWN:
                player_speed += 7
            elif event.key == pygame.K_UP:
                player_speed -= 7
        elif event.type == pygame.KEYUP:
            print(f"Key {pygame.key.name(event.key)} released")
            if event.key == pygame.K_DOWN:
                player_speed -= 7
            if event.key == pygame.K_UP:
                player_speed += 7

    screen.fill(pygame.Color("grey"))
    pygame.display.update()
    pygame.display.set_caption(f"Player Speed {player_speed}")
    clock.tick(60)  # limit to 60 FPS

pygame.quit()

This produces the following: MCVE key presses

I've expanded your debug print statements to provide more context and added an update to the title bar to display the current value of the player_speed variable.

import random
  • 3,054
  • 1
  • 17
  • 22
  • I tried adding your debugging statements as well, but the issue is that there is no response at all when I click the up/down/left/right keys. – Sagnik Biswas Jun 30 '22 at 19:49
  • @SagnikBiswas Does your pygame window have key focus? I.e. have you clicked in the window. Pygame will only see keyboard events if it is the active window. If you are still having problems, please create a new question as this question has been closed. Make sure you include a [mcve] and explain what you've tried and why your question is not already answered by the other linked questions. See [How to Ask?](https://stackoverflow.com/help/how-to-ask) for more details. – import random Jul 01 '22 at 04:19