[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]
Re: [pygame] Problems with keys
On Thu, Apr 06, 2006 at 07:00:05PM +0300, Juha wrote:
> 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:
>
> [*clip!*]
>
> 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
You don't really want to be using key repeats at all. keyboard repeats
will never be all that reliable for game-input purposes. Instead, you
want to catch both KEYDOWN and KEYUP events. Here is an example:
import os
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(os.path.join("..","content","timmy.tga"))
tr = t.get_rect()
tr.topleft = (0,0)
goLeft = False
goRight = False
run = True
while run:
screen.blit(bg, (0,0))
for event in pygame.event.get():
if event.type == QUIT:
run = False
break
if event.type == KEYDOWN:
if event.key == K_LEFT:
goLeft = True
elif event.key == K_RIGHT:
goRight = True
if event.type == KEYUP:
if event.key == K_LEFT:
goLeft = False
if event.key == K_RIGHT:
goRight = False
if goLeft and not goRight:
tr = tr.move(-5,0)
if goRight and not goLeft:
tr = tr.move(5,0)
screen.blit(t, tr)
pygame.display.flip()
Now eventually you will probably want to wrap the goRight and goLeft
into members of a game character class, or have a "velocity" member, or
something more object-oriented than this example, but as far as the
keyboard handling goes, I think this is what you want.
(and don't forget to use os.path.join() for your directory names!)
---
James Paige