[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

[pygame] Problems with keys



Hi,
 
I'm not sure if this was already posted, sorry for double posting if it was. I tried to send this mail before adding myself to the mailing list.
 
I have a simple program that displays an image and moves it to the left or right based on which arrow key the user pressed. Here's the code:
 
 
import pygame
from pygame.locals import*
 
pygame.init()
 
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("test")
pygame.mouse.set_visible(1)
bg = pygame.Surface(screen.get_size())
bg.convert()
bg.fill((0,0,0))
screen.blit(bg, (0,0))
pygame.display.flip()
 
t = pygame.image.load("..\\content\\timmy.tga")
tr = t.get_rect()
tr.topleft = (0,0)
 
pygame.key.set_repeat(1,1)
 
run = True
while run:
    screen.blit(bg, (0,0))

    for event in pygame.event.get():
        if event.type == QUIT:
            run = False
            break
 
        ## k = pygame.key.get_pressed()
        ## if k[K_LEFT]:
            ## tr = tr.move(-5, 0)
        ## elif k[K_RIGHT]:
            ## tr = tr.move(5,0)
           
        if event.type == KEYDOWN:
            if event.key == K_LEFT:
                tr = tr.move(-5,0)
            elif event.key == K_RIGHT:
                tr = tr.move(5,0)
               
    screen.blit(t, tr)
    pygame.display.flip()
 
 
The problem is that if the user holds one of the buttons, quickly releases it, and then starts pressing the other, the image stops moving. It's like the program starts ignoring the key repeats or something. I'd like to have the image just change direction without the user having to stop pressing the key and then again pressing it to get the image moving. The image moves correctly if the user changes keys a bit slower, but is there a way to make the program respond faster? I've tried checking the keys with both key.get_pressed() as well as event.type == KEYDOWN, but both have the same problem.
 
Juha Salo