[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]
Re: [pygame] Two questions regarding a simple space shooter
....
pygame.event.pump()
keys = pygame.key.get_pressed()
if K_LEFT in keys:
ship.move_left()
...
get_pressed() returns a sequence of True/Falses, so K_LEFT will never
be in keys. You can use the K_constants to index into the returned
sequence, i.e:
if keys[K_LEFT]:
ship_move_left()
I like this method better than checking KEYDOWN/KEYUP events. In the
arkanoid/pong clone I'm working on (this is the pygame "hello,
world!", apparently), I handled keyboard input something like this:
def handle_player_input(player, keymap):
# keymap is the output from pygame.key.get_pressed()
# player.moves is a dictionary that looks like { "up":K_UP,
"down":K_DOWN, etc. etc.}
moves = player.moves
dx, dy = 0, 0 #Resting
if keymap[moves["up"]]:
dy = -1
elif keymap[moves["down"]]:
dy = 1
if keymap[moves["left"]]:
dx = -1
elif keymap[moves["right"]]:
dx = 1
if keymap[moves["fire"]]:
pygame.event.post(Event(USEREVENT, {"code":"fire!",
"player":player, etc. }))
return dx, dy
(I'm letting the paddle travel in two directions, so it's a little
more complicated. You could easily drop one of the dimensions if you
don't want it.)
(Fair warning -- I'm new to this myself, this might not be the best
way of doing things...)
Good luck!