Reorganise level jsohn structure. Drop 'pos' attribute in favour of the array positio...
[koperkapel.git] / koperkapel / scenes / level.py
index 6537e5c05e46067306317548feb21ddf95a3c4df..71373c06a08a80c86f1d9368074d94ba53f9a6f9 100644 (file)
@@ -1,40 +1,30 @@
 """Render a level"""
 
-import json
-import os
-
 from pgzero.constants import keys
-from pgzero.loaders import images
+from ..loaders.levelloader import levels
 from .base import Scene, ChangeSceneEvent
-from .constants import TILE_SIZE, LEVEL_PATH
+from ..constants import TILE_SIZE, WIDTH, HEIGHT
 
 
 class LevelScene(Scene):
     """ Level scene. """
 
     def __init__(self, level_name):
-        self._level_name = level_name
-        f = open(os.path.join(LEVEL_PATH, level_name + '.json'))
-        level_data = json.load(f)
-        f.close()
-        self._tiles = level_data['tiles']
-        self._load_tile_images()
+        self._level_data = levels.load(level_name)
+        self._tiles = self._level_data['tiles']
 
-    def draw(self, screen):
+    def draw(self, screen, viewport=(0, 0)):
         screen.clear()
-        #screen.draw.text("This is level {}".format(self._level_name), (200, 100))
-        for tile in self._tiles:
-            pos = tile['pos']
-            pos = [pos[0] * TILE_SIZE, pos[1] * TILE_SIZE]
-            if not 'image' in tile:
-                # Skip broken tiles for now
-                continue
-            screen.blit(tile['image'], pos)
-
-    def _load_tile_images(self):
-        """Load all the tile images"""
-        for tile in self._tiles:
-            tile['image'] = getattr(images, tile['base'])
+        for y, row in enumerate(self._tiles):
+            for x, tile in enumerate(row):
+                pos = (x * TILE_SIZE - viewport[0],
+                       y * TILE_SIZE - viewport[1])
+                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)
 
     def on_key_down(self, key, mod, unicode):
         if key == keys.ESCAPE: