Move viewport management down into the engine and add suitable events. Cache initial...
[koperkapel.git] / koperkapel / scenes / level.py
index 71373c06a08a80c86f1d9368074d94ba53f9a6f9..c37b3e339c62a399e49e2cbb918750643e95b88c 100644 (file)
@@ -1,6 +1,7 @@
 """Render a level"""
 
 from pgzero.constants import keys
+from pygame import Surface
 from ..loaders.levelloader import levels
 from .base import Scene, ChangeSceneEvent
 from ..constants import TILE_SIZE, WIDTH, HEIGHT
@@ -12,19 +13,30 @@ class LevelScene(Scene):
     def __init__(self, level_name):
         self._level_data = levels.load(level_name)
         self._tiles = self._level_data['tiles']
+        self._surface = None
+        self._render()
 
-    def draw(self, screen, viewport=(0, 0)):
-        screen.clear()
+    def _render(self):
+        # We cache the rendered surface to avoid doing a large number
+        # of blits each frame, as that introduces a large performance
+        # overhead.
+        self._surface = Surface((len(self._tiles[0]) * TILE_SIZE,
+                                 len(self._tiles) * TILE_SIZE))
         for y, row in enumerate(self._tiles):
             for x, tile in enumerate(row):
-                pos = (x * TILE_SIZE - viewport[0],
-                       y * TILE_SIZE - viewport[1])
+                pos = (x * TILE_SIZE, y * TILE_SIZE)
                 if 'image' not in tile:
                     # Skip broken tiles for now
                     continue
-                if 0 <= pos[0] < WIDTH:
-                    if 0 <= pos[1] < HEIGHT:
-                        screen.blit(tile['image'], pos)
+                self._surface.blit(tile['image'], pos)
+
+    def draw(self, screen, viewport):
+        screen.clear()
+        # Viewport is the position of the screen relative to the
+        # surface. We need the position of the surface relative to
+        # the screen for the blit, so this conversion
+        screen_pos = -viewport[0], -viewport[1]
+        screen.blit(self._surface, screen_pos)
 
     def on_key_down(self, key, mod, unicode):
         if key == keys.ESCAPE: