class MenuScene(Scene):
-
def __init__(self, state):
super(MenuScene, self).__init__(state)
- self.add(TextWidget((10, 10), 'Game', fontsize=32, colour='white'))
- self.add(TextWidget((10, 40), 'Credits', fontsize=32, colour='white'))
- self.add(TextWidget((10, 70), 'Quit', fontsize=32, colour='white'))
- self.pos = 0
+ run_game = TextWidget((100, 100), 'Game', fontsize=32, colour='white')
+ run_game.add_callback('click',
+ lambda event: SceneChangeEvent.post(GameScene))
+ self.add(run_game)
+ credits = TextWidget((100, 200), 'Credits', fontsize=32, colour='white')
+ credits.add_callback('click',
+ lambda event: SceneChangeEvent.post(CreditsScene))
+ self.add(credits)
+ quit = TextWidget((100, 300), 'Quit', fontsize=32, colour='white')
+ quit.add_callback('click', lambda event: QuitGameEvent.post())
+ self.add(quit)
def handle_scene_event(self, ev):
if ev.type == pgl.KEYDOWN:
if ev.key in (pgl.K_q, pgl.K_ESCAPE):
QuitGameEvent.post()
return
- if ev.key == pgl.K_DOWN:
- self.pos = (self.pos + 1) % 3
- elif ev.key == pgl.K_UP:
- self.pos = (self.pos - 1) % 3
- elif ev.key == pgl.K_RETURN:
- if self.pos == 2:
- QuitGameEvent.post()
- return
- elif self.pos == 0:
- scene = GameScene
- elif self.pos == 1:
- scene = CreditsScene
- SceneChangeEvent.post(scene)
+from collections import defaultdict
+
import pygame
+from pygame import locals as pgl
+
from naja.events import InvalidateTheWorld
self.pos = pos
self.size = size or (0, 0)
self._prepared = False
+ self.callbacks = defaultdict(list)
@property
def rect(self):
# True for for this event
self._prepared = False
return False
+ if ev.type == pgl.MOUSEBUTTONDOWN:
+ self.callback('click')
return False
+ def add_callback(self, event, callback):
+ self.callbacks[event].append(callback)
+
+ def callback(self, event):
+ for callback in self.callbacks[event]:
+ callback(event)
+
class Container(object):
def __init__(self, *widgets):
widget.render(surface)
def handle_event(self, ev):
- for widget in self.widgets:
- if widget.handle_event(ev):
- return True
+ if hasattr(ev, 'pos'):
+ for widget in self.widgets:
+ if isinstance(widget, Container):
+ if widget.handle_event(ev):
+ return True
+ elif widget.rect.collidepoint(ev.pos):
+ if widget.handle_event(ev):
+ return True
+ else:
+ for widget in self.widgets:
+ if widget.handle_event(ev):
+ return True
return False