diff --git a/app.py b/app.py index deb22f5..bf174cd 100644 --- a/app.py +++ b/app.py @@ -152,6 +152,8 @@ def player_view(world: dict, player: dict, now: float) -> dict: view["recon_gain"] = {action["id"]: game.recon_gain(world, player, action) for action in game.ACTIONS if action.get("special") == "recon"} level = game.skill_level(player, "firekeeping") + view["region_yield"] = {action["id"]: round(game.region_yield(world, action) - 1, 3) for action in game.ACTIONS + if game.region_yield(world, action) > 1} view["firekeeping"] = {"minutes": game.fire_minutes(level), "bank": game.fire_bank(level)} # Inputs as the fires leave them: a lit fire pays the log. view["fuelled"] = {action["id"]: game.fire_inputs(world, action) for action in game.ACTIONS if action.get("fire")} @@ -201,8 +203,9 @@ def roster(world: dict, now: float) -> list[dict]: people = [] for player in world["players"].values(): action = game.ACTION_BY_ID[player["action"]["id"]] if player["action"] else None - game.regen(world, player, now) + game.regen(game.here(world, player), player, now) people.append({ + "at": player["at"], "travel": player["travel"] and player["travel"]["to"], "xp": player["xp"], "equip": player["equip"], "joined": player["joined"], "hp": int(player["hp"]), "max_hp": game.max_hp(player), "power": game.combat_power(player), "fighter": {key: value for key, value in game.fighter(player, game.blessing(player), {}).items() @@ -226,6 +229,9 @@ def roster(world: dict, now: float) -> list[dict]: return sorted(people, key=lambda p: -p["donated"]) +ROAD_ROUTES = ("/api/seen", "/api/pin", "/api/track", "/api/board", "/api/board/delete", "/api/charter/sign", "/api/charter/cancel") # what you can still do on the road + + class Handler(BaseHTTPRequestHandler): server_version = "Guildhall" store: Store @@ -303,9 +309,9 @@ class Handler(BaseHTTPRequestHandler): game.catch_up(world, now, self.store.rng) if player: summary = game.take_summary(player, game.empty_summary()) - game.regen(world, player, now) + game.regen(game.here(world, player), player, now) player["last_active"] = now - game.watch_fight(world, player, now) # looking at it: your manual abilities hold + game.watch_fight(game.here(world, player), player, now) # looking at it: your manual abilities hold self.store.save() self.send_json(self.state(uid, summary)) elif path.startswith("/api/"): @@ -335,9 +341,9 @@ class Handler(BaseHTTPRequestHandler): else: game.catch_up(world, now, self.store.rng) # everyone, so the fires are as they really are summary = game.take_summary(player, game.empty_summary()) - game.regen(world, player, now) + game.regen(game.here(world, player), player, now) player["last_active"] = now - game.watch_fight(world, player, now) + game.watch_fight(game.here(world, player), player, now) error = self.player_route(path, player, body, now) if error is None: game.process_player(world, player, now, self.store.rng) # a new fight is drawn up at once @@ -352,7 +358,18 @@ class Handler(BaseHTTPRequestHandler): self.send_json(self.state(uid)) def player_route(self, path: str, player: dict, body: dict, now: float) -> str | None: - world = self.store.world + world = game.here(self.store.world, player) + if player["travel"] and path not in ROAD_ROUTES: + return "You're on the road" + if path == "/api/travel": + pouch = body.get("pouch") + return game.travel(world, player, str(body.get("to")), pouch if isinstance(pouch, dict) else {}, now) + if path == "/api/charter": + return game.propose_charter(world, player, body.get("name"), body.get("region"), now) + if path == "/api/charter/sign": + return game.sign_charter(world, player, now) + if path == "/api/charter/cancel": + return game.cancel_charter(world, player) item = body.get("item") qty = body.get("qty") if path in ("/api/donate", "/api/sell", "/api/give"): @@ -453,11 +470,7 @@ class Handler(BaseHTTPRequestHandler): if path == "/api/install": return game.install(world, player, str(body.get("fitting")), str(body.get("source")), now) if path == "/api/garrison": - raid = game.upcoming_raid(world) - if body.get("join") and not raid: - return "There's no raid to stand guard for" - player["garrison"] = bool(body.get("join")) - return None + return game.stand_guard(world, player, bool(body.get("join")), now) if path == "/api/board/delete": message = next((m for m in world["board"] if m.get("id") == body.get("id")), None) if not message: @@ -621,6 +634,8 @@ class Handler(BaseHTTPRequestHandler): world = self.store.world now = self.store.now() player = world["players"].get(uid) + if player: + world = game.here(world, player) upcoming = game.upcoming_event(world) unseen = game.unseen_threat(world, player) if player else None # Newest first by when it happened: raids are announced long before they land. @@ -639,6 +654,8 @@ class Handler(BaseHTTPRequestHandler): "happenings": game.happenings_view(world, now), "history": history, "orders": world["orders"], + "kingdom": game.kingdom_view(world, now), + "city_speed": game.speed(world), "threat_report": unseen and {"id": unseen["id"], "kind": unseen["kind"], "at": unseen["resolved"], "report": unseen["report"]}, "players": roster(world, now), diff --git a/game.py b/game.py index 96f4ea1..3925403 100644 --- a/game.py +++ b/game.py @@ -1684,9 +1684,25 @@ RAID_TRAITS = ["lightly armoured, heavy on archers", "mounted and fast, few bows # --- world --------------------------------------------------------------- -WORLD_VERSION = 39 +WORLD_VERSION = 40 HOME_CITY = "guildhall" -CITY_KEYS = ("events", "next_event_at", "next_minor_at", "next_hardship_at", "next_fortune_at", "caravan") +CITY_KEYS = ("events", "next_event_at", "next_minor_at", "next_hardship_at", "next_fortune_at", "caravan", "orders") +TRAVEL_TIME = 12 * 60 # game seconds on the road between two towns +POUCH_SLOTS = 6 # kinds of item you can carry on the road... +POUCH_STACK = 100 # ...and how many of each +# Where a town stands: one town to a region, between them every gathering trade. Each trip out brings +# back more, most of all of the commonest stuff, and more as the town grows. XP stays the same. +REGIONS = { + "mountains": {"name": "Mountains", "icon": "⛰️", "skills": ["mining"]}, + "forest": {"name": "Forest", "icon": "🌲", "skills": ["woodcutting", "hunting"]}, + "coast": {"name": "Coast", "icon": "🌊", "skills": ["fishing"]}, + "plains": {"name": "Plains", "icon": "🌾", "skills": ["farming"]}, +} +REGION_YIELD = [1.0, 0.75, 0.5, 0.3, 0.2, 0.1] # more per trip at each material tier, for a full city +TOWN_SCALE = [0.5, 0.7, 0.85, 1.0] # how much of that a hamlet, village, town and city get +MAX_CITIES = 1 + len(REGIONS) +FOUNDING = {"settlers": 20, "gold": 5000, "provisions": 200} # what a new town takes from the one it leaves +FOUNDING_GRACE = 24 # game hours a new town gets before its first threat lands class World(MutableMapping): @@ -1733,13 +1749,14 @@ def _nested(doc: dict) -> World: return World(doc) -def new_world(now: float, speed: float = 1.0) -> World: - return _nested({ - "version": WORLD_VERSION, - "created": now, - "config": {"speed": speed, "clock_offset": 0}, - "players": {}, - "city": { +def here(world: World, player: dict) -> World: + """The world as the player's own town sees it.""" + return world.at(player["at"]) + + +def _new_city(now: float, speed: float, name: str) -> dict: + return { + "name": name, "founded": now, "population": 20.0, "treasury": 0.0, "stockpile": {"bread": 40}, @@ -1756,19 +1773,31 @@ def new_world(now: float, speed: float = 1.0) -> World: "fires": {key: new_fire(now) for key in FIRES}, "wages": 0, "monuments": {}, "built": [], "carving": None, "happiness": 0.5, "clothes_due": 0.0, "unheated": False, - }, - "events": [], - "next_event_at": now + 12 * HOUR / speed, - "next_minor_at": now + 30 * HOUR / speed, - "next_hardship_at": now + 24 * HOUR / speed, - "next_fortune_at": now + 6 * HOUR / speed, + "events": [], + "next_event_at": now + 12 * HOUR / speed, + "next_minor_at": now + 30 * HOUR / speed, + "next_hardship_at": now + 24 * HOUR / speed, + "next_fortune_at": now + 6 * HOUR / speed, + "caravan": None, + "orders": [], + } + + +def new_world(now: float, speed: float = 1.0) -> World: + return World({ + "version": WORLD_VERSION, + "created": now, + "config": {"speed": speed, "clock_offset": 0}, + "players": {}, + "cities": {HOME_CITY: _new_city(now, speed, "Guildhall")}, + "charter": None, "next_event_id": 1, "ledger": [], "board": [], "next_message_id": 1, - "orders": [], "next_order_id": 1, + "next_order_id": 1, "parties": {}, "next_party_id": 1, - "caravan": None, "next_caravan_id": 1, + "next_caravan_id": 1, }) @@ -2012,7 +2041,23 @@ def migrate(world: dict, now: float | None = None) -> World: world["version"] = 38 if world["version"] < 39: world["version"] = 39 - return world if isinstance(world, World) else _nested(world) + if not isinstance(world, World): + world = _nested(world) + if world["version"] < 40: + # Towns: everyone stands somewhere, with a bank there. Work orders belong to their town. + city = world["city"] + if "orders" in world.doc: + city["orders"] = world.doc.pop("orders") + city.setdefault("name", "Guildhall") + city.setdefault("founded", world["created"]) + for player in world["players"].values(): + player.update(at=world.here, banks={}, travel=None) + world.doc.setdefault("charter", None) + # Banks can be looted from the raid after the one already on its way. + raid = upcoming_raid(world) + world["bank_risk_after"] = raid.get("slot", 0) if raid else 0 + world["version"] = 40 + return world def _planks_to_frames(world: dict) -> None: @@ -2114,7 +2159,7 @@ def last_threat(world: dict) -> dict | None: def unseen_threat(world: dict, player: dict) -> dict | None: """The latest raid or dragon attack this player hasn't watched yet, if it happened while they were here.""" event = last_threat(world) - if event and event["id"] > player.get("seen_threat", 0) and event["resolved"] >= player["joined"]: + if event and event["id"] > player.get("seen_threat", 0) and event["resolved"] >= max(player["joined"], player.get("arrived", 0)): return event return None @@ -2215,6 +2260,8 @@ def upper_first(text: str) -> str: def log(world: dict, now: float, kind: str, text: str, who: str | None = None) -> None: + if world.here != HOME_CITY: + text = f"{world['city']['name']}: {text}" world["ledger"].append({"at": now, "kind": kind, "text": text, "who": who}) del world["ledger"][:-MAX_LOG] @@ -2347,6 +2394,7 @@ def new_player(uid: str, name: str, cls: str, now: float) -> dict: "perks": {"bank_slot": 0}, "manual": [], "patterns": [], "found": [], "eat_below": EAT_BELOW, "rented": 0, "boosts": [], "bought": None, "deeds": {}, "owned": [], "look": dict(DEFAULT_LOOK), "garrison": False, + "at": HOME_CITY, "banks": {}, "travel": None, # banks: what you left in the towns you're not in "donated": 0, "gave": {}, # item (or "gold"): {qty, worth, favour} given to the city, see credit() "ledger": [], # what you did, see note() and track() @@ -3152,7 +3200,7 @@ def fires_view(world: dict, now: float) -> dict: users = {} for player in world["players"].values(): action = player["action"] and ACTION_BY_ID.get(player["action"]["id"]) - if action and (action.get("fire") or action.get("tend")): + if action and (action.get("fire") or action.get("tend")) and player["at"] == world.here and not player["travel"]: users.setdefault(action.get("fire") or action["tend"], []).append( {"id": player["id"], "name": player["name"], "action": action["id"]}) return {key: {**fire, "heat": heat(world, key), "speed": speed(world), "users": users.get(key, [])} @@ -3427,6 +3475,11 @@ def process_player(world: dict, player: dict, now: float, rng: random.Random | N """Run the player's action forward to `now` (capped at 24h past last_active).""" rng = rng or random.Random() summary = empty_summary() + if player["travel"]: + if now < player["travel"]["arrive"]: + return summary # on the road: no work gets done + arrive(world, player) + world = here(world, player) collect_orders(world, player, now) current = player["action"] if current and current.get("party"): @@ -3736,6 +3789,8 @@ def join_fight(world: dict, player: dict, uid: str, now: float) -> str | None: host = world["players"].get(uid) if not host or host is player: return "No one to join" + if host["at"] != player["at"] or host["travel"]: + return f"{host['name']} is in another town" run = party_of(world, host) if run and ACTION_BY_ID[run["action"]].get("dungeon") and run is not party_of(world, player): if "run" in run: @@ -4200,8 +4255,11 @@ def _refund(world: dict, order: dict, now: float) -> None: for uid, items in _gave(order).items(): player = world["players"].get(uid) for item, qty in items.items(): - if qty and player: + if qty and player and player["at"] == world.here: bank_add(world, player, item, qty, now, empty_summary()) + elif qty and player: + bank = player["banks"].setdefault(world.here, {}) # waits in their bank here + bank[item] = bank.get(item, 0) + qty order["provided"], order["gave"] = {}, {} owner = world["players"].get(order["by"]) if owner: @@ -4381,7 +4439,14 @@ def _store(world: dict, order: dict, qty: int, now: float) -> None: def _hand_over(world: dict, order: dict, owner: dict, now: float) -> None: - """Put delivered items in the requester's bank; what doesn't fit waits on the order.""" + """Put delivered items in the requester's bank in the order's town, whether or not they're + there; if they are, what doesn't fit waits on the order.""" + if owner["at"] != world.here: + bank = owner["banks"].setdefault(world.here, {}) + bank[order["item"]] = bank.get(order["item"], 0) + order["held"] + note(world, owner, now, "Received", order["item"], order["held"], label=f"Work order Β· {world['city']['name']}") + order["held"] = 0 + return fits = min(order["held"], bank_room(world, owner, order["item"])) if fits: owner["bank"][order["item"]] = owner["bank"].get(order["item"], 0) + fits @@ -4483,7 +4548,149 @@ def donate(world: dict, player: dict, item: str, qty: int, now: float) -> str | return None +def stand_guard(world: World, player: dict, join: bool, now: float) -> str | None: + """Join or leave this town's garrison. Whoever wasn't here when the gates closed stays out.""" + raid = upcoming_raid(world) + if join and not raid: + return "There's no raid to stand guard for" + if join and player.get("arrived", 0) > raid["fire_at"] - GATES_WARNING / speed(world): + return "The gates have closed" + player["garrison"] = bool(join) + return None + + +def travel(world: World, player: dict, to: str, pouch: dict, now: float) -> str | None: + """Set off for another town with what fits in a pouch. Work waits until you arrive, + but a shared fight or a work order stays behind, and so does your place in the garrison.""" + if to not in world.doc["cities"]: + return "No such town" + if to == player["at"]: + return "You're already there" + if len(pouch) > POUCH_SLOTS: + return f"A pouch holds {POUCH_SLOTS} kinds of item" + for item, qty in pouch.items(): + if not isinstance(qty, int) or qty < 1 or qty > POUCH_STACK: + return f"A pouch holds up to {POUCH_STACK} of each item" + if player["bank"].get(item, 0) < qty: + return "You don't have that" + current = player["action"] + if current and (current.get("party") or "order" in current): + drop_out(world, player, now, "Left for another town") + player["garrison"] = False + for item, qty in pouch.items(): + bank_take(player, item, qty) + player["travel"] = {"from": player["at"], "to": to, "left": now, "arrive": now + TRAVEL_TIME / speed(world), "pouch": pouch} + return None + + +def arrive(world: World, player: dict) -> None: + """Off the road: into this town's bank, pouch unpacked, and back to work.""" + trip, player["travel"] = player["travel"], None + player["banks"][player["at"]] = player["bank"] + player["at"], player["bank"] = trip["to"], player["banks"].pop(trip["to"], {}) + player["arrived"] = trip["arrive"] + world = here(world, player) + for item, qty in trip["pouch"].items(): + player["bank"][item] = player["bank"].get(item, 0) + qty # never lost, even to a full bank + current = player["action"] + if current: + current.pop("fight", None) + current["start"] = max(current["start"], trip["arrive"]) + note(world, player, trip["arrive"], "Arrived", label=world["city"]["name"]) + + +def propose_charter(world: World, player: dict, name, region, now: float) -> str | None: + """Ask the guild to found a new town. A second founder has to sign before it happens.""" + name = str(name or "").strip() + if not 3 <= len(name) <= 24: + return "A town's name takes 3 to 24 letters" + if region not in REGIONS: + return "Pick a region" + if any(city.get("region") == region for city in world.doc["cities"].values()): + return f"There's already a town in the {REGIONS[region]['name'].lower()}" + if world["charter"]: + return "A charter is already waiting to be signed" + if len(world.doc["cities"]) >= MAX_CITIES: + return "The kingdom can't hold another town yet" + if not _slug(name): + return "A town's name takes 3 to 24 letters" + if _slug(name) in world.doc["cities"]: + return "There's already a town by that name" + error = _founding_short(world) + if error: + return error + world["charter"] = {"name": name, "region": region, "by": player["id"], "from": world.here, "at": now} + log(world, now, "tier", f"{player['name']} drew up a charter for a new town: {name}") + return None + + +def _founding_short(world: World) -> str | None: + """Why this town can't send out settlers, if it can't.""" + city = world["city"] + if city["tier"] + 1 < len(TIERS): + return f"Only a {TIERS[-1]['name'].lower()} can found a town" + if city["treasury"] < FOUNDING["gold"]: + return f"The treasury needs {int(city['treasury']):,} / {FOUNDING['gold']:,} gold" + if city["stockpile"].get("provisions", 0) < FOUNDING["provisions"]: + return f"The stockpile needs {city['stockpile'].get('provisions', 0):,} / {FOUNDING['provisions']:,} provisions" + return None + + +def sign_charter(world: World, player: dict, now: float) -> str | None: + """The second founder signs: settlers, gold and provisions leave, and the town exists.""" + charter = world["charter"] + if not charter: + return "No charter to sign" + if charter["by"] == player["id"]: + return "Another founder has to sign it" + source = world.at(charter["from"]) + error = _founding_short(source) + if error: + return error + giving = source["city"] + giving["population"] -= FOUNDING["settlers"] + giving["treasury"] -= FOUNDING["gold"] + giving["stockpile"]["provisions"] -= FOUNDING["provisions"] + if not giving["stockpile"]["provisions"]: + del giving["stockpile"]["provisions"] + city = _new_city(now, speed(world), charter["name"]) + city["population"] = float(FOUNDING["settlers"]) + city["region"] = charter["region"] + city["stockpile"]["provisions"] = FOUNDING["provisions"] + city["next_event_at"] = now + world.doc["cities"][_slug(charter["name"])] = city + world["charter"] = None + log(world, now, "tier", f"{charter['name']} was founded. {FOUNDING['settlers']} settlers set out from {giving['name']}") + return None + + +def cancel_charter(world: World, player: dict) -> str | None: + if not world["charter"] or world["charter"]["by"] != player["id"]: + return "It isn't yours to tear up" + world["charter"] = None + return None + + +def kingdom_view(world: World, now: float) -> dict: + """Every town at a glance, and what's on the road.""" + cities = [] + for key, city in world.doc["cities"].items(): + people = [p for p in world["players"].values() if p["at"] == key and not p["travel"]] + cities.append({"id": key, "name": city["name"], "region": city.get("region"), "town_scale": TOWN_SCALE[city["tier"]], + "population": int(city["population"]), + "tier": TIERS[city["tier"]]["name"], "repelled": city["repelled"], + "people": [p["id"] for p in people], "founded": city["founded"]}) + charter = world["charter"] + return {"cities": cities, "charter": charter, "pouch": {"slots": POUCH_SLOTS, "stack": POUCH_STACK}, + "founding": FOUNDING, "max": MAX_CITIES, "short": _founding_short(world), + "regions": REGIONS, "region_yield": REGION_YIELD, + "road": [{"id": p["id"], **{k: p["travel"][k] for k in ("from", "to", "arrive")}} + for p in world["players"].values() if p["travel"]]} + + def give(world: dict, giver: dict, receiver: dict, item: str, qty: int, now: float) -> str | None: + if receiver["at"] != giver["at"] or receiver["travel"]: + return f"{receiver['name']} is in another town" if receiver is giver: return "You can't give to yourself" if qty <= 0 or giver["bank"].get(item, 0) < qty: @@ -4922,7 +5129,7 @@ def defence(world: dict, guards: int | None = None) -> dict: return {"total": round(sum(parts.values()), 1), "parts": parts} garrison = [] for player in world["players"].values(): - if player["garrison"]: + if player["garrison"] and player["at"] == world.here: power = combat_power(player) garrison.append({"id": player["id"], "name": player["name"], "power": round(power, 1)}) parts["garrison"] += power @@ -4973,9 +5180,16 @@ def _pay_guards(world: dict, report: dict) -> None: city["wages"] = city.get("wages", 0) - report["guards"] * GUARD_WAGE -def tick(world: dict, now: float, rng: random.Random | None = None) -> bool: - """Advance the city and events to `now`. Returns True if anything changed.""" +def tick(world: World, now: float, rng: random.Random | None = None) -> bool: + """Advance every town and its events to `now`. Returns True if anything changed.""" rng = rng or random.Random() + changed = False + for key in list(world.doc["cities"]): + changed = _tick_city(world.at(key), now, rng) or changed + return changed + + +def _tick_city(world: World, now: float, rng: random.Random) -> bool: city = world["city"] changed = False burn_fires(world, now) @@ -5094,12 +5308,39 @@ THREAT_EVERY = 48 THREAT_WOBBLE = 2 +def city_age(world: World, now: float) -> float: + """Game days since this town was founded.""" + return (now - world["city"]["founded"]) * speed(world) / DAY + + +def threat_base(world: World, now: float) -> float: + """Bigger, richer and older towns draw bigger threats; every win draws a bolder one.""" + city = world["city"] + wealth = city["treasury"] + stockpile_value(city) + return (15 + 5 * city_age(world, now) + 1.5 * city["population"] + 1.6 * math.sqrt(wealth)) * (1 + 0.08 * city["repelled"]) + + +def _threats_elsewhere(world: World) -> list[dict]: + """The threats coming for the other towns.""" + return [event for key, city in world.doc["cities"].items() if key != world.here + for event in city["events"] if event["status"] == "upcoming" and event["kind"] in THREATS] + + def threat_slot(world: dict, now: float) -> float: - """When the next threat is due: two days after the last one's slot, never sooner than about two days off.""" + """When the next threat is due: two days after the last one's slot, never sooner than about two days off. + A new town falls in with the rest, from the first slot it has time to prepare for.""" hours = HOUR / speed(world) last = next((e["slot"] for e in reversed(world["events"]) if e["kind"] in THREATS and "slot" in e), None) soonest = now + (THREAT_EVERY - THREAT_WOBBLE) * hours - return max(last + THREAT_EVERY * hours, soonest) if last else now + THREAT_EVERY * hours + if last: + return max(last + THREAT_EVERY * hours, soonest) + slots = [e["slot"] for city in world.doc["cities"].values() for e in city["events"] if e["kind"] in THREATS and "slot" in e] + if not slots: + return now + THREAT_EVERY * hours + slot = max(slots) + while slot < now + FOUNDING_GRACE * hours: + slot += THREAT_EVERY * hours + return slot def _announce(world: dict, now: float, rng: random.Random) -> None: @@ -5107,7 +5348,7 @@ def _announce(world: dict, now: float, rng: random.Random) -> None: hours = HOUR / speed(world) first = not any(e["kind"] in ("raid", "dragon") for e in world["events"]) slot = threat_slot(world, now) - day = (now - world["created"]) * speed(world) / DAY + day = city_age(world, now) # The major-threat track: mostly bandits, sometimes (after the first days) a dragon. kind = "dragon" if not first and day >= 5 and rng.random() < 0.15 else "raid" event = { @@ -5115,13 +5356,16 @@ def _announce(world: dict, now: float, rng: random.Random) -> None: "announced": now, "recon": 0, "sabotage": 0.0, "jitter": rng.uniform(-1, 1), "slot": slot, "fire_at": slot + rng.uniform(-THREAT_WOBBLE, THREAT_WOBBLE) * hours, } + # Every town is hit in the same hour, so nobody can stand in two places. + other = next((e for e in _threats_elsewhere(world) if abs(e["slot"] - slot) < THREAT_EVERY / 2 * hours), None) + if other: + event.update(slot=other["slot"], fire_at=other["fire_at"]) world["next_event_id"] += 1 - # Bigger, richer and older cities draw bigger threats; every win draws a bolder one. - wealth = city["treasury"] + stockpile_value(city) - # A bigger guild draws a bolder band: half the combat power of everyone active in the last two days. + # A bigger guild draws a bolder band: half the combat power of everyone active in the last two + # days, shared between the towns by size, so where they stand doesn't shrink a raid. fighters = sum(combat_power(p) for p in world["players"].values() if p["last_active"] > now - 2 * DAY / speed(world)) - strength = ((15 + 5 * day + 1.5 * city["population"] + 1.6 * math.sqrt(wealth)) * (1 + 0.08 * city["repelled"]) - + 0.5 * fighters) + base = threat_base(world, now) + strength = base + 0.5 * fighters * (base / sum(threat_base(world.at(key), now) for key in world.doc["cities"])) # How big it looks is measured against what the city holds without preparing. event["standing"] = round(max(1.0, standing_defence(world)), 1) if kind == "dragon": @@ -5199,6 +5443,7 @@ WINDOW_HOURS = [4, 3, 2, 0] THREATS = ("raid", "dragon") +BANK_LOOT = 0.5 # share of what a fallen town's stockpile loses that its banks lose too GATES_WARNING = 300 # seconds of warning before a threat strikes @@ -5306,7 +5551,8 @@ def _fire(world: dict, event: dict, now: float, rng: random.Random) -> None: _deed(world["players"][entry["id"]], "dragons" if event["kind"] == "dragon" else "defended") # Wares bought against this threat are spent. for player in world["players"].values(): - player["boosts"] = [b for b in player["boosts"] if "threat" not in b] + if player["at"] == world.here: + player["boosts"] = [b for b in player["boosts"] if "threat" not in b] elif event["kind"] == "merchant": world["city"]["merchant_until"] = now + 12 * HOUR / speed(world) event["report"] = {"title": "A merchant caravan has arrived", @@ -5324,6 +5570,26 @@ def _fire(world: dict, event: dict, now: float, rng: random.Random) -> None: log(world, now, "event", f"{taken} refugees settled in the city") +def _loot_banks(world: World, event: dict, share: float, now: float) -> bool: + """A town that falls loses part of what's banked there: half what the stockpile lost, + less the share of each player's slots that are strongbox. Worn gear and pouches are safe.""" + if event.get("slot", 0) <= world.get("bank_risk_after", 0): + return False + looted = False + for player in world["players"].values(): + bank = player["bank"] if player["at"] == world.here else player["banks"].get(world.here, {}) + locked = (player["rented"] + gear_bonus(player, "slots")) / max(1, bank_slots(world, player)) + for item in list(bank): + gone = int(bank[item] * share * BANK_LOOT * (1 - min(1, locked))) + if gone: + bank[item] -= gone + if not bank[item]: + del bank[item] + note(world, player, now, "Lost", item, gone, label=world["city"]["name"]) + looted = True + return looted + + def _resolve_raid(world: dict, event: dict, now: float, rng: random.Random) -> None: city = world["city"] stock = city["stockpile"] @@ -5382,6 +5648,8 @@ def _resolve_raid(world: dict, event: dict, now: float, rng: random.Random) -> N stolen = ", ".join(amount(item, qty) for item, qty in taken.items()) loot = [f"{gold:,} gold"] if gold else [] lines.append("The raiders carried off " + " and ".join(loot + ([stolen] if stolen else [])) + ".") + if _loot_banks(world, event, share, now): + lines.append("They broke into the bank vaults too.") built = [key for key, b in city["buildings"].items() if b["level"] and not b["damaged"]] if severity > 0.35 and built: key = rng.choice(built) @@ -5399,7 +5667,8 @@ def _resolve_raid(world: dict, event: dict, now: float, rng: random.Random) -> N event["report"] = report _pay_guards(world, report) for player in world["players"].values(): - player["garrison"] = False + if player["at"] == world.here: + player["garrison"] = False city["rally"] = city["rallies"] = 0 city["devotion"] = 0 city["hired"] = 0 @@ -5462,7 +5731,8 @@ def _resolve_dragon(world: dict, event: dict, now: float, rng: random.Random) -> event["report"] = report _pay_guards(world, report) for player in world["players"].values(): - player["garrison"] = False + if player["at"] == world.here: + player["garrison"] = False city["rally"] = city["rallies"] = 0 city["devotion"] = 0 city["hired"] = 0 @@ -5699,10 +5969,20 @@ def _modifier_sources(world: dict) -> list[dict]: return sources +def region_yield(world: dict, action: dict) -> float: + """How much more this gathering brings back in this town, for standing where it does.""" + city = world["city"] + region = REGIONS.get(city.get("region")) + if not region or action["skill"] not in region["skills"] or not action["outputs"]: + return 1.0 + tier = sum(action["level"] >= level for level in TIER_LEVELS) - 1 + return 1 + REGION_YIELD[tier] * TOWN_SCALE[city["tier"]] + + def skill_mods(world: dict, action: dict) -> dict: """How weather, happenings and problems change this action right now.""" skill = action["skill"] - mods = {"speed": 1.0, "yield": 1.0, "xp": 1.0, "blocked": None} + mods = {"speed": 1.0, "yield": region_yield(world, action), "xp": 1.0, "blocked": None} for source in _modifier_sources(world): mods["speed"] *= source.get("speed", {}).get(skill, 1) mods["yield"] *= source.get("yield", {}).get(skill, 1) @@ -5930,8 +6210,9 @@ def _fortune(world: dict, now: float, rng: random.Random, kind: str | None = Non city["devotion"] = city.get("devotion", 0) + gift lines.append(f"They prayed at the temple: +{gift} devotion.") for player in world["players"].values(): - bank_add(world, player, "bones", 10, now, empty_summary()) - note(world, player, now, "Received", "bones", 10, label="Pilgrims") + if player["at"] == world.here: + bank_add(world, player, "bones", 10, now, empty_summary()) + note(world, player, now, "Received", "bones", 10, label="Pilgrims") lines.append("They left 10 bones with every adventurer.") _record(world, now, "fortune", kind, "πŸ™", "Pilgrims passed through the city", lines) elif kind == "mercenaries": @@ -6906,6 +7187,14 @@ ORDER_RECIPES, ORDER_RAW = _order_sources() # What changed, shown on the Patch notes page. Newest first; every shipped change adds a # line here (new / balance / fix), and a new release a new entry on top. PATCH_NOTES = [ + {"date": "2026-11-04", "title": "Kingdom", "notes": [ + ("new", "Kingdom: found a new town. Needs a city, a charter and a second signature. Costs 20 settlers, 5,000 gold, 200 provisions."), + ("new", "Regions: ⛰️ mining, 🌲 woodcutting + hunting, 🌊 fishing, 🌾 farming. Up to +100% yield on basic materials, grows with the town. One town per region."), + ("new", "Travel between towns: 12 min, no work on the road. Pouch: 6 items, 100 each."), + ("new", "Banks and work orders are per town. Shared fights need the same town. Raids strike every town in the same hour."), + ("new", "Garrison: be there before the gates close."), + ("balance", "⚠️ From the raid after next, a lost raid loots banks in that town: 6-21%. Strongbox slots protect their share. Worn gear and pouches are safe."), + ]}, {"date": "2026-11-04", "title": "Crucible", "notes": [ ("new", "Crucible: 5th fire, for silver and gold bars."), ("balance", "Gold bar: +1 willow log. White flame or hotter pays it."), @@ -7088,7 +7377,7 @@ def content() -> dict: "city_uses": {item: city_uses(item) for item in ITEMS}, "prayers": [{**prayer, "text": describe_prayer(prayer)} for prayer in PRAYERS], "max_prayers": MAX_PRAYERS, "potion_charges": POTION_CHARGES, "kit_defence": KIT_DEFENCE, "salve_cap": SALVE_CAP, "order_recipes": ORDER_RECIPES, "order_raw": ORDER_RAW, - "make_max": MAKE_MAX, "input_share": INPUT_SHARE, "problems": PROBLEMS, "fittings": list(FITTING_BY_ID.values()), + "make_max": MAKE_MAX, "travel_time": TRAVEL_TIME, "input_share": INPUT_SHARE, "problems": PROBLEMS, "fittings": list(FITTING_BY_ID.values()), "equip_slots": EQUIP_SLOTS, "class_speed": CLASS_SPEED, "rest_rate": REST_RATE, "bite": BITE, "eat_below": EAT_BELOW, "eat_choices": EAT_CHOICES, "abilities": combat.ABILITIES, "enemy_abilities": combat.ENEMY_ABILITIES, "unlock": combat.UNLOCK, "auto_cd": combat.AUTO_CD, "watch": combat.WATCH, "gcd": combat.GCD, "weapon_kits": combat.WEAPON_KITS, "group_size": GROUP_SIZE, "dungeon_size": DUNGEON_SIZE, "dungeon_wipes": DUNGEON_WIPES, "trade_ability": combat.TRADE_ABILITY, "potion_below": combat.POTION_BELOW, diff --git a/static/app.js b/static/app.js index 70a0d2c..77c3b7c 100644 --- a/static/app.js +++ b/static/app.js @@ -775,6 +775,7 @@ function sidebar() { ${nav("town", "🏘️", "Town square", `${S.city.population}`, "", `Population ${S.city.population}`)} ${nav("council", "πŸ“œ", "Council & threats", "", raid ? `` : "", raid ? "A threat is coming" : "")} + ${nav("kingdom", "πŸ—ΊοΈ", "Kingdom", `${S.kingdom.cities.length}`, S.kingdom.charter ? `sign` : "", S.kingdom.charter ? "A charter is waiting to be signed" : "")} ${nav("orders", ORDER_ICON(), "Work orders", "", takeable ? `${takeable}` : "", takeable ? `${takeable} for you` : "")} ${nav("board", "πŸ’¬", "Town board")} ${rosterNav()} @@ -810,7 +811,7 @@ function devbar() { `; } -const TITLES = { town: "Town square", council: "Council & threats", orders: "Work orders", board: "Town board", roster: "Guild roster", notes: "Patch notes", bank: "Bank", character: "Character" }; +const TITLES = { town: "Town square", kingdom: "Kingdom", council: "Council & threats", orders: "Work orders", board: "Town board", roster: "Guild roster", notes: "Patch notes", bank: "Bank", character: "Character" }; function topbar() { let title = TITLES[page] || "Guildhall"; @@ -818,7 +819,9 @@ function topbar() { if (page.startsWith("character:")) title = S.players.find((p) => p.id === page.slice(10))?.name || "Character"; if (!S.me) title = "Welcome to Guildhall"; let chips = ""; - if (S.me?.action) { + if (S.me?.travel) { + chips += ``; + } else if (S.me?.action) { const action = C.actions.find((a) => a.id === (S.me.action.growing || S.me.action.id)); chips += ``; } else if (S.me) { @@ -926,7 +929,62 @@ function pageHtml() { } if (page.startsWith("character:")) return characterSheet(page.slice(10)); if (page === "character") return characterSheet(S.uid); - return ({ town, council, orders, board, roster, notes, bank, achievements }[page] || town)(); + return ({ town, kingdom, council, orders, board, roster, notes, bank, achievements }[page] || town)(); +} + +// --- kingdom ---------------------------------------------------------------- +let pouch = {}; + +function regionPerks(region, scale) { + const y = S.kingdom.region_yield; + return `${region.skills.map((id) => skillOf(id).icon).join("")} +${pct(y[0] * scale)} β†’ +${pct(y.at(-1) * scale)}`; +} + +function townName(id) { + return S.kingdom.cities.find((c) => c.id === id)?.name || id; +} + +function kingdom() { + const me = S.me, k = S.kingdom; + const towns = k.cities.map((c) => { + const here = c.id === me.at && !me.travel; + const road = k.road.filter((r) => r.to === c.id).length; + const region = k.regions[c.region]; + return `
+

