init commit
This commit is contained in:
24
app/game/utils/common.py
Normal file
24
app/game/utils/common.py
Normal file
@@ -0,0 +1,24 @@
|
||||
from __future__ import annotations
|
||||
import math
|
||||
import random
|
||||
|
||||
from logging import getLogger
|
||||
|
||||
logger = getLogger(__file__)
|
||||
|
||||
class Dice:
|
||||
def roll_dice(self, spec: str = "1d6"):
|
||||
# supports "1d10", "2d6" etc
|
||||
total = 0
|
||||
try:
|
||||
n, d = map(int, spec.lower().split("d"))
|
||||
for _ in range(0,n,1):
|
||||
total += random.randint(1,d)
|
||||
return total
|
||||
except Exception as e:
|
||||
logger.error(f"Unable to roll dice spec: {spec} - please use 1d10 or similar")
|
||||
return 0
|
||||
|
||||
def max_of_die(self, spec: str) -> int:
|
||||
n, d = map(int, spec.lower().split("d"))
|
||||
return n * d
|
||||
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