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

Re: [pygame] keep a key pressed and then move a sprite



Ok thanks to reply so fast :) yeah of course, it seems obvious now but i didn't know there is a way to manage keyboard state without the common event loop.
I ll use this created topic to ask something else about the optimization of a game written with pygame. Restrict frames per second with clock.tick(xx) and only update dirty rects (in case of static background) is enough for a quite "simple" 2D game? Or there re more optimizations to do? I don't try to reach perfect performance, only want to make my faster as possible and less CPU consuming.

PS : i'm sorry but i do my best to try to write an understandable english, it s not my native langage at all and i m pretty young but i was forced to learn it to enjoy python/pygame ressources avaiable on the Internet (there is no many french ressources on the Internet...)

2010/11/24 Ian Mallett <geometrian@xxxxxxxxx>
Hi,

Try this:


while True:
   clock.tick(60) #set on 60 frames per second

   for event in pygame.event.get():
       if event.type == QUIT:
           sys.exit()

   key = pygame.key.get_pressed()

   if key[K_LEFT]: heroes.move_left()


   pygame.display.update(heroes_group.draw(screen))

The PyGame event manager fires events only when a key's state changes (that is, the moment it is pressed or the moment it was released, a single event is fired). 

What you want to do is to check the current state of the keyboard.  "pygame.key.get_pressed()" does this.  The state "key" that it returns can then be checked for the required key.

Ian