Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # encoding: utf-8
- import pygame
- from pygame.locals import *
- from pygame import event, key, mouse
- from pygame.time import Clock, wait
- from pyguane.core.singleton import Singleton
- import sys
- @Singleton
- class EventManager(object):
- def __init__(self):
- pygame.init()
- key.set_repeat(20)
- self._keys_state = {}
- self._user_events = {}
- self._clock = Clock()
- def _keyboardCallback(self, keysdown):
- if "escape" in keysdown:
- quit()
- def _mouseCallback(self, buttons_down, pos, relpos):
- for i,but in enumerate(buttons_down):
- if but: print "Button",i,"pressed at pos",pos," rel:",relpos
- def keyboard(self, func):
- """ register a function as a keyboard callback """
- self._keyboardCallback = func
- return self._keyboardCallback
- def mouse(self, func):
- """ register a function as a mouse callback """
- self._mouseCallback = func
- return self._mouseCallback
- def _setKeyState(self, key, state):
- self._keys_state[key] = state
- def getKeysDown(self):
- """ get a list of the keys currently pressed """
- return [k for k in self._keys_state if self._keys_state[k] == KEYDOWN]
- def isKeyDown(self, key):
- """ return True is the key is down """
- return self._keys_state[key] == KEYDOWN
- @property
- def buttons_down(self): return mouse.get_pressed()
- @property
- def mouse_pos(self): return mouse.get_pos()
- @property
- def mouse_relpos(self): return mouse.get_rel()
- def update(self):
- """Update the event loop
- Calls the callbacks binded to the mouse and the keyboard
- Calls USEREVENT callback
- """
- for e in event.get():
- if e.type == QUIT:
- pygame.quit()
- sys.exit()
- elif e.type in (KEYDOWN, KEYUP):
- self._setKeyState(key.name(e.key), e.type)
- elif e.type in (MOUSEBUTTONDOWN, MOUSEBUTTONUP, MOUSEMOTION):
- self._mouseCallback(self.buttons_down, self.mouse_pos, self.mouse_relpos)
- elif e.type == USEREVENT:
- try:
- e.callback()
- except AttributeError:
- print e," is a USEREVENT with no callback function defined."
- self._keyboardCallback(self.getKeysDown())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement