Mercurial > mamba
view mamba/engine.py @ 77:2aa652b92449
Focus
author | Stefano Rivera <stefano@rivera.za.net> |
---|---|
date | Sun, 11 Sep 2011 18:30:19 +0200 |
parents | fbb5cc655b47 |
children | 1e9da4893d51 |
line wrap: on
line source
"""Game engine and top-level game loop.""" from mamba.constants import SCREEN from mamba.widgets.base import Container import pygame.event import pygame.display import pygame from pygame.locals import QUIT, USEREVENT class Engine(object): def __init__(self): self._habitat = None def set_habitat(self, habitat): if self._habitat is not None: self._habitat.on_exit() self._habitat = habitat if self._habitat is not None: self._habitat.on_enter() def run(self): """Game loop.""" get_events = pygame.event.get flip = pygame.display.flip while True: events = get_events() for ev in events: if ev.type is QUIT: return elif NewHabitatEvent.matches(ev): self.set_habitat(ev.habitat) else: self._habitat.dispatch(ev) surface = pygame.display.get_surface() self._habitat.draw(surface) flip() class Habitat(object): def __init__(self): self.surface = None self.container = Container(pygame.Rect((0, 0), SCREEN), root=True) def on_enter(self): """Called when this becomes the current habitat.""" # Create the surface here as flipping between editor and # other things kills pygame.display self.surface = pygame.Surface(SCREEN) def on_exit(self): """Called when this stops being the current habitat.""" self.surface = None def dispatch(self, ev): self.container.event(ev) def draw(self, surface): if self.surface: self.surface.fill(pygame.Color('black')) self.container.draw(self.surface) surface.blit(self.surface, self.surface.get_rect()) class UserEvent(object): TYPE = "UNKNOWN" @classmethod def post(cls, **kws): ev = pygame.event.Event(USEREVENT, utype=cls.TYPE, **kws) pygame.event.post(ev) @classmethod def matches(cls, ev): return ev.type is USEREVENT and ev.utype == cls.TYPE class NewHabitatEvent(UserEvent): TYPE = "NEW_HABITAT" @classmethod def post(cls, habitat): super(NewHabitatEvent, cls).post(habitat=habitat)