2023-12-02 18:24:26 -08:00
|
|
|
import importlib
|
|
|
|
import os
|
|
|
|
import pkgutil
|
2023-12-04 21:51:15 -08:00
|
|
|
import random
|
2023-12-02 18:24:26 -08:00
|
|
|
import sys
|
|
|
|
|
2023-12-04 21:51:15 -08:00
|
|
|
from functools import cache
|
2023-12-02 18:24:26 -08:00
|
|
|
from types import ModuleType
|
|
|
|
|
2023-12-04 21:51:15 -08:00
|
|
|
from .types import NPC
|
2023-12-02 18:24:26 -08:00
|
|
|
|
|
|
|
|
|
|
|
def _import_submodules(module):
|
|
|
|
pkgs = pkgutil.iter_modules(module.__path__)
|
|
|
|
for loader, module_name, is_pkg in pkgs:
|
|
|
|
yield importlib.import_module(f"{module.__name__}.{module_name}")
|
|
|
|
|
|
|
|
|
2023-12-04 21:51:15 -08:00
|
|
|
@cache
|
2023-12-02 18:24:26 -08:00
|
|
|
def load_ancestry_pack(module_name: str = "") -> ModuleType:
|
|
|
|
if not module_name:
|
|
|
|
module_name = os.getenv("NPC_ANCESTRY_PACK", "npc.ancestries")
|
|
|
|
ancestry_pack = importlib.import_module(module_name)
|
|
|
|
_import_submodules(ancestry_pack)
|
|
|
|
supported_ancestries = dict(
|
|
|
|
(module.__name__.split(".")[-1], module) for module in list(_import_submodules(sys.modules[module_name]))
|
|
|
|
)
|
|
|
|
return ancestry_pack, supported_ancestries
|
2023-12-04 21:51:15 -08:00
|
|
|
|
|
|
|
|
|
|
|
def random_npc(ancestries: list = []) -> NPC:
|
|
|
|
if not ancestries:
|
|
|
|
_, ancestries = load_ancestry_pack()
|
|
|
|
return random.choice(list(ancestries.values())).NPC()
|