"""Loader a level, using the pygame-zero ResourceLoader infrastructure"""
+import os
import json
from pgzero.loaders import images, ResourceLoader
+import os
+import random
+from pygame.transform import rotate
+class Tile:
+ IMG = None
+
+ @classmethod
+ def image(cls):
+ if cls.IMG is None:
+ raise NotImplementedError()
+
+ return images.load(cls.IMG)
+
+class RandomizedTile(Tile):
+ IMGDIR = None
+ ROTATE = True
+
+ @classmethod
+ def image(cls):
+ if cls.IMGDIR is None:
+ raise NotImplementedError()
+
+ imgdir = os.path.join(os.path.dirname(__file__), '..', 'images', cls.IMGDIR)
+ imgpath = os.path.splitext(random.choice(os.listdir(imgdir)))[0]
+ img = images.load(os.path.join(cls.IMGDIR, imgpath))
+
+ if cls.ROTATE:
+ img = rotate(img, 90 * random.randint(0, 3))
+
+ return img
+
+class Floor(RandomizedTile):
+ IMGDIR = "floor"
+
+class Wall(RandomizedTile):
+ IMGDIR = "wall"
+
+TILES = {
+ "cwall": Wall, # rename this everywhere
+ "floor": Floor,
+}
class LevelLoader(ResourceLoader):
""" Level loader. """
f = open(level_path, 'r')
level_data = json.load(f)
f.close()
+ self._height = len(level_data['tiles'])
+ self._width = len(level_data['tiles'][0])
self._tiles = level_data['tiles']
+ self._tileset = level_data['tileset']
+ # Consistency check, so we can assume things are correct
+ # in the level renderer
+ for row, row_data in enumerate(self._tiles):
+ if len(row_data) != self._width:
+ raise RuntimeError("Incorrect len for row %d" % row)
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'])
+ for row_data in self._tiles:
+ for tile in row_data:
+ tile['image'] = TILES[tile['base']].image()
levels = LevelLoader('levels')