From 7adb937746b4a1f552fd3dd01ee7cd387b78a3fb Mon Sep 17 00:00:00 2001 From: dodo Date: Wed, 8 Jan 2025 22:35:51 +0100 Subject: [PATCH 01/37] WIP: Area now only stores references to Entities --- src/fantasy_forge/area.py | 46 +++++--------------------------------- src/fantasy_forge/world.py | 7 +++++- 2 files changed, 12 insertions(+), 41 deletions(-) diff --git a/src/fantasy_forge/area.py b/src/fantasy_forge/area.py index 386eee2..5c67715 100644 --- a/src/fantasy_forge/area.py +++ b/src/fantasy_forge/area.py @@ -18,18 +18,21 @@ class Area(Entity): __important_attributes__ = ("name",) contents: dict[str, Entity] + content_refs: list[str] # names of Entities def __init__(self: Self, config_dict: dict[str, Any], l10n: FluentLocalization): """ config_dict contents + 'content_refs' (list[str]): list of contents as names of Entity objects (default: []) inherited from Entity 'name' (str): name of the entity 'description' (str): description of the entity (default: "") 'obvious'(bool): whether the entity will be spotted immediately (default: False) """ - super().__init__(config_dict, l10n) + self.contents_refs = config_dict.get("content_refs", []) self.contents: dict = {} + super().__init__(config_dict, l10n) def __iter__(self: Self) -> Iterator: for obj in self.contents: @@ -45,48 +48,11 @@ def on_look(self: Self) -> str: ) def to_dict(self: Self) -> dict: + """Return area as a dictionary.""" area_dict: dict = super().to_dict() - area_dict["contents"] = self.contents + area_dict["content_refs"] = self.content_refs return area_dict - @staticmethod - def from_dict(area_dict: dict, l10n: FluentLocalization) -> Area: - contents_list: list[Entity] = [] - for entity_dict in area_dict.get("contents", []): - match entity_dict.get("kind", "entity"): - case "item": - from fantasy_forge.item import Item - - contents_list.append(Item(entity_dict, l10n)) - case "gateway": - from fantasy_forge.gateway import Gateway - - contents_list.append(Gateway(entity_dict, l10n)) - case "key": - from fantasy_forge.key import Key - - contents_list.append(Key(entity_dict, l10n)) - case "enemy": - from fantasy_forge.enemy import Enemy - - contents_list.append(Enemy(entity_dict, l10n)) - case "weapon": - from fantasy_forge.weapon import Weapon - - contents_list.append(Weapon(entity_dict, l10n)) - case "armour": - from fantasy_forge.armour import Armour - - contents_list.append(Armour(entity_dict, l10n)) - - case default: - logger.info("could not determine %s used Entity instead", default) - contents_list.append(Entity(entity_dict, l10n)) - contents = {entity.name: entity for entity in contents_list} - area = Area(area_dict, l10n) - area.contents = contents - return area - @staticmethod def load(world, root_path: Path, name: str): """Loads an area from toml-file.""" diff --git a/src/fantasy_forge/world.py b/src/fantasy_forge/world.py index c830266..9ec5b79 100644 --- a/src/fantasy_forge/world.py +++ b/src/fantasy_forge/world.py @@ -41,7 +41,12 @@ def __init__( self._load_assets() # populate areas dict - for area in self.assets["Area"]: + area: Area + for area in self.filter(Area): + for ref in area.contents_refs: + # load entity from asset store into area + area.contents[ref.name] = self[ref.name] + # save area in areas dict self.areas[area.name] = area @property From 420b63cd294eec5121d8b636c3e25867ff0b0215 Mon Sep 17 00:00:00 2001 From: dodo Date: Sat, 14 Dec 2024 04:18:20 +0100 Subject: [PATCH 02/37] init flat folder structure --- src/fantasy_forge/load_assets.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/fantasy_forge/load_assets.py b/src/fantasy_forge/load_assets.py index e0fb844..0110e04 100644 --- a/src/fantasy_forge/load_assets.py +++ b/src/fantasy_forge/load_assets.py @@ -11,6 +11,7 @@ from fantasy_forge.item import Item from fantasy_forge.key import Key from fantasy_forge.player import Player +from fantasy_forge.utils import WORLDS_FOLDER from fantasy_forge.weapon import Weapon logger = logging.getLogger(__name__) @@ -29,3 +30,10 @@ "players": Player, "weapons": Weapon, } + + +def init_flat_folder_structure(world_name: str): + world_path = WORLDS_FOLDER / world_name + world_path.mkdir() + for cls_dir, cls in ASSET_TYPES.items(): + (world_path / cls_dir).mkdir() From 3d3c2391c0843f70223b471d1c603dd9f03ec5b5 Mon Sep 17 00:00:00 2001 From: dodo Date: Sat, 14 Dec 2024 04:32:00 +0100 Subject: [PATCH 03/37] init nested folder structure --- src/fantasy_forge/load_assets.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/fantasy_forge/load_assets.py b/src/fantasy_forge/load_assets.py index 0110e04..1b27bd3 100644 --- a/src/fantasy_forge/load_assets.py +++ b/src/fantasy_forge/load_assets.py @@ -37,3 +37,18 @@ def init_flat_folder_structure(world_name: str): world_path.mkdir() for cls_dir, cls in ASSET_TYPES.items(): (world_path / cls_dir).mkdir() + +def init_nested_folder_structure(world_name: str): + world_path = WORLDS_DIR / world_name + for c in CONSTRUCTORS.values(): + current = c + tmp = f"{current.__name__}" + while True: + bases = current.__bases__ + if object in bases: + break + else: + current = bases[0] + tmp = f"{current.__name__}/{tmp}" + path = world_path / tmp + path.mkdir(parents=True, exist_ok=True) \ No newline at end of file From 3904816f236b7ad8989614aae4b3407eda7a771b Mon Sep 17 00:00:00 2001 From: dodo Date: Sat, 14 Dec 2024 13:59:09 +0100 Subject: [PATCH 04/37] refactoring better variable names, type hints --- src/fantasy_forge/load_assets.py | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/src/fantasy_forge/load_assets.py b/src/fantasy_forge/load_assets.py index 1b27bd3..879e697 100644 --- a/src/fantasy_forge/load_assets.py +++ b/src/fantasy_forge/load_assets.py @@ -33,22 +33,27 @@ def init_flat_folder_structure(world_name: str): + """Generates flat directory structure for asset types.""" world_path = WORLDS_FOLDER / world_name world_path.mkdir() - for cls_dir, cls in ASSET_TYPES.items(): + for cls_dir in ASSET_TYPES: (world_path / cls_dir).mkdir() + def init_nested_folder_structure(world_name: str): - world_path = WORLDS_DIR / world_name - for c in CONSTRUCTORS.values(): - current = c - tmp = f"{current.__name__}" + """Generates nested directory structure based on class inheritance.""" + world_path = WORLDS_FOLDER / world_name + + asset_type: type + for asset_type in ASSET_TYPES.values(): + current: type = asset_type + path_str: str = current.__name__ while True: - bases = current.__bases__ + bases: tuple[type, ...] = current.__bases__ if object in bases: break else: current = bases[0] - tmp = f"{current.__name__}/{tmp}" - path = world_path / tmp - path.mkdir(parents=True, exist_ok=True) \ No newline at end of file + path_str = f"{current.__name__}/{path_str}" + path = world_path / path_str + path.mkdir(parents=True, exist_ok=True) From e5896c9a0205b92cbf210cf0344b0143e5560feb Mon Sep 17 00:00:00 2001 From: dodo Date: Sat, 14 Dec 2024 14:04:16 +0100 Subject: [PATCH 05/37] refactoring --- src/fantasy_forge/load_assets.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/fantasy_forge/load_assets.py b/src/fantasy_forge/load_assets.py index 879e697..45d1b98 100644 --- a/src/fantasy_forge/load_assets.py +++ b/src/fantasy_forge/load_assets.py @@ -47,13 +47,16 @@ def init_nested_folder_structure(world_name: str): asset_type: type for asset_type in ASSET_TYPES.values(): current: type = asset_type - path_str: str = current.__name__ + type_hierachy: list[type] = [current] + while True: bases: tuple[type, ...] = current.__bases__ if object in bases: break else: current = bases[0] - path_str = f"{current.__name__}/{path_str}" - path = world_path / path_str + type_hierachy.insert(0, current) + + path_str: str = "/".join((t.__name__ for t in type_hierachy)) + path: Path = world_path / path_str path.mkdir(parents=True, exist_ok=True) From 443f27e73f5c3b4a35e0d1b0f104326d05898858 Mon Sep 17 00:00:00 2001 From: dodo Date: Sun, 5 Jan 2025 12:56:22 +0100 Subject: [PATCH 06/37] some refactoring --- src/fantasy_forge/load_assets.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/fantasy_forge/load_assets.py b/src/fantasy_forge/load_assets.py index 45d1b98..879c67e 100644 --- a/src/fantasy_forge/load_assets.py +++ b/src/fantasy_forge/load_assets.py @@ -1,4 +1,5 @@ import logging +from pathlib import Path from fantasy_forge.area import Area from fantasy_forge.armour import Armour @@ -36,8 +37,9 @@ def init_flat_folder_structure(world_name: str): """Generates flat directory structure for asset types.""" world_path = WORLDS_FOLDER / world_name world_path.mkdir() - for cls_dir in ASSET_TYPES: - (world_path / cls_dir).mkdir() + asset_type: type + for asset_type in ASSET_TYPES: + (world_path / asset_type.__name__).mkdir() def init_nested_folder_structure(world_name: str): @@ -47,7 +49,7 @@ def init_nested_folder_structure(world_name: str): asset_type: type for asset_type in ASSET_TYPES.values(): current: type = asset_type - type_hierachy: list[type] = [current] + type_hierarchy: list[type] = [current] while True: bases: tuple[type, ...] = current.__bases__ @@ -55,8 +57,8 @@ def init_nested_folder_structure(world_name: str): break else: current = bases[0] - type_hierachy.insert(0, current) + type_hierarchy.insert(0, current) - path_str: str = "/".join((t.__name__ for t in type_hierachy)) + path_str: str = "/".join((t.__name__ for t in type_hierarchy)) path: Path = world_path / path_str path.mkdir(parents=True, exist_ok=True) From 4099c05b8a26378fcb2971aa5ce6aa3f2001a242 Mon Sep 17 00:00:00 2001 From: dodo Date: Sun, 5 Jan 2025 13:26:46 +0100 Subject: [PATCH 07/37] changes asset_types into a dict --- src/fantasy_forge/load_assets.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/fantasy_forge/load_assets.py b/src/fantasy_forge/load_assets.py index 879c67e..f15c51d 100644 --- a/src/fantasy_forge/load_assets.py +++ b/src/fantasy_forge/load_assets.py @@ -37,9 +37,9 @@ def init_flat_folder_structure(world_name: str): """Generates flat directory structure for asset types.""" world_path = WORLDS_FOLDER / world_name world_path.mkdir() - asset_type: type + asset_type: str for asset_type in ASSET_TYPES: - (world_path / asset_type.__name__).mkdir() + (world_path / asset_type).mkdir() def init_nested_folder_structure(world_name: str): From a34b723bfacbd425456b867a74bed98cd9c5c81f Mon Sep 17 00:00:00 2001 From: dodo Date: Sun, 5 Jan 2025 15:42:03 +0100 Subject: [PATCH 08/37] renames module --- src/fantasy_forge/{load_assets.py => folder_structure.py} | 0 src/fantasy_forge/world.py | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) rename src/fantasy_forge/{load_assets.py => folder_structure.py} (100%) diff --git a/src/fantasy_forge/load_assets.py b/src/fantasy_forge/folder_structure.py similarity index 100% rename from src/fantasy_forge/load_assets.py rename to src/fantasy_forge/folder_structure.py diff --git a/src/fantasy_forge/world.py b/src/fantasy_forge/world.py index 9ec5b79..8fbb7c9 100644 --- a/src/fantasy_forge/world.py +++ b/src/fantasy_forge/world.py @@ -8,7 +8,7 @@ import toml from fantasy_forge.area import Area -from fantasy_forge.load_assets import ASSET_TYPES +from fantasy_forge.folder_structure import ASSET_TYPES from fantasy_forge.localization import get_fluent_locale from fantasy_forge.utils import WORLDS_FOLDER From 2d1bb760be0d9e31d4452aedc50b912b6ccad04c Mon Sep 17 00:00:00 2001 From: dodo Date: Sun, 5 Jan 2025 16:06:04 +0100 Subject: [PATCH 09/37] type alias for asset type world.get_asset and world.iter_asset --- src/fantasy_forge/folder_structure.py | 30 ++++++++++++++++++++------- src/fantasy_forge/world.py | 30 ++++++++++++++++++++------- 2 files changed, 45 insertions(+), 15 deletions(-) diff --git a/src/fantasy_forge/folder_structure.py b/src/fantasy_forge/folder_structure.py index f15c51d..0e7731c 100644 --- a/src/fantasy_forge/folder_structure.py +++ b/src/fantasy_forge/folder_structure.py @@ -1,5 +1,6 @@ import logging from pathlib import Path +from typing import TypeAlias, Union from fantasy_forge.area import Area from fantasy_forge.armour import Armour @@ -17,7 +18,22 @@ logger = logging.getLogger(__name__) -ASSET_TYPES: dict[str, type] = { +ASSET_TYPE: TypeAlias = Union[ + Area, + Armour, + Character, + Container, + Enemy, + Entity, + Gateway, + Inventory, + Item, + Key, + Player, + Weapon, +] + +ASSET_TYPE_DICT: dict[str, type] = { "areas": Area, "armour": Armour, "characters": Character, @@ -38,7 +54,7 @@ def init_flat_folder_structure(world_name: str): world_path = WORLDS_FOLDER / world_name world_path.mkdir() asset_type: str - for asset_type in ASSET_TYPES: + for asset_type in ASSET_TYPE_DICT: (world_path / asset_type).mkdir() @@ -46,13 +62,13 @@ def init_nested_folder_structure(world_name: str): """Generates nested directory structure based on class inheritance.""" world_path = WORLDS_FOLDER / world_name - asset_type: type - for asset_type in ASSET_TYPES.values(): - current: type = asset_type - type_hierarchy: list[type] = [current] + asset_type: ASSET_TYPE + for asset_type in ASSET_TYPE_DICT.values(): + current: ASSET_TYPE = asset_type + type_hierarchy: list[ASSET_TYPE] = [current] while True: - bases: tuple[type, ...] = current.__bases__ + bases: tuple[ASSET_TYPE, ...] = current.__bases__ if object in bases: break else: diff --git a/src/fantasy_forge/world.py b/src/fantasy_forge/world.py index 8fbb7c9..9722f04 100644 --- a/src/fantasy_forge/world.py +++ b/src/fantasy_forge/world.py @@ -3,12 +3,12 @@ import logging from collections import defaultdict from pathlib import Path -from typing import IO, TYPE_CHECKING, Self +from typing import IO, TYPE_CHECKING, Iterator, Self -import toml +from toml import load from fantasy_forge.area import Area -from fantasy_forge.folder_structure import ASSET_TYPES +from fantasy_forge.folder_structure import ASSET_TYPE, ASSET_TYPE_DICT from fantasy_forge.localization import get_fluent_locale from fantasy_forge.utils import WORLDS_FOLDER @@ -67,7 +67,7 @@ def load(name: str) -> World: world_toml_path: Path = world_path / "world.toml" with world_toml_path.open() as world_file: - world_toml_data: dict = toml.load(world_file) + world_toml_data: dict = load(world_file) world_name: str = world_toml_data["name"] assert world_name == name @@ -90,12 +90,12 @@ def _load_assets(self): # iterate through world dir toml_path: Path for toml_path in world_path.glob("**/*.toml"): - asset_type: type + asset_type: ASSET_TYPE parent: str = toml_path.parent.name # infer type from parent directory - if parent in ASSET_TYPES.keys(): - asset_type = ASSET_TYPES[parent] + if parent in ASSET_TYPE_DICT.keys(): + asset_type = ASSET_TYPE_DICT[parent] else: logger.info("skipped %s", toml_path.name) continue @@ -103,7 +103,7 @@ def _load_assets(self): # read toml io: IO with toml_path.open(encoding="utf-8") as io: - toml_data: dict = toml.load(io) + toml_data: dict = load(io) # parse asset from toml data if hasattr(asset_type, "from_dict"): @@ -114,6 +114,20 @@ def _load_assets(self): self.assets[asset_type.__name__].append(asset) + def iter_assets(self) -> Iterator[ASSET_TYPE]: + for assets in self.assets.values(): + yield from assets + + def get_asset(self, asset_name: str, asset_type: str = "") -> ASSET_TYPE: + if asset_type: + assets = self.assets[asset_type] + else: + assets = self.iter_assets() + + for asset in assets: + if asset.__name__ == asset_name: + return asset + if TYPE_CHECKING: from fluent.runtime import FluentLocalization From d9863a4719d5d7b81d445cbf1a73b92b1ebd35a0 Mon Sep 17 00:00:00 2001 From: dodo Date: Sun, 5 Jan 2025 19:23:31 +0100 Subject: [PATCH 10/37] adds asset2path function --- src/fantasy_forge/folder_structure.py | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/src/fantasy_forge/folder_structure.py b/src/fantasy_forge/folder_structure.py index 0e7731c..cd1b593 100644 --- a/src/fantasy_forge/folder_structure.py +++ b/src/fantasy_forge/folder_structure.py @@ -64,17 +64,20 @@ def init_nested_folder_structure(world_name: str): asset_type: ASSET_TYPE for asset_type in ASSET_TYPE_DICT.values(): - current: ASSET_TYPE = asset_type - type_hierarchy: list[ASSET_TYPE] = [current] + path = asset2path(world_name, asset_type) + path.mkdir(parents=True, exist_ok=True) - while True: - bases: tuple[ASSET_TYPE, ...] = current.__bases__ - if object in bases: - break - else: - current = bases[0] - type_hierarchy.insert(0, current) +def asset2path(world_name: str, asset_type: ASSET_TYPE) -> Path: + world_path = WORLDS_FOLDER / world_name - path_str: str = "/".join((t.__name__ for t in type_hierarchy)) - path: Path = world_path / path_str - path.mkdir(parents=True, exist_ok=True) + current: ASSET_TYPE = asset_type + type_hierarchy: list[ASSET_TYPE] = [current] + while True: + bases: tuple[ASSET_TYPE, ...] = current.__bases__ + if object in bases: + break + current = bases[0] + type_hierarchy.insert(0, current) + path_str: str = "/".join((t.__name__ for t in type_hierarchy)) + path: Path = world_path / path_str + return path \ No newline at end of file From 953ecb112d2cf0e35b6a23c3a86426a6563b3e0f Mon Sep 17 00:00:00 2001 From: dodo Date: Sun, 5 Jan 2025 19:25:04 +0100 Subject: [PATCH 11/37] adds add_asset module easy way to add new assets via the commandline --- src/fantasy_forge/add_asset.py | 76 ++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 src/fantasy_forge/add_asset.py diff --git a/src/fantasy_forge/add_asset.py b/src/fantasy_forge/add_asset.py new file mode 100644 index 0000000..c00248e --- /dev/null +++ b/src/fantasy_forge/add_asset.py @@ -0,0 +1,76 @@ +from pathlib import Path + +import toml + +from fantasy_forge.folder_structure import ( + ASSET_TYPE, + ASSET_TYPE_DICT, + asset2path, +) +from fantasy_forge.utils import WORLDS_FOLDER, clean_filename +# TODO: use questionairy for type parsing + +def bool_from_str(str_data: str) -> bool: + match str_data.casefold(): + case "true" | "y": + return True + case "false" | "n": + return False + case _: + return False + + +def get_asset_data(asset_type: ASSET_TYPE) -> dict: + config_dict: dict = {} + attr_name: str + attr_type: type + for attr_name, attr_type in asset_type.__attributes__.items(): + raw = input(f"{attr_type.__name__:>8} {attr_name}: ") + data = PARSER[attr_type](raw) + config_dict[attr_name] = data + return config_dict + + +def main(): + # select world + # TODO: allow world selection through argument parser + world_name: str = input("World name: ") + world_path: Path = WORLDS_FOLDER / world_name + assert world_path.exists() + + while True: + # select asset type + asset_type_inp: str = input("Asset type: ") + if not asset_type_inp: + break + + asset_type: ASSET_TYPE = ASSET_TYPE_DICT[asset_type_inp] + + # input asset specific data + config_dict: dict = get_asset_data(asset_type) + + name: str = config_dict["name"] + + # save asset to file + filename = f"{clean_filename(name)}.toml" + + asset_path: Path = asset2path(world_name, asset_type) + filepath = asset_path / Path(filename) + + # TODO: implement a "safe" non-writing mode, selectable via ArgumentParser + with filepath.open("w", encoding="utf-8") as f: + content = toml.dumps(config_dict) + f.write(content) + + print(f"your {asset_type.__name__!r} was saved at {filepath}") + print() + + +PARSER = { + int: int, + str: str, + bool: bool_from_str, +} + +if __name__ == "__main__": + main() From 91698f86f6be0467aeb3585fb761a75521c7b4f0 Mon Sep 17 00:00:00 2001 From: dodo Date: Sun, 5 Jan 2025 20:08:38 +0100 Subject: [PATCH 12/37] separate directory for builder --- src/{fantasy_forge => builder}/add_asset.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/{fantasy_forge => builder}/add_asset.py (100%) diff --git a/src/fantasy_forge/add_asset.py b/src/builder/add_asset.py similarity index 100% rename from src/fantasy_forge/add_asset.py rename to src/builder/add_asset.py From c90040e6038796b1e42657cdbffb56dd99569564 Mon Sep 17 00:00:00 2001 From: dodo Date: Sun, 5 Jan 2025 21:27:46 +0100 Subject: [PATCH 13/37] adds dependency for questionary --- pyproject.toml | 1 + uv.lock | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index d0c7f79..c0406c6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -12,6 +12,7 @@ dependencies = [ "toml", "huepy", "fuzzywuzzy>=0.18.0", + "questionary", ] [project.scripts] diff --git a/uv.lock b/uv.lock index 8546c8a..d20fd1f 100644 --- a/uv.lock +++ b/uv.lock @@ -54,6 +54,7 @@ dependencies = [ { name = "fluent-runtime" }, { name = "fuzzywuzzy" }, { name = "huepy" }, + { name = "questionary" }, { name = "toml" }, ] @@ -70,6 +71,7 @@ requires-dist = [ { name = "fluent-runtime" }, { name = "fuzzywuzzy", specifier = ">=0.18.0" }, { name = "huepy" }, + { name = "questionary" }, { name = "toml" }, ] @@ -271,6 +273,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/bd/68/6429b6348b3757ce604d714402ada78e342d502cd9b799ee23c65393d1ba/prettystack-0.4.0-py3-none-any.whl", hash = "sha256:5526d37e31926e1b513205b7cb1dbf82412670771755d188fb6c42539e6de6d3", size = 5854 }, ] +[[package]] +name = "prompt-toolkit" +version = "3.0.50" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "wcwidth" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a1/e1/bd15cb8ffdcfeeb2bdc215de3c3cffca11408d829e4b8416dcfe71ba8854/prompt_toolkit-3.0.50.tar.gz", hash = "sha256:544748f3860a2623ca5cd6d2795e7a14f3d0e1c3c9728359013f79877fc89bab", size = 429087 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e4/ea/d836f008d33151c7a1f62caf3d8dd782e4d15f6a43897f64480c2b8de2ad/prompt_toolkit-3.0.50-py3-none-any.whl", hash = "sha256:9b6427eb19e479d98acff65196a307c555eb567989e6d88ebbb1b509d9779198", size = 387816 }, +] + [[package]] name = "psutil" version = "6.1.0" @@ -355,6 +369,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/11/c3/005fcca25ce078d2cc29fd559379817424e94885510568bc1bc53d7d5846/pytz-2024.2-py2.py3-none-any.whl", hash = "sha256:31c7c1817eb7fae7ca4b8c7ee50c72f93aa2dd863de768e1ef4245d426aa0725", size = 508002 }, ] +[[package]] +name = "questionary" +version = "2.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "prompt-toolkit" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a8/b8/d16eb579277f3de9e56e5ad25280fab52fc5774117fb70362e8c2e016559/questionary-2.1.0.tar.gz", hash = "sha256:6302cdd645b19667d8f6e6634774e9538bfcd1aad9be287e743d96cacaf95587", size = 26775 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ad/3f/11dd4cd4f39e05128bfd20138faea57bec56f9ffba6185d276e3107ba5b2/questionary-2.1.0-py3-none-any.whl", hash = "sha256:44174d237b68bc828e4878c763a9ad6790ee61990e0ae72927694ead57bab8ec", size = 36747 }, +] + [[package]] name = "six" version = "1.16.0" From 658f504aa1f5ac6d5dba5abb473d1fd1d73fe9f5 Mon Sep 17 00:00:00 2001 From: dodo Date: Sun, 5 Jan 2025 21:28:41 +0100 Subject: [PATCH 14/37] module for creating a new world --- src/builder/create_world.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/builder/create_world.py diff --git a/src/builder/create_world.py b/src/builder/create_world.py new file mode 100644 index 0000000..680242a --- /dev/null +++ b/src/builder/create_world.py @@ -0,0 +1,37 @@ +from pathlib import Path + +import questionary + +from fantasy_forge.utils import WORLDS_FOLDER, LOCALE_FOLDER +from fantasy_forge.localization import get_fluent_locale +from fluent.runtime import FluentLocalization +from fantasy_forge.folder_structure import init_nested_folder_structure + +world_name = questionary.text("Select a name for your world: ").ask() +world_dir: Path = WORLDS_FOLDER / world_name + +if world_dir.exists(): + print("A world with that name already exists.") + exit() +else: + print(f"Creating a new world at {world_dir}.") + +# choose locale +locale_options = [path.name for path in LOCALE_FOLDER.iterdir()] +locale = questionary.select("Choose a locale: ", choices=locale_options).ask() + +l10n: FluentLocalization = get_fluent_locale(locale) + +# create folder for new world +world_dir.mkdir() + +# init nested folder structure +init_nested_folder_structure(world_name) + +# create readme file +readme_file: Path = world_dir / "README.md" +readme_file.touch() +readme_file.write_text(f"# {world_name}\n", encoding="UTF-8") + +# TODO: enter areas +# TODO: create and save world object \ No newline at end of file From 5fefc6823dfda4a8f4586fcab4df18ff66376991 Mon Sep 17 00:00:00 2001 From: dodo Date: Sun, 5 Jan 2025 21:28:54 +0100 Subject: [PATCH 15/37] moves module --- src/{ => builder}/init_world.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/{ => builder}/init_world.py (100%) diff --git a/src/init_world.py b/src/builder/init_world.py similarity index 100% rename from src/init_world.py rename to src/builder/init_world.py From 7adbcff2d366812e5d9440a87f82c70cb46b398d Mon Sep 17 00:00:00 2001 From: dodo Date: Sun, 5 Jan 2025 21:29:11 +0100 Subject: [PATCH 16/37] uses questionary --- src/builder/add_asset.py | 55 +++++++++++++++++++++++++--------------- 1 file changed, 35 insertions(+), 20 deletions(-) diff --git a/src/builder/add_asset.py b/src/builder/add_asset.py index c00248e..81213ec 100644 --- a/src/builder/add_asset.py +++ b/src/builder/add_asset.py @@ -1,5 +1,5 @@ from pathlib import Path - +import questionary import toml from fantasy_forge.folder_structure import ( @@ -8,7 +8,7 @@ asset2path, ) from fantasy_forge.utils import WORLDS_FOLDER, clean_filename -# TODO: use questionairy for type parsing + def bool_from_str(str_data: str) -> bool: match str_data.casefold(): @@ -25,8 +25,16 @@ def get_asset_data(asset_type: ASSET_TYPE) -> dict: attr_name: str attr_type: type for attr_name, attr_type in asset_type.__attributes__.items(): - raw = input(f"{attr_type.__name__:>8} {attr_name}: ") - data = PARSER[attr_type](raw) + prompt = f"{attr_name}: " + match attr_type.__name__: + case "bool": + data = questionary.confirm(prompt).ask() + case "int": + raw = questionary.text(prompt).ask() + assert raw.isdigit() + data = int(raw) + case _: + data = questionary.text(prompt).ask() config_dict[attr_name] = data return config_dict @@ -34,16 +42,20 @@ def get_asset_data(asset_type: ASSET_TYPE) -> dict: def main(): # select world # TODO: allow world selection through argument parser - world_name: str = input("World name: ") + world_list = [path.name for path in WORLDS_FOLDER.iterdir()] + world_name = questionary.select( + "World name: ", choices=world_list, default="test" + ).ask() + world_path: Path = WORLDS_FOLDER / world_name assert world_path.exists() - while True: + running: bool = True + while running: # select asset type - asset_type_inp: str = input("Asset type: ") - if not asset_type_inp: - break - + asset_type_inp: str = questionary.select( + "Asset type: ", choices=list(ASSET_TYPE_DICT.keys()), default="Entity" + ).ask() asset_type: ASSET_TYPE = ASSET_TYPE_DICT[asset_type_inp] # input asset specific data @@ -57,20 +69,23 @@ def main(): asset_path: Path = asset2path(world_name, asset_type) filepath = asset_path / Path(filename) - # TODO: implement a "safe" non-writing mode, selectable via ArgumentParser - with filepath.open("w", encoding="utf-8") as f: - content = toml.dumps(config_dict) - f.write(content) + save = questionary.confirm( + "Do you want to save this asset?", default=True + ).ask() + if save: + with filepath.open("w", encoding="utf-8") as f: + content = toml.dumps(config_dict) + f.write(content) + + print(f"your {asset_type.__name__!r} was saved at: ") + questionary.print(f"{filepath}", style="italic") + else: + print(f"your {asset_type.__name__!r} wasn't saved") - print(f"your {asset_type.__name__!r} was saved at {filepath}") print() + running = questionary.confirm("Do you want to continue?").ask() -PARSER = { - int: int, - str: str, - bool: bool_from_str, -} if __name__ == "__main__": main() From 8654a811450948067c81c30c614177b6ba2f0e43 Mon Sep 17 00:00:00 2001 From: dodo Date: Sun, 5 Jan 2025 21:29:20 +0100 Subject: [PATCH 17/37] refactoring --- src/fantasy_forge/folder_structure.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/fantasy_forge/folder_structure.py b/src/fantasy_forge/folder_structure.py index cd1b593..d179e01 100644 --- a/src/fantasy_forge/folder_structure.py +++ b/src/fantasy_forge/folder_structure.py @@ -60,8 +60,6 @@ def init_flat_folder_structure(world_name: str): def init_nested_folder_structure(world_name: str): """Generates nested directory structure based on class inheritance.""" - world_path = WORLDS_FOLDER / world_name - asset_type: ASSET_TYPE for asset_type in ASSET_TYPE_DICT.values(): path = asset2path(world_name, asset_type) From 39a6c41b2fea9310a263938db6ae5c368cb2937c Mon Sep 17 00:00:00 2001 From: dodo Date: Sun, 5 Jan 2025 21:30:47 +0100 Subject: [PATCH 18/37] moves obsolete module in the correct folder --- src/builder/builder.py | 151 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 151 insertions(+) create mode 100644 src/builder/builder.py diff --git a/src/builder/builder.py b/src/builder/builder.py new file mode 100644 index 0000000..45437bf --- /dev/null +++ b/src/builder/builder.py @@ -0,0 +1,151 @@ +"""Generates toml files for new world.""" + +from cmd import Cmd +from pathlib import Path +from typing import Self + +import toml + +# TODO: centralized save & load method +# TODO: auto completion for commands + + +class Builder(Cmd): + root_dir: Path = Path.cwd() / "worlds" + current_world: Path | None # TODO: Change type to World + current_area_dir: Path | None + current_area: Path | None # TODO: Change type to Area + + world_toml: dict | None + area_toml: dict | None + + def __init__(self: Self): + self.current_world = None + self.current_area = None + self.current_area_dir = None + + self.world_toml = None + self.area_toml = None + + def do_status(self: Self, arg: str): + print(f"root directory: {self.root_dir}") + print(f"current world: {self.current_world}") + print(f"current area: {self.current_area}") + + def do_new(self: Self, arg: str): + match arg.strip().lower(): + case "world": + self.new_world() + case "area": + self.new_area() + case _: + raise NotImplementedError(f"new {arg} is not yet implemented.") + + def new_world(self: Self): + world_name: str = input("Enter a name for your world: ") + world_dir = self.root_dir / world_name + if world_dir.exists(): + print("A world with that name already exists.") + return + # create dir for world + world_dir.mkdir() + + # create area dir for world + area_dir: Path = world_dir / "areas" + area_dir.mkdir() + + # sets up world.toml file + toml_path: Path = world_dir / "world.toml" + toml_path.touch() + + # sets up readme file for world + readme_path: Path = world_dir / "README.md" + readme_path.touch() + + # ask for world description + description: str = input("Enter a description for your world: \n") + + self.current_world = world_dir + self.world_toml = {"name": world_name, "description": description, "areas": []} + self.current_area_dir = area_dir + + def new_area(self: Self): + if self.current_world is None: + print("You have to create or select a world first.") + return + + area_name: str = input("Enter a name for your area: ") + area_desc: str = input("Enter a description for your area: \n") + + area_toml = {"name": area_name, "description": area_desc} + + # create area.toml file + area_path: Path = self.current_area_dir / f"{area_name}.toml" + area_path.touch() + + # dump area toml to file + with area_path.open("w", encoding="UTF-8") as stream: + toml.dump(area_toml, stream) + self.area_toml = area_toml + + # add area to world.toml + self.world_toml["areas"].append(area_name) + + self.current_area = area_path + + def new_item(self: Self): + # TODO + pass + + def new_key(self: Self): + # TODO + pass + + def new_gateway(self: Self): + # TODO + pass + + def do_list(self: Self, arg: str): + match arg.strip().lower(): + case "world": + self.list_world() + case "area": + self.list_area() + case _: + raise NotImplementedError(f"new {arg} is not yet implemented.") + + def list_world(self: Self): + for world_path in self.root_dir.iterdir(): + print(world_path) + + def list_area(self: Self): + if self.current_area_dir is None: + print("You have to create or select a world first.") + return + for area_path in self.current_area_dir.glob("*.toml"): + print(area_path) + + def do_select(self: Self, arg: str): + match arg.strip().lower(): + case "world": + self.select_world() + case "area": + self.select_area() + + def select_world(self: Self): + # TODO: implement select menu + pass + + def select_area(self: Self): + # TODO: implement select menu + pass + + def do_quit(self: Self, arg: str): + # write world.toml to file + with self.current_world.open("w", encoding="UTF-8") as stream: + toml.dump(self.world_toml, stream) + + +if __name__ == "__main__": + builder = Builder() + builder.cmdloop() From 10aba27054a88bd35c2ef34f8ec466b1cc7fb776 Mon Sep 17 00:00:00 2001 From: dodo Date: Mon, 6 Jan 2025 12:29:23 +0100 Subject: [PATCH 19/37] combines two modules --- src/builder/builder.py | 165 +++++++----------------------------- src/builder/create_world.py | 37 -------- 2 files changed, 31 insertions(+), 171 deletions(-) delete mode 100644 src/builder/create_world.py diff --git a/src/builder/builder.py b/src/builder/builder.py index 45437bf..b729a9f 100644 --- a/src/builder/builder.py +++ b/src/builder/builder.py @@ -1,151 +1,48 @@ """Generates toml files for new world.""" +import logging from cmd import Cmd from pathlib import Path -from typing import Self -import toml +import questionary +from fluent.runtime import FluentLocalization -# TODO: centralized save & load method -# TODO: auto completion for commands +from fantasy_forge.folder_structure import init_nested_folder_structure +from fantasy_forge.localization import get_fluent_locale +from fantasy_forge.utils import LOCALE_FOLDER, WORLDS_FOLDER, clean_filename +from fantasy_forge.world import World +logger = logging.getLogger(__name__) -class Builder(Cmd): - root_dir: Path = Path.cwd() / "worlds" - current_world: Path | None # TODO: Change type to World - current_area_dir: Path | None - current_area: Path | None # TODO: Change type to Area - world_toml: dict | None - area_toml: dict | None +def new_world() -> World: + name = questionary.select("Which world do ou choose? ", choices=world_list).ask() + world_dir: Path = WORLDS_FOLDER / clean_filename(name) - def __init__(self: Self): - self.current_world = None - self.current_area = None - self.current_area_dir = None + # choose locale + locale_options = [path.name for path in sorted(LOCALE_FOLDER.iterdir())] + locale = questionary.select("Choose a locale: ", choices=locale_options).ask() - self.world_toml = None - self.area_toml = None + l10n: FluentLocalization = get_fluent_locale(locale) - def do_status(self: Self, arg: str): - print(f"root directory: {self.root_dir}") - print(f"current world: {self.current_world}") - print(f"current area: {self.current_area}") + # create folder for new world + world_dir.mkdir() - def do_new(self: Self, arg: str): - match arg.strip().lower(): - case "world": - self.new_world() - case "area": - self.new_area() - case _: - raise NotImplementedError(f"new {arg} is not yet implemented.") + # init nested folder structure + init_nested_folder_structure(name) - def new_world(self: Self): - world_name: str = input("Enter a name for your world: ") - world_dir = self.root_dir / world_name - if world_dir.exists(): - print("A world with that name already exists.") - return - # create dir for world - world_dir.mkdir() + # create readme file + readme_file: Path = world_dir / "README.md" + readme_file.touch() + readme_file.write_text(f"# {name}\n", encoding="UTF-8") - # create area dir for world - area_dir: Path = world_dir / "areas" - area_dir.mkdir() + # create world object + world = World(l10n, name, {}, "") + return world - # sets up world.toml file - toml_path: Path = world_dir / "world.toml" - toml_path.touch() - # sets up readme file for world - readme_path: Path = world_dir / "README.md" - readme_path.touch() - - # ask for world description - description: str = input("Enter a description for your world: \n") - - self.current_world = world_dir - self.world_toml = {"name": world_name, "description": description, "areas": []} - self.current_area_dir = area_dir - - def new_area(self: Self): - if self.current_world is None: - print("You have to create or select a world first.") - return - - area_name: str = input("Enter a name for your area: ") - area_desc: str = input("Enter a description for your area: \n") - - area_toml = {"name": area_name, "description": area_desc} - - # create area.toml file - area_path: Path = self.current_area_dir / f"{area_name}.toml" - area_path.touch() - - # dump area toml to file - with area_path.open("w", encoding="UTF-8") as stream: - toml.dump(area_toml, stream) - self.area_toml = area_toml - - # add area to world.toml - self.world_toml["areas"].append(area_name) - - self.current_area = area_path - - def new_item(self: Self): - # TODO - pass - - def new_key(self: Self): - # TODO - pass - - def new_gateway(self: Self): - # TODO - pass - - def do_list(self: Self, arg: str): - match arg.strip().lower(): - case "world": - self.list_world() - case "area": - self.list_area() - case _: - raise NotImplementedError(f"new {arg} is not yet implemented.") - - def list_world(self: Self): - for world_path in self.root_dir.iterdir(): - print(world_path) - - def list_area(self: Self): - if self.current_area_dir is None: - print("You have to create or select a world first.") - return - for area_path in self.current_area_dir.glob("*.toml"): - print(area_path) - - def do_select(self: Self, arg: str): - match arg.strip().lower(): - case "world": - self.select_world() - case "area": - self.select_area() - - def select_world(self: Self): - # TODO: implement select menu - pass - - def select_area(self: Self): - # TODO: implement select menu - pass - - def do_quit(self: Self, arg: str): - # write world.toml to file - with self.current_world.open("w", encoding="UTF-8") as stream: - toml.dump(self.world_toml, stream) - - -if __name__ == "__main__": - builder = Builder() - builder.cmdloop() +def select_world() -> World: + world_list = [world.name for world in WORLDS_FOLDER.iterdir()] + name = questionary.select("Which world do ou choose? ", choices=world_list).ask() + world = World.load(name) + return world diff --git a/src/builder/create_world.py b/src/builder/create_world.py deleted file mode 100644 index 680242a..0000000 --- a/src/builder/create_world.py +++ /dev/null @@ -1,37 +0,0 @@ -from pathlib import Path - -import questionary - -from fantasy_forge.utils import WORLDS_FOLDER, LOCALE_FOLDER -from fantasy_forge.localization import get_fluent_locale -from fluent.runtime import FluentLocalization -from fantasy_forge.folder_structure import init_nested_folder_structure - -world_name = questionary.text("Select a name for your world: ").ask() -world_dir: Path = WORLDS_FOLDER / world_name - -if world_dir.exists(): - print("A world with that name already exists.") - exit() -else: - print(f"Creating a new world at {world_dir}.") - -# choose locale -locale_options = [path.name for path in LOCALE_FOLDER.iterdir()] -locale = questionary.select("Choose a locale: ", choices=locale_options).ask() - -l10n: FluentLocalization = get_fluent_locale(locale) - -# create folder for new world -world_dir.mkdir() - -# init nested folder structure -init_nested_folder_structure(world_name) - -# create readme file -readme_file: Path = world_dir / "README.md" -readme_file.touch() -readme_file.write_text(f"# {world_name}\n", encoding="UTF-8") - -# TODO: enter areas -# TODO: create and save world object \ No newline at end of file From 1cb9e3c2d3d167954284266f226de07a4a0ea521 Mon Sep 17 00:00:00 2001 From: dodo Date: Mon, 6 Jan 2025 12:30:44 +0100 Subject: [PATCH 20/37] removes obsolete module --- src/builder/init_world.py | 59 --------------------------------------- 1 file changed, 59 deletions(-) delete mode 100644 src/builder/init_world.py diff --git a/src/builder/init_world.py b/src/builder/init_world.py deleted file mode 100644 index 93491c3..0000000 --- a/src/builder/init_world.py +++ /dev/null @@ -1,59 +0,0 @@ -from pathlib import Path - -import toml - -root_dir: Path = Path("worlds") - -world_name = input("Select a name for your world: ") -world_dir: Path = root_dir / world_name - -if world_dir.exists(): - print("A world with that name already exists.") - exit() - -# create folder for new world -world_dir.mkdir() - -# create world.toml file -world_toml_path: Path = world_dir / "world.toml" -world_toml_path.touch() - -# create readme file -readme_file: Path = world_dir / "README.md" -readme_file.touch() -readme_file.write_text(f"# {world_name}\n", encoding="UTF-8") - -# create areas folder -area_dir: Path = world_dir / "areas" -area_dir.mkdir() - -word_toml = { - "name": world_name, - "language": "en", - "areas": [], -} - -# ask for areas -while True: - area_name: str = input("Select a name for the next area: ") - - if not area_name: - break - - area_path: Path = area_dir / area_name - if area_path.exists(): - print("An Area with that name already exists.") - continue - - # ask for area description - area_description: str = input("Give a description for that area: ") - - area_toml = {"name": area_name, "description": area_description} - with area_path.open("w", encoding="UTF-8") as stream: - toml.dump(area_toml, stream) - - word_toml["areas"].append(area_name) - -# dump world toml -with world_toml_path.open("w", encoding="UTF-8") as stream: - toml.dump(word_toml, stream) From 6c57740b2c30a5b77ff8d66d8ef0d7596b724d5e Mon Sep 17 00:00:00 2001 From: dodo Date: Mon, 6 Jan 2025 12:59:21 +0100 Subject: [PATCH 21/37] world directory name will be sanitized --- src/fantasy_forge/folder_structure.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/fantasy_forge/folder_structure.py b/src/fantasy_forge/folder_structure.py index d179e01..3222379 100644 --- a/src/fantasy_forge/folder_structure.py +++ b/src/fantasy_forge/folder_structure.py @@ -12,8 +12,7 @@ from fantasy_forge.inventory import Inventory from fantasy_forge.item import Item from fantasy_forge.key import Key -from fantasy_forge.player import Player -from fantasy_forge.utils import WORLDS_FOLDER +from fantasy_forge.utils import WORLDS_FOLDER, clean_filename from fantasy_forge.weapon import Weapon logger = logging.getLogger(__name__) @@ -65,8 +64,9 @@ def init_nested_folder_structure(world_name: str): path = asset2path(world_name, asset_type) path.mkdir(parents=True, exist_ok=True) + def asset2path(world_name: str, asset_type: ASSET_TYPE) -> Path: - world_path = WORLDS_FOLDER / world_name + world_path = WORLDS_FOLDER / clean_filename(world_name) current: ASSET_TYPE = asset_type type_hierarchy: list[ASSET_TYPE] = [current] @@ -78,4 +78,4 @@ def asset2path(world_name: str, asset_type: ASSET_TYPE) -> Path: type_hierarchy.insert(0, current) path_str: str = "/".join((t.__name__ for t in type_hierarchy)) path: Path = world_path / path_str - return path \ No newline at end of file + return path From 46e1c474ed808301a4f5b0cdc5fe739c5ef268ff Mon Sep 17 00:00:00 2001 From: dodo Date: Mon, 6 Jan 2025 13:16:22 +0100 Subject: [PATCH 22/37] started working on builder shell --- src/builder/builder.py | 87 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 84 insertions(+), 3 deletions(-) diff --git a/src/builder/builder.py b/src/builder/builder.py index b729a9f..e95415f 100644 --- a/src/builder/builder.py +++ b/src/builder/builder.py @@ -1,13 +1,19 @@ """Generates toml files for new world.""" +import cmd import logging -from cmd import Cmd from pathlib import Path import questionary +from add_asset import get_asset_data from fluent.runtime import FluentLocalization -from fantasy_forge.folder_structure import init_nested_folder_structure +from fantasy_forge.area import Area +from fantasy_forge.folder_structure import ( + ASSET_TYPE, + ASSET_TYPE_DICT, + init_nested_folder_structure, +) from fantasy_forge.localization import get_fluent_locale from fantasy_forge.utils import LOCALE_FOLDER, WORLDS_FOLDER, clean_filename from fantasy_forge.world import World @@ -15,8 +21,70 @@ logger = logging.getLogger(__name__) +class Builder(cmd.Cmd): + world: World + world_dir: Path + + def preloop(self): + select = questionary.select( + "What do you want to do?", + choices=["Create a new world?", "Edit an existing world"], + ).ask() + if select == "Create a new world?": + world = new_world() + elif select == "Edit an existing world": + world = select_world() + else: + exit(1) + self.world = world + self.world_dir = WORLDS_FOLDER / clean_filename(world.name) + super().preloop() + + def precmd(self, line): + line = line.strip() + line = line.casefold() + return line + + def do_new(self, line): + """Creates a new element.""" + match line: + case "world": + self.do_save() + world = new_world() + self.world = world + self.world_dir = WORLDS_FOLDER / clean_filename(world.name) + case "area": + config_dict = get_asset_data(Area) + area = Area(config_dict, self.world.l10n) + area_name = area.name + self.world.areas[area_name] = area + case _: + asset_type: ASSET_TYPE = select_asset_type() + config_dict: dict = get_asset_data(asset_type) + asset = asset_type(config_dict, self.world.l10n) + self.world.assets[asset_type.__name__].append(asset) + + def do_edit(self): + """Edits an existing element.""" + pass + + def do_list(self): + """Lists all the elements.""" + pass + + def do_save(self, line): + """Save the current world to filesystem.""" + # save all assets in world + # save world.toml + pass + + def do_status(self, line: str): + print(f"current world: {self.world}") + print(f"current world dir: {self.world_dir}") + + def new_world() -> World: - name = questionary.select("Which world do ou choose? ", choices=world_list).ask() + name = questionary.text("Choose a name for your new world: ").ask() world_dir: Path = WORLDS_FOLDER / clean_filename(name) # choose locale @@ -46,3 +114,16 @@ def select_world() -> World: name = questionary.select("Which world do ou choose? ", choices=world_list).ask() world = World.load(name) return world + + +def select_asset_type() -> ASSET_TYPE: + asset_type_inp: str = questionary.select( + "Asset type: ", choices=list(ASSET_TYPE_DICT.keys()), default="Entity" + ).ask() + asset_type: ASSET_TYPE = ASSET_TYPE_DICT[asset_type_inp] + return asset_type + + +if __name__ == "__main__": + builder = Builder() + builder.cmdloop() From bdf7c6ba19c918fb76640450b144baaf400cde14 Mon Sep 17 00:00:00 2001 From: dodo Date: Mon, 6 Jan 2025 13:17:00 +0100 Subject: [PATCH 23/37] removes obsolete function --- src/builder/add_asset.py | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/src/builder/add_asset.py b/src/builder/add_asset.py index 81213ec..c9c798c 100644 --- a/src/builder/add_asset.py +++ b/src/builder/add_asset.py @@ -10,16 +10,6 @@ from fantasy_forge.utils import WORLDS_FOLDER, clean_filename -def bool_from_str(str_data: str) -> bool: - match str_data.casefold(): - case "true" | "y": - return True - case "false" | "n": - return False - case _: - return False - - def get_asset_data(asset_type: ASSET_TYPE) -> dict: config_dict: dict = {} attr_name: str From 5c9fcffdcaf0f09d85dc0e0b87c0232154097a00 Mon Sep 17 00:00:00 2001 From: dodo Date: Mon, 6 Jan 2025 13:31:17 +0100 Subject: [PATCH 24/37] moves function --- src/builder/add_asset.py | 20 +------------------- src/builder/builder.py | 20 +++++++++++++++++++- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/src/builder/add_asset.py b/src/builder/add_asset.py index c9c798c..38abe0d 100644 --- a/src/builder/add_asset.py +++ b/src/builder/add_asset.py @@ -8,25 +8,7 @@ asset2path, ) from fantasy_forge.utils import WORLDS_FOLDER, clean_filename - - -def get_asset_data(asset_type: ASSET_TYPE) -> dict: - config_dict: dict = {} - attr_name: str - attr_type: type - for attr_name, attr_type in asset_type.__attributes__.items(): - prompt = f"{attr_name}: " - match attr_type.__name__: - case "bool": - data = questionary.confirm(prompt).ask() - case "int": - raw = questionary.text(prompt).ask() - assert raw.isdigit() - data = int(raw) - case _: - data = questionary.text(prompt).ask() - config_dict[attr_name] = data - return config_dict +from builder import get_asset_data def main(): diff --git a/src/builder/builder.py b/src/builder/builder.py index e95415f..0a97e1c 100644 --- a/src/builder/builder.py +++ b/src/builder/builder.py @@ -5,7 +5,6 @@ from pathlib import Path import questionary -from add_asset import get_asset_data from fluent.runtime import FluentLocalization from fantasy_forge.area import Area @@ -109,6 +108,25 @@ def new_world() -> World: return world +def get_asset_data(asset_type: ASSET_TYPE) -> dict: + config_dict: dict = {} + attr_name: str + attr_type: type + for attr_name, attr_type in asset_type.__attributes__.items(): + prompt = f"{attr_name}: " + match attr_type.__name__: + case "bool": + data = questionary.confirm(prompt).ask() + case "int": + raw = questionary.text(prompt).ask() + assert raw.isdigit() + data = int(raw) + case _: + data = questionary.text(prompt).ask() + config_dict[attr_name] = data + return config_dict + + def select_world() -> World: world_list = [world.name for world in WORLDS_FOLDER.iterdir()] name = questionary.select("Which world do ou choose? ", choices=world_list).ask() From 2ff6ed53ed8aeb560451af425df1e7c23091f716 Mon Sep 17 00:00:00 2001 From: dodo Date: Mon, 6 Jan 2025 13:38:04 +0100 Subject: [PATCH 25/37] adds list command --- src/builder/builder.py | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/src/builder/builder.py b/src/builder/builder.py index 0a97e1c..f984063 100644 --- a/src/builder/builder.py +++ b/src/builder/builder.py @@ -67,9 +67,24 @@ def do_edit(self): """Edits an existing element.""" pass - def do_list(self): - """Lists all the elements.""" - pass + def do_list(self, line: str): + """Lists all the elements of a kind.""" + match line: + case "world": + for world_dir in WORLDS_FOLDER.iterdir(): + print(world_dir) + case "area": + for area_name, area in self.world.areas.items(): + print(area_name, repr(area)) + case _: + asset_type: ASSET_TYPE + if line.title() in ASSET_TYPE_DICT: + asset_type = ASSET_TYPE_DICT[line.title()] + else: + asset_type = select_asset_type() + for asset in self.world.assets[asset_type.__name__]: + print(asset.name, repr(asset)) + def do_save(self, line): """Save the current world to filesystem.""" From 3a5895577610ad848a9214cae95a19751f16d13c Mon Sep 17 00:00:00 2001 From: dodo Date: Mon, 6 Jan 2025 13:43:02 +0100 Subject: [PATCH 26/37] adds option to show all assets --- src/builder/builder.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/builder/builder.py b/src/builder/builder.py index f984063..cb46ceb 100644 --- a/src/builder/builder.py +++ b/src/builder/builder.py @@ -76,6 +76,10 @@ def do_list(self, line: str): case "area": for area_name, area in self.world.areas.items(): print(area_name, repr(area)) + case "all" | "": + # list all assets + for asset in self.world.iter_assets(): + print(repr(asset)) case _: asset_type: ASSET_TYPE if line.title() in ASSET_TYPE_DICT: @@ -83,7 +87,7 @@ def do_list(self, line: str): else: asset_type = select_asset_type() for asset in self.world.assets[asset_type.__name__]: - print(asset.name, repr(asset)) + print(repr(asset)) def do_save(self, line): From 0485a6cb1ee8655bdf38872ba7d9eba6b096f60f Mon Sep 17 00:00:00 2001 From: dodo Date: Mon, 6 Jan 2025 13:46:49 +0100 Subject: [PATCH 27/37] adds properties for world_dir and world_name --- src/builder/builder.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/builder/builder.py b/src/builder/builder.py index cb46ceb..2a0916b 100644 --- a/src/builder/builder.py +++ b/src/builder/builder.py @@ -22,7 +22,14 @@ class Builder(cmd.Cmd): world: World - world_dir: Path + + @property + def world_name(self) -> str: + return self.world.name + + @property + def world_dir(self) -> Path: + return WORLDS_FOLDER / clean_filename(self.world_name) def preloop(self): select = questionary.select( @@ -36,7 +43,6 @@ def preloop(self): else: exit(1) self.world = world - self.world_dir = WORLDS_FOLDER / clean_filename(world.name) super().preloop() def precmd(self, line): @@ -51,7 +57,6 @@ def do_new(self, line): self.do_save() world = new_world() self.world = world - self.world_dir = WORLDS_FOLDER / clean_filename(world.name) case "area": config_dict = get_asset_data(Area) area = Area(config_dict, self.world.l10n) From 0f2e41e9c2c9bed14cac6bd9930771ae8958b46e Mon Sep 17 00:00:00 2001 From: dodo Date: Mon, 6 Jan 2025 13:47:23 +0100 Subject: [PATCH 28/37] renames Builder class --- src/builder/builder.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/builder/builder.py b/src/builder/builder.py index 2a0916b..1dbb78c 100644 --- a/src/builder/builder.py +++ b/src/builder/builder.py @@ -20,7 +20,7 @@ logger = logging.getLogger(__name__) -class Builder(cmd.Cmd): +class BuilderShell(cmd.Cmd): world: World @property @@ -167,5 +167,5 @@ def select_asset_type() -> ASSET_TYPE: if __name__ == "__main__": - builder = Builder() + builder = BuilderShell() builder.cmdloop() From e2531ab454f9300430305302562115c3170c82ee Mon Sep 17 00:00:00 2001 From: dodo Date: Mon, 6 Jan 2025 13:59:16 +0100 Subject: [PATCH 29/37] refactors new command --- src/builder/builder.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/builder/builder.py b/src/builder/builder.py index 1dbb78c..70ea705 100644 --- a/src/builder/builder.py +++ b/src/builder/builder.py @@ -58,12 +58,18 @@ def do_new(self, line): world = new_world() self.world = world case "area": + print("Let's create a new area.") config_dict = get_asset_data(Area) area = Area(config_dict, self.world.l10n) area_name = area.name self.world.areas[area_name] = area case _: - asset_type: ASSET_TYPE = select_asset_type() + asset_type: ASSET_TYPE + if line.title() in ASSET_TYPE_DICT: + asset_type = ASSET_TYPE_DICT[line.title()] + else: + asset_type = select_asset_type() + print(f"Let's create a new {asset_type.__name__}.") config_dict: dict = get_asset_data(asset_type) asset = asset_type(config_dict, self.world.l10n) self.world.assets[asset_type.__name__].append(asset) @@ -94,7 +100,6 @@ def do_list(self, line: str): for asset in self.world.assets[asset_type.__name__]: print(repr(asset)) - def do_save(self, line): """Save the current world to filesystem.""" # save all assets in world From e5e0280de74400dc088988cdf8c3458bbfa2f7b4 Mon Sep 17 00:00:00 2001 From: dodo Date: Mon, 6 Jan 2025 14:11:17 +0100 Subject: [PATCH 30/37] adds spawn command --- src/builder/builder.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/builder/builder.py b/src/builder/builder.py index 70ea705..6eb74fa 100644 --- a/src/builder/builder.py +++ b/src/builder/builder.py @@ -110,6 +110,16 @@ def do_status(self, line: str): print(f"current world: {self.world}") print(f"current world dir: {self.world_dir}") + def do_spawn(self, line: str): + """Prints or selects the spawn area of the current world.""" + if line: + # set spawn area + area_name = questionary.select("Choose a spawn area", choices=list(self.world.areas.keys())).ask() + self.world.spawn = area_name + else: + # print spawn + print(f"current spawn: {self.world.spawn}") + def new_world() -> World: name = questionary.text("Choose a name for your new world: ").ask() From accbe143676deb736979f14dfccf4c6a8fdcdfc4 Mon Sep 17 00:00:00 2001 From: dodo Date: Mon, 6 Jan 2025 14:27:40 +0100 Subject: [PATCH 31/37] minor refactoring --- src/builder/builder.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/builder/builder.py b/src/builder/builder.py index 6eb74fa..f96609d 100644 --- a/src/builder/builder.py +++ b/src/builder/builder.py @@ -34,9 +34,9 @@ def world_dir(self) -> Path: def preloop(self): select = questionary.select( "What do you want to do?", - choices=["Create a new world?", "Edit an existing world"], + choices=["Create a new world", "Edit an existing world"], ).ask() - if select == "Create a new world?": + if select == "Create a new world": world = new_world() elif select == "Edit an existing world": world = select_world() @@ -55,6 +55,7 @@ def do_new(self, line): match line: case "world": self.do_save() + print("Let's create a new area.") world = new_world() self.world = world case "area": @@ -82,12 +83,15 @@ def do_list(self, line: str): """Lists all the elements of a kind.""" match line: case "world": + print("Let's list all worlds.") for world_dir in WORLDS_FOLDER.iterdir(): print(world_dir) case "area": + print("Let's list all areas.") for area_name, area in self.world.areas.items(): print(area_name, repr(area)) case "all" | "": + print("Let's list all assets.") # list all assets for asset in self.world.iter_assets(): print(repr(asset)) @@ -97,6 +101,7 @@ def do_list(self, line: str): asset_type = ASSET_TYPE_DICT[line.title()] else: asset_type = select_asset_type() + print(f"Let's list all assets of type {asset_type.__name__}") for asset in self.world.assets[asset_type.__name__]: print(repr(asset)) @@ -114,7 +119,9 @@ def do_spawn(self, line: str): """Prints or selects the spawn area of the current world.""" if line: # set spawn area - area_name = questionary.select("Choose a spawn area", choices=list(self.world.areas.keys())).ask() + area_name = questionary.select( + "Choose a spawn area", choices=list(self.world.areas.keys()) + ).ask() self.world.spawn = area_name else: # print spawn From 7b0aeaf94ec588e782792f187081d2a04ea3506b Mon Sep 17 00:00:00 2001 From: dodo Date: Mon, 6 Jan 2025 14:56:50 +0100 Subject: [PATCH 32/37] adds save asset function --- src/builder/builder.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/builder/builder.py b/src/builder/builder.py index f96609d..898de38 100644 --- a/src/builder/builder.py +++ b/src/builder/builder.py @@ -5,12 +5,14 @@ from pathlib import Path import questionary +import toml from fluent.runtime import FluentLocalization from fantasy_forge.area import Area from fantasy_forge.folder_structure import ( ASSET_TYPE, ASSET_TYPE_DICT, + asset2path, init_nested_folder_structure, ) from fantasy_forge.localization import get_fluent_locale @@ -107,8 +109,9 @@ def do_list(self, line: str): def do_save(self, line): """Save the current world to filesystem.""" - # save all assets in world - # save world.toml + for asset in self.world.iter_assets(): + save_asset(self.world, asset) + # TODO: save world.toml pass def do_status(self, line: str): @@ -188,6 +191,14 @@ def select_asset_type() -> ASSET_TYPE: return asset_type +def save_asset(world: World, asset: ASSET_TYPE): + asset_path = asset2path(world.name, asset) / clean_filename(asset.name) + asset_data = asset.to_dict() + content = toml.dumps(asset_data) + with asset_path.open("w") as file: + file.write(content) + + if __name__ == "__main__": builder = BuilderShell() builder.cmdloop() From 685f3eedc8b211142ce3200e58d8449a9b46ed31 Mon Sep 17 00:00:00 2001 From: dodo Date: Mon, 6 Jan 2025 15:38:33 +0100 Subject: [PATCH 33/37] adds populate area method --- src/builder/builder.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/builder/builder.py b/src/builder/builder.py index 898de38..82acae8 100644 --- a/src/builder/builder.py +++ b/src/builder/builder.py @@ -130,6 +130,16 @@ def do_spawn(self, line: str): # print spawn print(f"current spawn: {self.world.spawn}") + def _populate_area(self, area: Area): + """Adds assets from world into an area.""" + assets_to_add = questionary.checkbox( + "Choose the assets", + choices=[str(asset) for asset in self.world.iter_assets()], + ).ask() + for asset_name in assets_to_add: + asset = self.world.get_asset(asset_name) + area.contents[asset_name] = asset + def new_world() -> World: name = questionary.text("Choose a name for your new world: ").ask() From ebc5d43e940a9e27f42e7987c7168bae01917789 Mon Sep 17 00:00:00 2001 From: dodo Date: Mon, 6 Jan 2025 16:22:10 +0100 Subject: [PATCH 34/37] introduces World.store the successor of World.assets --- src/fantasy_forge/world.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/fantasy_forge/world.py b/src/fantasy_forge/world.py index 9722f04..cc7854f 100644 --- a/src/fantasy_forge/world.py +++ b/src/fantasy_forge/world.py @@ -24,6 +24,7 @@ class World: areas: dict[str, Area] spawn: str # area name to spawn in assets: dict[str, list[ASSET_TYPE]] # store of all loaded assets + store: dict[str, ASSET_TYPE] # stores all assets def __init__( self: Self, @@ -37,9 +38,12 @@ def __init__( self.areas = areas self.spawn = spawn + self.store = dict() + self.assets = defaultdict(list) self._load_assets() + # populate areas dict area: Area for area in self.filter(Area): @@ -114,6 +118,27 @@ def _load_assets(self): self.assets[asset_type.__name__].append(asset) + assert asset.name not in self.store + self.store[asset.name] = asset + + def __iter__(self) -> Iterator[ASSET_TYPE]: + yield from self.store.values() + + def __getitem__(self, asset_key: str) -> ASSET_TYPE | None: + return self.store.get(asset_key) + + def add_asset(self, asset: ASSET_TYPE) -> None: + assert asset.name not in self.store + self.store[asset.name] = asset + + def pop_asset(self, asset_key: str) -> ASSET_TYPE | None: + if asset_key in self.store: + asset: ASSET_TYPE = self.store.pop(asset_key) + return asset + + def filter(self, wanted_type: type) -> Iterator[ASSET_TYPE]: + yield from (asset for asset in self if isinstance(asset, wanted_type)) + def iter_assets(self) -> Iterator[ASSET_TYPE]: for assets in self.assets.values(): yield from assets From 7bfe0b114b804dfc3a7b5ad513413073efae2e6c Mon Sep 17 00:00:00 2001 From: dodo Date: Mon, 6 Jan 2025 16:24:10 +0100 Subject: [PATCH 35/37] removes World.assets --- src/fantasy_forge/world.py | 20 -------------------- 1 file changed, 20 deletions(-) diff --git a/src/fantasy_forge/world.py b/src/fantasy_forge/world.py index cc7854f..1dc1586 100644 --- a/src/fantasy_forge/world.py +++ b/src/fantasy_forge/world.py @@ -1,7 +1,6 @@ from __future__ import annotations import logging -from collections import defaultdict from pathlib import Path from typing import IO, TYPE_CHECKING, Iterator, Self @@ -23,7 +22,6 @@ class World: name: str areas: dict[str, Area] spawn: str # area name to spawn in - assets: dict[str, list[ASSET_TYPE]] # store of all loaded assets store: dict[str, ASSET_TYPE] # stores all assets def __init__( @@ -39,8 +37,6 @@ def __init__( self.spawn = spawn self.store = dict() - - self.assets = defaultdict(list) self._load_assets() @@ -116,8 +112,6 @@ def _load_assets(self): logger.info("skipped %s", toml_path.name) continue - self.assets[asset_type.__name__].append(asset) - assert asset.name not in self.store self.store[asset.name] = asset @@ -139,20 +133,6 @@ def pop_asset(self, asset_key: str) -> ASSET_TYPE | None: def filter(self, wanted_type: type) -> Iterator[ASSET_TYPE]: yield from (asset for asset in self if isinstance(asset, wanted_type)) - def iter_assets(self) -> Iterator[ASSET_TYPE]: - for assets in self.assets.values(): - yield from assets - - def get_asset(self, asset_name: str, asset_type: str = "") -> ASSET_TYPE: - if asset_type: - assets = self.assets[asset_type] - else: - assets = self.iter_assets() - - for asset in assets: - if asset.__name__ == asset_name: - return asset - if TYPE_CHECKING: from fluent.runtime import FluentLocalization From 517dd212ec90d6e9bd78c5f9424deae222fe5722 Mon Sep 17 00:00:00 2001 From: dodo Date: Mon, 6 Jan 2025 16:27:10 +0100 Subject: [PATCH 36/37] adds World.__contains__ --- src/fantasy_forge/world.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/fantasy_forge/world.py b/src/fantasy_forge/world.py index 1dc1586..6116de6 100644 --- a/src/fantasy_forge/world.py +++ b/src/fantasy_forge/world.py @@ -118,6 +118,9 @@ def _load_assets(self): def __iter__(self) -> Iterator[ASSET_TYPE]: yield from self.store.values() + def __contains__(self, asset_key: str): + return asset_key in self.store + def __getitem__(self, asset_key: str) -> ASSET_TYPE | None: return self.store.get(asset_key) From 1d7386e73307fe3919f347cebe5a5cd368615189 Mon Sep 17 00:00:00 2001 From: dodo Date: Mon, 6 Jan 2025 16:36:47 +0100 Subject: [PATCH 37/37] enables the new World.store --- src/builder/builder.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/builder/builder.py b/src/builder/builder.py index 82acae8..827ee04 100644 --- a/src/builder/builder.py +++ b/src/builder/builder.py @@ -75,7 +75,7 @@ def do_new(self, line): print(f"Let's create a new {asset_type.__name__}.") config_dict: dict = get_asset_data(asset_type) asset = asset_type(config_dict, self.world.l10n) - self.world.assets[asset_type.__name__].append(asset) + self.world.add_asset(asset) def do_edit(self): """Edits an existing element.""" @@ -95,7 +95,7 @@ def do_list(self, line: str): case "all" | "": print("Let's list all assets.") # list all assets - for asset in self.world.iter_assets(): + for asset in self.world: print(repr(asset)) case _: asset_type: ASSET_TYPE @@ -104,12 +104,12 @@ def do_list(self, line: str): else: asset_type = select_asset_type() print(f"Let's list all assets of type {asset_type.__name__}") - for asset in self.world.assets[asset_type.__name__]: + for asset in self.world.filter(asset_type): print(repr(asset)) def do_save(self, line): """Save the current world to filesystem.""" - for asset in self.world.iter_assets(): + for asset in self.world: save_asset(self.world, asset) # TODO: save world.toml pass @@ -134,10 +134,10 @@ def _populate_area(self, area: Area): """Adds assets from world into an area.""" assets_to_add = questionary.checkbox( "Choose the assets", - choices=[str(asset) for asset in self.world.iter_assets()], + choices=list(self.world.store.keys()), ).ask() for asset_name in assets_to_add: - asset = self.world.get_asset(asset_name) + asset = self.world[asset_name] area.contents[asset_name] = asset