Ensure color_pos is always -1 when the lights go out, so behaviour is always consistent
[tabakrolletjie.git] / tabakrolletjie / engine.py
1 """ Engine for moving controll scenes and tranistions between them.
2 """
3
4 import pygame.display
5 import pygame.event
6 import pygame.time
7
8 import pygame.locals as pgl
9
10 from .constants import FPS, DRAW_FPS, FONTS, FPS_FRAMES
11 from .loader import loader
12 from .events import QuitEvent, SceneChangeEvent
13
14
15 class Engine(object):
16     def __init__(self, screen, gamestate):
17         self._screen = screen
18         self._gamestate = gamestate
19         self._scene = None
20
21     def set_scene(self, scene):
22         if self._scene is not None:
23             self._scene.exit(self._gamestate)
24         self._scene = scene
25         if scene is not None:
26             self._scene.enter(self._gamestate)
27
28     def run(self):
29         clock = pygame.time.Clock()
30         fpses = [FPS] * FPS_FRAMES
31         frame = 0
32         font = loader.load_font(FONTS['sans'], size=16)
33
34         while True:
35             events = pygame.event.get()
36             for ev in events:
37                 if QuitEvent.matches(ev) or ev.type == pgl.QUIT:
38                     self.set_scene(None)
39                     return
40                 elif SceneChangeEvent.matches(ev):
41                     self.set_scene(ev.scene)
42                 else:
43                     self._scene.event(ev, self._gamestate)
44
45             # Advance time on the world
46             # Time is assumed to flow perfectly, so no dt parameter for now
47             self._scene.tick(self._gamestate)
48             self._scene.render(self._screen, self._gamestate)
49             if DRAW_FPS:
50                 fps = sum(fpses) / FPS_FRAMES
51                 text = font.render("FPS: %.2f" % fps, True, (255, 255, 255))
52                 self._screen.blit(text, (10, 10), None)
53             pygame.display.flip()
54             fpses[frame] = 1000.0 / clock.tick(FPS)
55             frame += 1
56             if frame >= FPS_FRAMES:
57                 frame = 0