From 9716c38db307a48cc69bf5a3d77347d5fba4acc2 Mon Sep 17 00:00:00 2001 From: Neil Date: Mon, 29 Feb 2016 16:40:36 +0200 Subject: [PATCH] Split level loading into a custom loader --- koperkapel/loaders/levelloader.py | 28 ++++++++++++++++++++++++++++ koperkapel/scenes/level.py | 23 +++++------------------ 2 files changed, 33 insertions(+), 18 deletions(-) create mode 100644 koperkapel/loaders/levelloader.py diff --git a/koperkapel/loaders/levelloader.py b/koperkapel/loaders/levelloader.py new file mode 100644 index 0000000..4fa6ecd --- /dev/null +++ b/koperkapel/loaders/levelloader.py @@ -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') diff --git a/koperkapel/scenes/level.py b/koperkapel/scenes/level.py index 6537e5c..a58c51d 100644 --- a/koperkapel/scenes/level.py +++ b/koperkapel/scenes/level.py @@ -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 -- 2.34.1