0

im a beginner in pygame, and i dont have any experience in programming, im using pygame.key.get_pressed() :

import pygame, sys
from pygame.locals import *

pygame.init()
DISPLAYSURF = pygame.display.set_mode((400, 400))
pygame.display.set_caption('Hello World!')


green = (0,255,0)
FPS = 60
FpsClock = pygame.time.Clock()
playerY = 200
playerX = 200

while True:
    BG = pygame.draw.rect(DISPLAYSURF,(255, 255,255),(0,0,400,400))
    player = pygame.draw.rect(DISPLAYSURF,(green),(playerX, playerY,20, 20))
    keys = pygame.key.get_pressed()

    
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if keys[pygame.K_z]:
            playerY -= 5
        if keys[pygame.K_s]:
            playerY += 5
        if keys[pygame.K_d]:
            playerX += 5
        if keys[pygame.K_q]:
            playerX -= 5

    pygame.display.update(player)

    

    pygame.display.update()
    FpsClock.tick(FPS)

when i click one time on s key for example everything works just fine the player moves, but if i hold down s button there is a delay before the player move's down while im holding the button (samething for w,a,d)

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
erramidev
  • 27
  • 4

1 Answers1

0

It is a matter of Indentation. You must evaluate the pressed keys in the application loop instead of the event loop:

while True:
    BG = pygame.draw.rect(DISPLAYSURF,(255, 255,255),(0,0,400,400))
    player = pygame.draw.rect(DISPLAYSURF,(green),(playerX, playerY,20, 20))
    keys = pygame.key.get_pressed()

    
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    
    # INDENTATION
    #<--|
    
    if keys[pygame.K_z]:
        playerY -= 5
    if keys[pygame.K_s]:
        playerY += 5
    if keys[pygame.K_d]:
        playerX += 5
    if keys[pygame.K_q]:
        playerX -= 5

    pygame.display.update(player)
    pygame.display.update()
    FpsClock.tick(FPS)

pygame.key.get_pressed() returns a sequence with the state of each key. If a key is held down, the state for the key is True, otherwise False.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174