Read world config from TOML instead of hardcoding

This commit is contained in:
Jared Miller 2026-02-07 16:14:03 -05:00
parent 0f05302b6e
commit bea2a73c98
Signed by: shmup
GPG key ID: 22B5C6D66A38B06C
2 changed files with 37 additions and 2 deletions

View file

@ -4,6 +4,7 @@ import asyncio
import logging
import pathlib
import time
import tomllib
from typing import cast
import telnetlib3
@ -25,6 +26,14 @@ PORT = 6789
_world: World | None = None
def load_world_config(world_name: str = "earth") -> dict:
"""Load world configuration from TOML file."""
worlds_dir = pathlib.Path(__file__).resolve().parents[2] / "worlds"
config_path = worlds_dir / world_name / "config.toml"
with open(config_path, "rb") as f:
return tomllib.load(f)
def find_passable_start(world: World, start_x: int, start_y: int) -> tuple[int, int]:
"""Find a passable tile starting from (start_x, start_y) and searching outward.
@ -139,9 +148,21 @@ async def run_server() -> None:
# Generate world once at startup (cached to build/ after first run)
cache_dir = pathlib.Path(__file__).resolve().parents[2] / "build"
log.info("loading world (seed=42, 1000x1000)...")
config = load_world_config()
world_cfg = config["world"]
log.info(
"loading world (seed=%d, %dx%d)...",
world_cfg["seed"],
world_cfg["width"],
world_cfg["height"],
)
t0 = time.monotonic()
_world = World(seed=42, width=1000, height=1000, cache_dir=cache_dir)
_world = World(
seed=world_cfg["seed"],
width=world_cfg["width"],
height=world_cfg["height"],
cache_dir=cache_dir,
)
elapsed = time.monotonic() - t0
if _world.cached:
log.info("world loaded from cache in %.2fs", elapsed)

View file

@ -89,3 +89,17 @@ async def test_shell_handles_quit():
calls = [str(call) for call in writer.write.call_args_list]
assert any("Goodbye" in call for call in calls)
writer.close.assert_called()
def test_load_world_config():
"""Config loader returns expected values from worlds/earth/config.toml."""
config = server.load_world_config()
assert config["world"]["seed"] == 42
assert config["world"]["width"] == 1000
assert config["world"]["height"] == 1000
def test_load_world_config_missing():
"""Config loader raises FileNotFoundError for nonexistent world."""
with pytest.raises(FileNotFoundError):
server.load_world_config("nonexistent")