Split level loading into a custom loader
authorNeil <neil@dip.sun.ac.za>
Mon, 29 Feb 2016 14:40:36 +0000 (16:40 +0200)
committerNeil <neil@dip.sun.ac.za>
Mon, 29 Feb 2016 14:40:36 +0000 (16:40 +0200)
koperkapel/loaders/levelloader.py [new file with mode: 0644]
koperkapel/scenes/level.py

diff --git a/koperkapel/loaders/levelloader.py b/koperkapel/loaders/levelloader.py
new file mode 100644 (file)
index 0000000..4fa6ecd
--- /dev/null
@@ -0,0 +1,28 @@
+"""Loader a level, using the pygame-zero ResourceLoader infrastructure"""
+
+import json
+
+from pgzero.loaders import images, ResourceLoader
+
+
+class LevelLoader(ResourceLoader):
+    """ Level loader. """
+
+    EXTNS = ['json']
+    TYPE = 'level'
+
+    def _load(self, level_path):
+        f = open(level_path, 'r')
+        level_data = json.load(f)
+        f.close()
+        self._tiles = level_data['tiles']
+        self._load_tile_images()
+        return level_data
+
+    def _load_tile_images(self):
+        """Load all the tile images"""
+        for tile in self._tiles:
+            tile['image'] = images.load(tile['base'])
+
+
+levels = LevelLoader('levels')
index 6537e5c05e46067306317548feb21ddf95a3c4df..a58c51d450ee3d8b04200e138b0687f3fef60f30 100644 (file)
@@ -1,41 +1,28 @@
 """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
 
 
 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):
         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:
+            if 'image' not 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'])
-
     def on_key_down(self, key, mod, unicode):
         if key == keys.ESCAPE:
             from .menu import MenuScene