${esc(c.name)} ${here ? `πŸ“ Here` : ""}

+

${esc(c.tier)} Β· πŸ‘₯ ${fmt(c.population)} Β· πŸ›‘οΈ ${fmt(c.repelled)}${road ? ` Β· πŸ›€οΈ ${road}` : ""}

+ ${region ? `

${region.icon} ${esc(region.name)} Β· ${regionPerks(region, c.town_scale)}

` : ""} +

${c.people.length ? c.people.map((uid) => esc(playerName(uid))).join(", ") : `Nobody here`}

+ ${here || me.travel ? "" : ``} +
`; + }).join(""); + const kinds = Object.keys(pouch).length; + const stock = Object.keys(me.bank).filter((id) => !pouch[id]).sort((a, b) => item(a).name.localeCompare(item(b).name)); + const pack = me.travel + ? `

πŸ›€οΈ ${esc(townName(me.travel.from))} β†’ ${esc(townName(me.travel.to))}: ${dur(Math.max(0, me.travel.arrive - S.now))}

+

${Object.entries(me.travel.pouch).map(([id, qty]) => itemChip(id, qty)).join(" ") || `Empty pouch`}

` + : `

${kinds} / ${k.pouch.slots} Β· up to ${k.pouch.stack} each

+

${Object.entries(pouch).map(([id, qty]) => ``).join(" ") || `Empty`}

+
+ +
`; + const charter = k.charter; + const full = k.cities.length >= k.max; + const open = Object.entries(k.regions).filter(([id]) => !k.cities.some((c) => c.region === id)); + const cost = `${COIN} ${fmt(S.city.treasury)} / ${fmt(k.founding.gold)} Β· ${itemChip("provisions", S.city.stockpile.provisions || 0)} / ${fmt(k.founding.provisions)} Β· πŸ‘₯ ${k.founding.settlers}`; + const founding = charter + ? `

πŸ“œ ${esc(charter.name)} Β· ${k.regions[charter.region].icon} ${esc(k.regions[charter.region].name)} Β· ${esc(playerName(charter.by))}

+ ${charter.by === me.id ? `` : ``}` + : full ? `

${k.cities.length} / ${k.max} towns

` + : `

${cost}

+ ${S.city.next_tier ? `

${esc(k.short)}

` : `
+ +
`}`; + return `
${towns}
+
+

${me.travel ? "On the road" : "Travel pouch"}

${pack}
+

Found a town

${founding}
+
`; } // Where an item comes from: the recipe that makes it, else what finds it, else the fight that drops it. @@ -1899,7 +1957,7 @@ function actionCard(a) { return `
${icon}
-
${esc(a.name)} ${Object.keys(a.outputs).map((id) => needTag(id) + fittedTag(id)).join("")}
+
${esc(a.name)} ${Object.keys(a.outputs).map((id) => needTag(id) + fittedTag(id)).join("")}${me.region_yield[a.id] ? ` +${pct(me.region_yield[a.id])}` : ""}
Level ${a.level} Β· ${dur(time)} Β· ${a.xp} XP
${orderable ? `` : ""}${Object.keys(a.inputs).length ? `` : ""}
${io ? `
${io}
` : ""} @@ -1992,7 +2050,7 @@ function itemPanel(id) { const me = S.me, it = item(id), have = me.bank[id]; const merchant = S.city.merchant_until > serverNow(); const price = it.value * (merchant ? 1.5 : 1); - const others = S.players.filter((p) => p.id !== S.uid); + const others = S.players.filter((p) => p.id !== S.uid && p.at === S.me.at && !p.travel); const qtyBox = (kind, label) => `
` + ``; return `
@@ -3287,6 +3345,28 @@ document.addEventListener("click", (e) => { if (d.install) return act("/api/install", { fitting: d.install, source: d.source }); if ("plot" in d) return act("/api/plot", { id: d.plot || null }); if (d.garrison) return act("/api/garrison", { join: d.garrison === "1" }); + if (d.travel) { + if (!confirm(`Travel to ${townName(d.travel)}? Work stops on the road.`)) return; + const sent = pouch; + pouch = {}; + return act("/api/travel", { to: d.travel, pouch: sent }); + } + if ("pouchAdd" in d) { + const id = $("[data-keep^=pouch-item]").value; + const qty = Math.min(Number($("[data-keep=pouch-qty]").value) || 0, S.kingdom.pouch.stack, S.me.bank[id] || 0); + if (id && qty > 0) pouch[id] = qty; + return render(); + } + if (d.pouchDrop) { delete pouch[d.pouchDrop]; return render(); } + if ("charterNew" in d) { + if (!confirm(`Draw up a charter? Once signed, ${S.kingdom.founding.settlers} settlers, gold and provisions leave this town.`)) return; + return act("/api/charter", { name: $("[data-keep=charter-name]").value, region: $("[data-keep=charter-region]").value }); + } + if ("charterSign" in d) { + if (!confirm(`Sign the charter for ${S.kingdom.charter.name}? The town is founded at once.`)) return; + return act("/api/charter/sign", {}); + } + if ("charterCancel" in d) return act("/api/charter/cancel", {}); if (d.perk) return act("/api/perk", { perk: d.perk }); if (d.pin) return act("/api/pin", { skill: d.pin }); if (d.track) return act("/api/track", { id: d.track }); diff --git a/static/styles.css b/static/styles.css index 3451127..f0ea0e7 100644 --- a/static/styles.css +++ b/static/styles.css @@ -952,3 +952,6 @@ button.swatch { width: 36px; height: 36px; } .food-kinds .missing .gi { color: var(--bad) !important; opacity: .3; } .food-kinds > span[data-goto]:hover { border-color: var(--muted); } .mood-tags { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; } + +.pouch-row { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin-top: 8px; } +.pouch-row select, .pouch-row input[type=text] { min-width: 0; flex: 1 1 140px; } diff --git a/tests/test_game.py b/tests/test_game.py index 307b1b3..36658b8 100644 --- a/tests/test_game.py +++ b/tests/test_game.py @@ -686,7 +686,7 @@ class EventTest(unittest.TestCase): self.assertEqual(p["favour"], 25) self.assertFalse(p["garrison"]) - def test_defeat_culls_and_loots_but_spares_banks(self): + def test_defeat_culls_and_loots_banks_too(self): world = world_with(("fred", "commoner")) p = world["players"]["fred"] p["bank"] = {"stone": 500} @@ -703,7 +703,8 @@ class EventTest(unittest.TestCase): self.assertLess(city["treasury"], 500) self.assertTrue(city["buildings"]["walls"]["damaged"]) self.assertEqual(city["buildings"]["walls"]["level"], 1) - self.assertEqual(p["bank"], {"stone": 500}) + self.assertLess(p["bank"]["stone"], 500) + self.assertGreater(p["bank"]["stone"], 0) self.assertEqual(game.defence(world)["parts"]["walls"], 0) def test_repair_is_cheaper_than_building(self): @@ -3594,6 +3595,277 @@ class WorldShapeTest(unittest.TestCase): self.assertEqual(world["next_event_id"], 99) +class KingdomTest(unittest.TestCase): + def setUp(self): + self.world = game.new_world(T0) + self.a = game.new_player("a", "Ada", "miner", T0) + self.b = game.new_player("b", "Bo", "builder", T0) + self.world["players"].update(a=self.a, b=self.b) + city = self.world["city"] + city["tier"] = len(game.TIERS) - 1 + city["population"] = 185.0 + city["treasury"] = 10000.0 + city["stockpile"]["provisions"] = 500 + + def found(self, name="Saltmere", now=T0, region="coast"): + self.assertIsNone(game.propose_charter(self.world, self.a, name, region, now)) + self.assertIsNone(game.sign_charter(self.world, self.b, now)) + return self.world.at(game._slug(name)) + + def go(self, player, to, pouch=None, now=T0): + self.assertIsNone(game.travel(game.here(self.world, player), player, to, pouch or {}, now)) + return now + game.TRAVEL_TIME + + def test_a_charter_needs_a_second_founder(self): + game.propose_charter(self.world, self.a, "Saltmere", "coast", T0) + self.assertEqual(len(self.world.doc["cities"]), 1) + self.assertIsNotNone(game.sign_charter(self.world, self.a, T0)) + self.assertIsNone(game.sign_charter(self.world, self.b, T0)) + self.assertEqual(len(self.world.doc["cities"]), 2) + + def test_founding_takes_settlers_gold_and_provisions_along(self): + new = self.found() + self.assertEqual(self.world["city"]["population"], 165.0) + self.assertEqual(self.world["city"]["treasury"], 5000.0) + self.assertEqual(self.world["city"]["stockpile"]["provisions"], 300) + self.assertEqual(new["city"]["population"], 20.0) + self.assertEqual(new["city"]["stockpile"]["provisions"], 200) + self.assertEqual(new["city"]["tier"], 0) + + def test_only_a_full_city_can_found(self): + self.world["city"]["tier"] = 2 + self.assertIn("city", game.propose_charter(self.world, self.a, "Saltmere", "coast", T0)) + + def test_travel_pauses_work_and_arrives_with_the_pouch(self): + new = self.found() + self.a["bank"] = {"stone": 150, "logs": 5} + self.assertIsNone(game.start_action(self.world, self.a, "mine_stone", T0)) + arrive = self.go(self.a, new.here, {"stone": 100}) + self.assertEqual(self.a["bank"], {"stone": 50, "logs": 5}) + xp = self.a["xp"]["mining"] + game.process_player(self.world, self.a, arrive - 1) + self.assertEqual(self.a["xp"]["mining"], xp) + self.assertEqual(self.a["at"], game.HOME_CITY) + game.process_player(self.world, self.a, arrive + 600) + self.assertEqual(self.a["at"], new.here) + self.assertEqual(self.a["banks"][game.HOME_CITY], {"stone": 50, "logs": 5}) + self.assertGreater(self.a["xp"]["mining"], xp) + self.assertGreaterEqual(self.a["bank"]["stone"], 100) + + def test_pouch_limits(self): + new = self.found() + self.a["bank"] = {"stone": 500} + travel = lambda pouch: game.travel(self.world, self.a, new.here, pouch, T0) + self.assertIn("up to", travel({"stone": game.POUCH_STACK + 1})) + self.assertIn("kinds", travel({f"i{n}": 1 for n in range(game.POUCH_SLOTS + 1)})) + self.assertIn("don't have", travel({"logs": 1})) + self.assertIsNone(self.a["travel"]) + + def test_a_full_bank_never_loses_the_pouch(self): + new = self.found() + self.a["bank"] = {"stone": 100} + self.a["overflow"] = "stop" + self.a["banks"][new.here] = {f"item{n}": 1 for n in range(40)} + arrive = self.go(self.a, new.here, {"stone": 100}) + game.process_player(self.world, self.a, arrive) + self.assertEqual(self.a["bank"]["stone"], 100) + + def test_garrison_counts_only_where_you_stand(self): + new = self.found() + self.a["garrison"] = True + before = game.defence(self.world)["parts"]["garrison"] + self.assertGreater(before, 0) + self.assertEqual(game.defence(new)["parts"]["garrison"], 0) + self.go(self.a, new.here) + self.assertFalse(self.a["garrison"]) + + def test_gates_close_on_latecomers(self): + new = self.found() + raid = {"id": 900, "kind": "raid", "status": "upcoming", "fire_at": T0 + 3600, "slot": T0 + 3600, "strength": 10, "sabotage": 0.0, "recon": 0, "jitter": 0} + new["events"].append(raid) + self.a["at"] = new.here + self.a["arrived"] = T0 + 3600 - game.GATES_WARNING + 1 + self.assertIn("gates", game.stand_guard(new, self.a, True, T0 + 3599)) + self.a["arrived"] = T0 + self.assertIsNone(game.stand_guard(new, self.a, True, T0 + 3599)) + self.assertTrue(self.a["garrison"]) + + def test_towns_are_hit_in_the_same_hour(self): + rng = random.Random(4) + game.tick(self.world, T0 + 13 * game.HOUR, rng) + home = game.upcoming_raid(self.world) + new = self.found(now=T0 + 13 * game.HOUR) + game.tick(self.world, T0 + 13 * game.HOUR + 1, rng) + threat = game.upcoming_raid(new) + self.assertEqual(threat["slot"], home["slot"]) + self.assertEqual(threat["fire_at"], home["fire_at"]) + + def test_a_new_town_gets_time_before_its_first_threat(self): + rng = random.Random(4) + game.tick(self.world, T0 + 13 * game.HOUR, rng) + home = game.upcoming_raid(self.world) + late = home["slot"] - 2 * game.HOUR + new = self.found(now=late) + game.tick(self.world, late + 1, rng) + threat = game.upcoming_raid(new) + self.assertGreater(threat["slot"], home["slot"]) + + def test_a_new_town_draws_a_small_raid(self): + rng = random.Random(4) + game.tick(self.world, T0 + 13 * game.HOUR, rng) + new = self.found(now=T0 + 13 * game.HOUR) + game.tick(self.world, T0 + 13 * game.HOUR + 1, rng) + self.assertLess(game.upcoming_raid(new)["strength"], game.upcoming_raid(self.world)["strength"]) + + def test_where_fighters_stand_doesnt_shrink_a_raid(self): + new = self.found() + now = T0 + 3600 + self.a["last_active"] = self.b["last_active"] = now + self.a["xp"]["combat"] = 100000 + game._announce(self.world, now, random.Random(1)) + first = self.world["events"][-1]["strength"] + self.world["events"].clear() + self.a["at"] = new.here + game._announce(self.world, now, random.Random(1)) + self.assertEqual(self.world["events"][-1]["strength"], first) + + def loot(self, world, slot, share=0.4): + return game._loot_banks(world, {"slot": slot}, share, T0) + + def test_a_fallen_town_loots_only_its_own_banks(self): + new = self.found() + self.a["bank"] = {"stone": 1000} + self.a["banks"][new.here] = {"stone": 1000} + self.assertTrue(self.loot(self.world, 5)) + self.assertEqual(self.a["bank"]["stone"], 800) + self.assertEqual(self.a["banks"][new.here]["stone"], 1000) + + def test_a_bank_elsewhere_is_looted_where_it_lies(self): + new = self.found() + self.a["at"] = new.here + self.a["banks"][game.HOME_CITY] = {"stone": 1000} + self.loot(self.world, 5) + self.assertEqual(self.a["banks"][game.HOME_CITY]["stone"], 800) + + def test_strongbox_slots_shield_their_share(self): + self.a["bank"] = {"stone": 1000} + self.a["rented"] = game.bank_slots(self.world, self.a) # half the slots, after renting as many again + self.loot(self.world, 5) + self.assertEqual(self.a["bank"]["stone"], 900) + + def test_the_raid_on_its_way_at_the_switch_spares_banks(self): + self.world["bank_risk_after"] = 5 + self.a["bank"] = {"stone": 1000} + self.assertFalse(self.loot(self.world, 5)) + self.assertEqual(self.a["bank"]["stone"], 1000) + self.assertTrue(self.loot(self.world, 6)) + + def test_worn_gear_is_never_looted(self): + self.a["equip"]["weapon"] = "copper_sword" + self.a["bank"] = {"stone": 1000} + self.loot(self.world, 5) + self.assertEqual(self.a["equip"]["weapon"], "copper_sword") + + def test_gifts_and_fights_stay_in_town(self): + new = self.found() + self.a["bank"] = {"stone": 10} + self.b["at"] = new.here + self.assertIn("another town", game.give(self.world, self.a, self.b, "stone", 5, T0)) + self.assertIn("another town", game.join_fight(self.world, self.a, "b", T0)) + + def test_a_refund_waits_in_the_bank_where_the_order_was(self): + new = self.found() + order = {"id": 1, "by": "b", "provided": {"stone": 5}, "gave": {"a": {"stone": 5}}, "reward": 0, "paid": 0} + self.a["at"] = new.here + game._refund(self.world, order, T0) + self.assertEqual(self.a["banks"][game.HOME_CITY]["stone"], 5) + self.assertNotIn("stone", self.a["bank"]) + + def test_every_gathering_trade_has_a_region(self): + self.assertEqual({skill for region in game.REGIONS.values() for skill in region["skills"]}, game.GATHERING) + + def test_one_town_to_a_region(self): + self.found() + self.assertIn("already", game.propose_charter(self.world, self.a, "Brine", "coast", T0)) + self.assertIsNone(game.propose_charter(self.world, self.a, "Brine", "forest", T0)) + + def test_a_region_favours_its_own_trades_and_common_stuff(self): + hills = self.found(region="mountains") + action = game.ACTION_BY_ID + self.assertEqual(game.region_yield(hills, action["mine_stone"]), 1.5) + self.assertEqual(game.region_yield(hills, action["mine_copper"]), 1.5) + self.assertEqual(game.region_yield(hills, action["mine_runite"]), 1.05) + self.assertEqual(game.region_yield(hills, action["cut_logs"] if "cut_logs" in action else next(a for a in game.ACTIONS if a["skill"] == "woodcutting")), 1.0) + self.assertEqual(game.region_yield(self.world, action["mine_copper"]), 1.0) + + def test_the_bonus_grows_with_the_town(self): + hills = self.found(region="mountains") + hills["city"]["tier"] = len(game.TIERS) - 1 + self.assertEqual(game.region_yield(hills, game.ACTION_BY_ID["mine_copper"]), 2.0) + + def test_a_region_pays_more_ore_but_the_same_xp(self): + hills = self.found(region="mountains") + hills["city"]["tier"] = len(game.TIERS) - 1 + self.a["cls"] = "builder" + home = game.new_player("c", "Cy", "builder", T0) + self.world["players"]["c"] = home + self.a["at"] = hills.here + action = game.ACTION_BY_ID["mine_copper"] + for player, world in ((self.a, hills), (home, self.world)): + for _ in range(10): + game._finish_action(world, player, action, T0, random.Random(3), game.empty_summary()) + self.assertEqual(self.a["bank"]["copper_ore"], 2 * home["bank"]["copper_ore"]) + self.assertEqual(self.a["xp"]["mining"], home["xp"]["mining"]) + + def test_a_filled_order_goes_to_your_bank_in_its_town(self): + new = self.found() + order = {"id": 1, "by": "a", "item": "stone", "held": 40} + self.a["at"] = new.here + game._hand_over(self.world, order, self.a, T0) + self.assertEqual(order["held"], 0) + self.assertEqual(self.a["banks"][game.HOME_CITY]["stone"], 40) + self.assertNotIn("stone", self.a["bank"]) + + def test_a_town_needs_a_real_name(self): + self.assertIn("name", game.propose_charter(self.world, self.a, "!!!!", "coast", T0)) + + def test_a_report_from_before_you_arrived_stays_shut(self): + new = self.found() + new["events"].append({"id": 50, "kind": "raid", "status": "done", "resolved": T0 + 10, "report": {"title": "Victory"}}) + self.a["at"] = new.here + self.a["arrived"] = T0 + 20 + self.assertIsNone(game.unseen_threat(new, self.a)) + self.a["arrived"] = T0 + 5 + self.assertIsNotNone(game.unseen_threat(new, self.a)) + + def test_fires_list_only_who_is_here(self): + new = self.found() + tend = next(a for a in game.ACTIONS if a.get("tend")) + self.a["action"] = {"id": tend["id"], "start": T0} + self.assertTrue(game.fires_view(self.world, T0)[tend["tend"]]["users"]) + self.assertFalse(game.fires_view(new, T0)[tend["tend"]]["users"]) + + def test_the_log_says_which_town(self): + new = self.found() + game.log(new, T0, "raid", "Trouble") + self.assertIn("Saltmere", self.world["ledger"][-1]["text"]) + + def test_old_saves_gain_towns(self): + doc = json.loads(json.dumps(self.world.doc)) + doc["version"] = 39 + doc["orders"] = doc["cities"][game.HOME_CITY].pop("orders") + for player in doc["players"].values(): + for key in ("at", "banks", "travel"): + del player[key] + city = doc["cities"][game.HOME_CITY] + del city["name"], city["founded"] + world = game.migrate(doc, T0) + self.assertEqual(world["version"], game.WORLD_VERSION) + self.assertEqual(world["players"]["a"]["at"], game.HOME_CITY) + self.assertEqual(world["city"]["name"], "Guildhall") + self.assertEqual(world["orders"], []) + + if __name__ == "__main__": unittest.main()