X-Git-Url: https://git.ctpug.org.za/?a=blobdiff_plain;f=koperkapel%2Fscenes%2Flevel.py;h=5c86629078551df0d69459b20d61b77b08093ffa;hb=3e77dbd29c93992e5281e6f8b05f156413b9a9e4;hp=6537e5c05e46067306317548feb21ddf95a3c4df;hpb=6a8c0b31ee60408c54c9ff0d9ba46b225613f48a;p=koperkapel.git diff --git a/koperkapel/scenes/level.py b/koperkapel/scenes/level.py index 6537e5c..5c86629 100644 --- a/koperkapel/scenes/level.py +++ b/koperkapel/scenes/level.py @@ -1,40 +1,42 @@ """Render a level""" -import json -import os - from pgzero.constants import keys -from pgzero.loaders import images +from pygame import Surface +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() - - def draw(self, screen): + def enter(self, world): + self._level_data = levels.load(world.level.name) + self._tiles = self._level_data['tiles'] + self._surface = None + self._render() + + 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, y * TILE_SIZE) + if 'image' not in tile: + # Skip broken tiles for now + continue + self._surface.blit(tile['image'], pos) + + def draw(self, screen, viewport): 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']) + # 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: