121 lines
2.2 KiB
Python
121 lines
2.2 KiB
Python
|
|
|
|
import json
|
|
|
|
from typing import Dict, List, Any
|
|
|
|
|
|
|
|
class GameState:
|
|
|
|
def __init__(self):
|
|
|
|
self.map_tiles = []
|
|
|
|
self.resources = {}
|
|
|
|
self.entities = []
|
|
|
|
self.camera = {'x': 0, 'y': 0, 'zoom': 1.0}
|
|
|
|
self.player_data = {}
|
|
|
|
|
|
|
|
class StateLoader:
|
|
|
|
def __init__(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def load_level(self, path: str) -> GameState:
|
|
|
|
try:
|
|
|
|
with open(path, 'r') as file:
|
|
|
|
data = json.load(file)
|
|
|
|
except FileNotFoundError:
|
|
|
|
raise FileNotFoundError(f"Level file not found: {path}")
|
|
|
|
except json.JSONDecodeError:
|
|
|
|
raise ValueError(f"Invalid JSON in level file: {path}")
|
|
|
|
|
|
|
|
game_state = GameState()
|
|
|
|
game_state.map_tiles = self.parse_map(data.get('map', {}))
|
|
|
|
game_state.resources = data.get('resources', {})
|
|
|
|
game_state.entities = data.get('entities', [])
|
|
|
|
game_state.player_data = data.get('player', {})
|
|
|
|
game_state.camera = data.get('camera', {'x': 0, 'y': 0, 'zoom': 1.0})
|
|
|
|
|
|
|
|
return game_state
|
|
|
|
|
|
|
|
def parse_map(self, data: Dict[str, Any]) -> List[List[Dict]]:
|
|
|
|
map_data = data.get('tiles', [])
|
|
|
|
map_width = data.get('width', 0)
|
|
|
|
map_height = data.get('height', 0)
|
|
|
|
|
|
|
|
if not map_data or map_width == 0 or map_height == 0:
|
|
|
|
return []
|
|
|
|
|
|
|
|
tiles = []
|
|
|
|
for y in range(map_height):
|
|
|
|
row = []
|
|
|
|
for x in range(map_width):
|
|
|
|
index = y * map_width + x
|
|
|
|
if index < len(map_data):
|
|
|
|
tile_data = map_data[index]
|
|
|
|
row.append({
|
|
|
|
'type': tile_data.get('type', 'grass'),
|
|
|
|
'walkable': tile_data.get('walkable', True),
|
|
|
|
'buildable': tile_data.get('buildable', True),
|
|
|
|
'resources': tile_data.get('resources', {})
|
|
|
|
})
|
|
|
|
else:
|
|
|
|
row.append({'type': 'grass', 'walkable': True, 'buildable': True, 'resources': {}})
|
|
|
|
tiles.append(row)
|
|
|
|
|
|
|
|
return tiles
|
|
|