init commit
This commit is contained in:
50
app/game/utils/loaders.py
Normal file
50
app/game/utils/loaders.py
Normal file
@@ -0,0 +1,50 @@
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Any, Tuple
|
||||
from dataclasses import fields, is_dataclass
|
||||
|
||||
import yaml
|
||||
|
||||
class TemplateStore:
|
||||
def __init__(self):
|
||||
|
||||
# incase we have problems later
|
||||
# templates_dir = Path(settings.repo_root) / "coc_api" / "app" / "game" / "templates"
|
||||
templates_dir = Path() / "app" / "game" / "templates"
|
||||
|
||||
races_yml_path = templates_dir / "races.yaml"
|
||||
classes_yml_path = templates_dir / "classes.yaml"
|
||||
spells_path = templates_dir / "spells.yaml"
|
||||
|
||||
with open(races_yml_path, "r", encoding="utf-8") as f:
|
||||
self.races = yaml.safe_load(f)["races"]
|
||||
with open(classes_yml_path, "r", encoding="utf-8") as f:
|
||||
self.classes = yaml.safe_load(f)["classes"]
|
||||
with open(spells_path, "r", encoding="utf-8") as f:
|
||||
self.spells = yaml.safe_load(f)["spells"]
|
||||
|
||||
def race(self, race_id: str) -> Dict[str, Any]:
|
||||
if race_id not in self.races:
|
||||
raise KeyError(f"Unknown race: {race_id}")
|
||||
return self.races[race_id]
|
||||
|
||||
def profession(self, class_id: str) -> Dict[str, Any]:
|
||||
if class_id not in self.classes:
|
||||
raise KeyError(f"Unknown class: {class_id}")
|
||||
return self.classes[class_id]
|
||||
|
||||
def spell(self, spell_id: str) -> Dict[str, Any]:
|
||||
if spell_id not in self.spells:
|
||||
raise KeyError(f"Unknown spell: {spell_id}")
|
||||
return self.spells[spell_id]
|
||||
|
||||
def from_dict(cls, d):
|
||||
"""Recursively reconstruct dataclasses from dicts."""
|
||||
if not is_dataclass(cls):
|
||||
return d
|
||||
kwargs = {}
|
||||
for f in fields(cls):
|
||||
value = d.get(f.name)
|
||||
if is_dataclass(f.type):
|
||||
value = from_dict(f.type, value)
|
||||
kwargs[f.name] = value
|
||||
return cls(**kwargs)
|
||||
Reference in New Issue
Block a user