Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Korakot Chaovavanich http://korakot.stumbleupon.com

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Handle keyboard event easily

I found a code that simplify keyboard event handling
from the popular pys60 tutorial.
I simplify it a bit (removing some feature but make it easier to read)
   1  
   2  from appuifw import *
   3  from key_codes import *
   4  
   5  class Keyboard(object):
   6      def __init__(self):
   7          self.state = {}  # is this key pressing ?
   8          self.buffer= {}  # is it waiting to be processed ?
   9      def handle_event(self, event): # for event_callback
  10          code = event['scancode']
  11          if event['type'] == EEventKeyDown:
  12              self.buffer[code]= 1   # put into queue
  13              self.state[code] = 1
  14          elif event['type'] == EEventKeyUp:
  15              self.state[code] = 0
  16      def pressing(self, code):      # just check
  17          return self.state.get(code,0)
  18      def pressed(self, code):       # check and process the event
  19          if self.buffer.get(code,0):
  20              self.buffer[code] = 0  # take out of queue
  21              return 1
  22          return 0
  23  
  24  key = Keyboard()
  25  app.body = canvas = Canvas(event_callback=key.handle_event)

Now you can check the keyboard status with key.pressing and key.pressed
   1  
   2  >>> key.state   # just pressed up arrow
   3  {17: 0}
   4  >>> key.buffer
   5  {17: 1}
   6  >>> key.pressing(EScancodeUpArrow)  # it's not pressing
   7  0
   8  >>> key.pressed(EScancodeUpArrow)   # yes, it's pressed
   9  1
  10  >>> key.pressed(EScancodeUpArrow)   # no, you've just processed it
  11  0
  12  >>>

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS