Mercurial > sypikslang
comparison gamelib/engine.py @ 52:1d3d20bdc8b9
Move engine stuff into it's own file
author | Neil Muller <drnlmuller@gmail.com> |
---|---|
date | Mon, 07 May 2012 21:55:55 +0200 |
parents | |
children | 7309392d9ca9 |
comparison
equal
deleted
inserted
replaced
51:ac637e84f8f8 | 52:1d3d20bdc8b9 |
---|---|
1 # -*- coding: utf-8 -*- | |
2 # vim:fileencoding=utf-8 ai ts=4 sts=4 et sw=4 | |
3 | |
4 | |
5 """Game engine stuff""" | |
6 | |
7 import pygame | |
8 from pygame.locals import (MOUSEBUTTONDOWN, MOUSEBUTTONUP, MOUSEMOTION, QUIT, | |
9 USEREVENT) | |
10 from pygame.time import Clock | |
11 | |
12 from gamelib.constants import FPS | |
13 | |
14 | |
15 class UserEvent(object): | |
16 # Handy event wrapper | |
17 | |
18 TYPE = "unknown" | |
19 | |
20 @classmethod | |
21 def post(cls, **kw): | |
22 event = pygame.event.Event(USEREVENT, utype=cls.TYPE, **kw) | |
23 pygame.event.post(event) | |
24 | |
25 @classmethod | |
26 def matches(cls, event): | |
27 return event.type == USEREVENT and event.utype == cls.TYPE | |
28 | |
29 | |
30 class AddWindow(UserEvent): | |
31 # Add the given window to the top of the window stack | |
32 | |
33 TYPE = "ADD_WINDOW" | |
34 | |
35 @classmethod | |
36 def post(cls, window): | |
37 super(AddWindow, cls).post(window=window) | |
38 | |
39 | |
40 class PopWindow(UserEvent): | |
41 # Pop a window off the top of the window stack | |
42 | |
43 TYPE = "POP_WINDOW" | |
44 | |
45 @classmethod | |
46 def post(cls): | |
47 super(PopWindow, cls).post() | |
48 | |
49 | |
50 class Engine(object): | |
51 | |
52 def __init__(self, screen): | |
53 self._window_stack = [] | |
54 self._running = False | |
55 self._mouse_down = False | |
56 self._screen = screen | |
57 | |
58 def run(self, window): | |
59 clock = Clock() | |
60 self._window_stack.append(window) | |
61 self._running = True | |
62 self._mouse_down = False | |
63 while self._running: | |
64 self.process_input() | |
65 self.draw() | |
66 clock.tick(FPS) | |
67 | |
68 def draw(self): | |
69 for view in self._window_stack: | |
70 view.draw(self._screen) | |
71 pygame.display.flip() | |
72 | |
73 def process_input(self): | |
74 for event in pygame.event.get(): | |
75 if self._mouse_down: | |
76 if event.type == MOUSEBUTTONUP: | |
77 self._mouse_down = False | |
78 self._window_stack[-1].on_mouse_up(event.pos) | |
79 elif event.type == MOUSEMOTION: | |
80 self._window_stack[-1].on_mouse_move(event.pos) | |
81 elif not self._mouse_down and event.type == MOUSEBUTTONDOWN: | |
82 self._mouse_down = True | |
83 self._window_stack[-1].on_mouse_down(event.pos) | |
84 elif event.type == QUIT: | |
85 self._running = False | |
86 elif AddWindow.matches(event): | |
87 self._window_stack.append(event.window) | |
88 elif PopWindow.matches(event): | |
89 self._window_stack.pop() |