From 348689763087871913ce9a6f15f38bb2e64bb0f2 Mon Sep 17 00:00:00 2001 From: rope Date: Wed, 4 Nov 2026 17:57:20 +0000 Subject: [PATCH] Caravans: crewed wagons, town stock by vote, roads, ambushes; war table shows all scouted threats and march impact Co-Authored-By: Claude Opus 5.5 --- app.py | 14 +- game.py | 359 +++++++++++++++++++++++++++++++++++++++++++-- static/app.js | 118 +++++++++++++-- static/icons.svg | 1 + static/styles.css | 1 + tests/test_game.py | 255 ++++++++++++++++++++++++++++++++ 6 files changed, 724 insertions(+), 24 deletions(-) diff --git a/app.py b/app.py index bbba87c..36d1c50 100644 --- a/app.py +++ b/app.py @@ -366,6 +366,18 @@ class Handler(BaseHTTPRequestHandler): return game.travel(world, player, str(body.get("to")), pouch if isinstance(pouch, dict) else {}, now) if path == "/api/council/propose": return game.propose_march(world, player, str(body.get("from")), str(body.get("to")), body.get("guards"), now) + if path == "/api/council/freight": + return game.propose_freight(world, player, str(body.get("to")), body.get("item"), body.get("qty"), now) + if path in ("/api/caravan/form", "/api/caravan/board"): + goods = body.get("goods") if isinstance(body.get("goods"), dict) else {} + freight = body.get("freight") if isinstance(body.get("freight"), list) else [] + if path == "/api/caravan/form": + return game.form_caravan(world, player, str(body.get("to")), goods, freight, now) + return game.board_caravan(world, player, body.get("id"), goods, freight, now) + if path == "/api/caravan/depart": + return game.depart_caravan(world, player, body.get("id"), now) + if path == "/api/caravan/cancel": + return game.cancel_caravan(world, player, body.get("id")) if path == "/api/council/vote": return game.vote_march(world, player, body.get("id"), bool(body.get("yes")), now) if path == "/api/charter": @@ -658,7 +670,7 @@ class Handler(BaseHTTPRequestHandler): "happenings": game.happenings_view(world, now), "history": history, "orders": world["orders"], - "kingdom": game.kingdom_view(world, now), + "kingdom": game.kingdom_view(world, now, uid), "city_speed": game.speed(world), "threat_report": unseen and {"id": unseen["id"], "kind": unseen["kind"], "at": unseen["resolved"], "report": unseen["report"]}, diff --git a/game.py b/game.py index 8b7d599..a6d24a1 100644 --- a/game.py +++ b/game.py @@ -1650,6 +1650,13 @@ BUILDINGS = { "final": {"yew_logs": 40, "yew_frame": 4, "bear_leather": 40, "rune_lock": 6}, "effect": "Per level: +3 bank slots, +250 stack size", }, + "roads": { + "name": "Roads", "icon": "๐Ÿ›ค๏ธ", "max": 3, "gold": 200, + "base": {"stone": 600, "logs": 300, "provisions": 60, "copper_rivets": 40}, + "advanced": {"cut_stone": 80, "beam": 10, "iron_nails": 100}, + "late": {"oak_frame": 4, "hide_glue": 30, "steel_hinges": 15}, + "effect": "Caravans on this town's roads: faster, bigger, fewer ambushes", + }, } # Buildings rise by labour: players working the site, and a slow trickle from # the townsfolk so nothing stalls completely while everyone is away. @@ -1684,7 +1691,7 @@ RAID_TRAITS = ["lightly armoured, heavy on archers", "mounted and fast, few bows # --- world --------------------------------------------------------------- -WORLD_VERSION = 42 +WORLD_VERSION = 43 HOME_CITY = "guildhall" 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 @@ -1705,6 +1712,21 @@ MARCH_TIME = 20 * HOUR # guards on the road, as a unit, between any two towns VOTE_TIME = HOUR # how long the war council has before the votes cast decide MAIN_ASSAULT = (1.5, 0.75) # how the bandits weigh their main target against the rest, kingdom total unchanged MAIN_TIER = 2 # a town has to be this big to draw it, and it takes two such towns +# Caravans: players crew a wagon train. Each road level, at either end, helps every caravan on that road. +CARAVAN_TIME = HOUR # game seconds town to town, on bare tracks +CARAVAN_LOAD = 1000 # items each crew member can carry +CARAVAN_WAIT = 2 * HOUR # a caravan that never sets off unloads again after this +FREIGHT_WAIT = 48 * HOUR # town stock the council sent, if no caravan takes it, goes back after this +CARRIAGE = 0.05 # of a town shipment's worth, paid in favour to the crew at the far end +ROAD_SPEED = 0.1 # less time per road level... +ROAD_LOAD = 0.25 # ...more load... +ROAD_SAFETY = 0.1 # ...and fewer ambushes +AMBUSH_ODDS = 0.3 # a full caravan's chance of an ambush, on bare tracks: bandits go for what's worth robbing +AMBUSH_MOST = 5 # how many ambushes can count for or against any one raid +AMBUSH_SHARE = 0.05 # an ambush party's size, against the raid it's from +AMBUSH_WEAKEN = 0.02 # the raid loses this much if its ambush is beaten... +AMBUSH_FEED = 0.02 # ...and gains this much if the ambush succeeds +AMBUSH_LOSS = 0.3 # of the cargo gone when it does 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 @@ -1795,7 +1817,7 @@ def new_world(now: float, speed: float = 1.0) -> World: "players": {}, "cities": {HOME_CITY: _new_city(now, speed, "Guildhall")}, "charter": None, - "marches": [], "council": [], "next_march_id": 1, + "marches": [], "council": [], "next_march_id": 1, "convoys": [], "freight": [], "next_event_id": 1, "ledger": [], "board": [], @@ -2073,6 +2095,12 @@ def migrate(world: dict, now: float | None = None) -> World: if player["at"] != HOME_CITY: player["town_favour"][HOME_CITY], player["favour"] = player["favour"], 0 world["version"] = 42 + if world["version"] < 43: + # Caravans, and roads for them. + for city in world.doc["cities"].values(): + city["buildings"].setdefault("roads", {"level": 0, "damaged": False, "fund": {}, "fittings": []}) + world.doc.update(convoys=[], freight=[]) + world["version"] = 43 return world @@ -4704,7 +4732,7 @@ def propose_march(world: World, player: dict, source: str, target: str, guards, return "Pick two towns" if not isinstance(guards, int) or guards < 1: return "Send at least one guard" - if any(p["status"] == "open" and p["from"] == source for p in world["council"]): + if any(p["status"] == "open" and p["from"] == source and "items" not in p for p in world["council"]): return f"{cities[source]['name']} already has a march before the council" ready = guards_on_duty(world.at(source)) if guards > ready: @@ -4745,13 +4773,16 @@ def _count_votes(world: World, proposal: dict, now: float) -> None: def _close_vote(world: World, proposal: dict, passed: bool, now: float) -> None: proposal["closed"] = now proposal["status"] = "rejected" + freight = "items" in proposal if passed: - proposal["status"] = "sent" if _send_guards(world, proposal, now) else "failed" + proposal["status"] = "sent" if (_ship_freight if freight else _send_guards)(world, proposal, now) else "failed" cities = world.doc["cities"] if proposal["status"] == "failed": - log(world, now, "raid", f"The war council's march from {cities[proposal['from']]['name']} found no guards at their posts") + log(world, now, "raid", f"The war council's shipment from {cities[proposal['from']]['name']} found nothing left to send" if freight + else f"The war council's march from {cities[proposal['from']]['name']} found no guards at their posts") elif proposal["status"] == "rejected": - log(world, now, "raid", f"The war council kept the guards in {cities[proposal['from']]['name']}") + log(world, now, "raid", f"The war council kept the goods in {cities[proposal['from']]['name']}" if freight + else f"The war council kept the guards in {cities[proposal['from']]['name']}") def _send_guards(world: World, proposal: dict, now: float) -> bool: @@ -4776,16 +4807,300 @@ def _send_guards(world: World, proposal: dict, now: float) -> bool: return True +def propose_freight(world: World, player: dict, target: str, item, qty, now: float) -> str | None: + """Ask the war council to send town stock to another town. A caravan still has to carry it.""" + if target not in world.doc["cities"] or target == world.here: + return "Pick another town" + if item not in ITEMS: + return "No such item" + if not isinstance(qty, int) or qty < 1: + return "Send at least one" + have = world["city"]["stockpile"].get(item, 0) + if qty > have: + return f"The stockpile holds {have:,} / {qty:,}" + proposal = {"id": world["next_march_id"], "by": player["id"], "from": world.here, "to": target, "items": {item: qty}, + "at": now, "ends": now + VOTE_TIME / speed(world), "yes": [player["id"]], "no": [], "status": "open"} + world["next_march_id"] += 1 + world["council"].append(proposal) + del world["council"][:-20] + log(world, now, "order", f"{player['name']} asked the war council to send {amount(item, qty)} to " + f"{world.doc['cities'][target]['name']}", player["id"]) + _count_votes(world, proposal, now) + return None + + +def _ship_freight(world: World, proposal: dict, now: float) -> bool: + """The goods leave the stockpile and wait at the gate for a caravan.""" + stock = world.at(proposal["from"])["city"]["stockpile"] + items = {} + for item, qty in proposal["items"].items(): + take = min(qty, stock.get(item, 0)) + if take: + take_stock_qty(stock, item, take) + items[item] = take + if items: + world["freight"].append({"id": proposal["id"], "from": proposal["from"], "to": proposal["to"], "items": items, "at": now}) + log(world.at(proposal["from"]), now, "order", f"{_listing(items)} waits at the gate for a caravan to {world.doc['cities'][proposal['to']]['name']}") + return bool(items) + + +def road_level(world: World, source: str, target: str) -> int: + """How good the road between two towns is: both ends' road works count.""" + return building_level(world.at(source), "roads") + building_level(world.at(target), "roads") + + +def caravan_route(world: World, source: str, target: str) -> dict: + """How long a caravan takes on this road, what each crew member carries, and its odds of an ambush.""" + level = road_level(world, source, target) + return {"time": CARAVAN_TIME * (1 - ROAD_SPEED * level) / speed(world), "load": int(CARAVAN_LOAD * (1 + ROAD_LOAD * level)), + "odds": AMBUSH_ODDS * (1 - ROAD_SAFETY * level), "level": level} + + +def _store_for(player: dict, town: str, item: str, qty: int) -> None: + """Put something in the player's bank in that town, wherever they are.""" + bank = player["bank"] if player["at"] == town else player["banks"].setdefault(town, {}) + bank[item] = bank.get(item, 0) + qty + + +def _convoy_load(convoy: dict) -> int: + return sum(qty for goods in convoy["goods"].values() for qty in goods.values()) + sum(convoy["freight"].values()) + + +def _in_caravan(world: World, player: dict) -> dict | None: + return next((c for c in world["convoys"] if player["id"] in c["crew"]), None) + + +def _load_caravan(world: World, convoy: dict, player: dict, goods: dict, freight: list, crew: int) -> str | None: + """Your own goods from your bank, then as much of the town's waiting shipments as fits.""" + room = caravan_route(world, convoy["from"], convoy["to"])["load"] * crew - _convoy_load(convoy) + for item, qty in goods.items(): + if not isinstance(qty, int) or qty < 1: + return "Load at least one" + if player["bank"].get(item, 0) < qty: + return "You don't have that" + if sum(goods.values()) > room: + return f"The wagons hold {room:,} more" + room -= sum(goods.values()) + mine = convoy["goods"].setdefault(player["id"], {}) + for item, qty in goods.items(): + bank_take(player, item, qty) + mine[item] = mine.get(item, 0) + qty + for shipment in world["freight"]: + if shipment["id"] not in freight or shipment["from"] != convoy["from"] or shipment["to"] != convoy["to"]: + continue + for item in list(shipment["items"]): + take = min(room, shipment["items"][item]) + if take: + take_stock_qty(shipment["items"], item, take) + convoy["freight"][item] = convoy["freight"].get(item, 0) + take + room -= take + world["freight"] = [shipment for shipment in world["freight"] if shipment["items"]] + return None + + +def form_caravan(world: World, player: dict, target: str, goods: dict, freight: list, now: float) -> str | None: + """Start loading a caravan here. Others can join it until you set off.""" + if target not in world.doc["cities"] or target == world.here: + return "Pick another town" + if _in_caravan(world, player): + return "You're already with a caravan" + convoy = {"id": world["next_march_id"], "from": world.here, "to": target, "leader": player["id"], "crew": [player["id"]], + "goods": {}, "freight": {}, "status": "loading", "at": now} + error = _load_caravan(world, convoy, player, goods, freight, 1) + if error: + return error + world["next_march_id"] += 1 + world["convoys"].append(convoy) + log(world, now, "order", f"{player['name']} is loading a caravan for {world.doc['cities'][target]['name']}", player["id"]) + return None + + +def board_caravan(world: World, player: dict, convoy_id, goods: dict, freight: list, now: float) -> str | None: + """Join a caravan loading here, or load more on the one you're with.""" + convoy = next((c for c in world["convoys"] if c["id"] == convoy_id), None) + if not convoy or convoy["status"] != "loading": + return "That caravan has gone" + if convoy["from"] != world.here: + return "That caravan is in another town" + other = _in_caravan(world, player) + if other and other is not convoy: + return "You're already with a caravan" + joining = player["id"] not in convoy["crew"] + error = _load_caravan(world, convoy, player, goods, freight, len(convoy["crew"]) + joining) + if error: + return error + if joining: + convoy["crew"].append(player["id"]) + return None + + +def _unload(world: World, convoy: dict) -> None: + """A caravan that won't go: goods back to their owners, town goods back to the gate.""" + for uid, goods in convoy["goods"].items(): + owner = world["players"].get(uid) + for item, qty in goods.items(): + if owner: + _store_for(owner, convoy["from"], item, qty) + if convoy["freight"]: + world["freight"].append({"id": convoy["id"], "from": convoy["from"], "to": convoy["to"], "items": convoy["freight"], "at": convoy["at"]}) + + +def cancel_caravan(world: World, player: dict, convoy_id) -> str | None: + convoy = next((c for c in world["convoys"] if c["id"] == convoy_id and c["status"] == "loading"), None) + if not convoy or convoy["leader"] != player["id"]: + return "It isn't yours to call off" + _unload(world, convoy) + world["convoys"].remove(convoy) + return None + + +def depart_caravan(world: World, player: dict, convoy_id, now: float) -> str | None: + """Set off. Everyone aboard goes on the road: no work until it arrives. Anyone who left town stays behind, and their goods with them.""" + convoy = next((c for c in world["convoys"] if c["id"] == convoy_id and c["status"] == "loading"), None) + if not convoy or convoy["leader"] != player["id"]: + return "It isn't yours to send off" + route = caravan_route(world, convoy["from"], convoy["to"]) + source = world.at(convoy["from"]) + for uid in list(convoy["crew"]): + member = world["players"][uid] + if member["at"] != convoy["from"] or member["travel"]: + convoy["crew"].remove(uid) + for item, qty in convoy["goods"].pop(uid, {}).items(): + _store_for(member, convoy["from"], item, qty) + if not convoy["crew"]: + return "Nobody's left to crew it" + arrive = now + route["time"] + for uid in convoy["crew"]: + member = world["players"][uid] + current = member["action"] + if current and (current.get("party") or "order" in current): + drop_out(source, member, now, "Left with a caravan") + member["garrison"] = False + member["travel"] = {"from": convoy["from"], "to": convoy["to"], "left": now, "arrive": arrive, "pouch": {}, "convoy": convoy["id"]} + fullness = _convoy_load(convoy) / (route["load"] * len(convoy["crew"])) + convoy.update(status="road", left=now, arrive=arrive, midway=now + route["time"] / 2, odds=route["odds"] * fullness, rolled=False) + log(source, now, "order", f"A caravan set off for {world.doc['cities'][convoy['to']]['name']} with {len(convoy['crew'])} crew") + return None + + +def _ambush(world: World, convoy: dict, now: float, rng: random.Random) -> None: + """Halfway down the road, bandits may strike. They come from the bigger raid at either end: beat them + and that raid goes in weaker; lose and they make off with cargo and come back the stronger for it.""" + convoy["rolled"] = True + if rng.random() >= convoy["odds"]: + return + raids = [threat for threat in (upcoming_raid(world.at(convoy["from"])), upcoming_raid(world.at(convoy["to"]))) if threat and threat["kind"] == "raid"] + if not raids: + return + raid = max(raids, key=lambda threat: threat["strength"]) + counted = raid.get("ambushes", 0) < AMBUSH_MOST + raid["ambushes"] = raid.get("ambushes", 0) + 1 + band = raid["strength"] * AMBUSH_SHARE * rng.uniform(0.7, 1.3) + crew = [world["players"][uid] for uid in convoy["crew"]] + won = sum(combat_power(member) for member in crew) >= band + town = world.at(convoy["to"]) + if won: + if counted: + raid["sabotage"] = min(0.3, raid["sabotage"] + AMBUSH_WEAKEN) + for member in crew: + gain_xp(here(world, member), member, "combat", round(band), now) + note(world, member, now, "Ambushed", label="Beat them off") + log(town, now, "raid", f"Bandits fell on the caravan from {world.doc['cities'][convoy['from']]['name']} and were beaten off. The coming raid is weaker for it") + else: + for owner, goods in [*convoy["goods"].items(), (None, convoy["freight"])]: + for item in list(goods): + gone = max(1, int(goods[item] * AMBUSH_LOSS)) + take_stock_qty(goods, item, min(gone, goods[item])) + if counted: + raid["strength"] = round(raid["strength"] * (1 + AMBUSH_FEED), 1) + for member in crew: + note(world, member, now, "Ambushed", label="Lost cargo") + log(town, now, "raid", f"Bandits robbed the caravan from {world.doc['cities'][convoy['from']]['name']}. The coming raid is stronger for it") + convoy["ambush"] = "won" if won else "lost" + + +def _caravan_arrives(world: World, convoy: dict, now: float) -> None: + """The caravan is in: goods to their owners' banks there, town goods to its stockpile, and the crew earn their favour there.""" + target = convoy["to"] + for uid, goods in convoy["goods"].items(): + owner = world["players"].get(uid) + for item, qty in goods.items(): + if owner: + _store_for(owner, target, item, qty) + town = world.at(target) + stock = town["city"]["stockpile"] + for item, qty in convoy["freight"].items(): + stock[item] = stock.get(item, 0) + qty + fee = sum(ITEMS[item]["value"] * qty for item, qty in convoy["freight"].items()) * CARRIAGE / max(1, len(convoy["crew"])) + for uid in convoy["crew"] if fee else []: + member = world["players"][uid] + if member["at"] == target: + member["favour"] += fee + else: + member["town_favour"][target] = member["town_favour"].get(target, 0) + fee + log(town, now, "order", f"A caravan came in from {world.doc['cities'][convoy['from']]['name']}" + + (f" with {_listing(convoy['freight'])}" if convoy["freight"] else "")) + world["convoys"].remove(convoy) + + +def _caravan_road_tick(world: World, now: float, rng: random.Random) -> bool: + changed = False + for convoy in list(world["convoys"]): + if convoy["status"] == "loading": + if now >= convoy["at"] + CARAVAN_WAIT / speed(world): + _unload(world, convoy) + world["convoys"].remove(convoy) + changed = True + continue + if not convoy["rolled"] and now >= convoy["midway"]: + _ambush(world, convoy, now, rng) + changed = True + if now >= convoy["arrive"]: + _caravan_arrives(world, convoy, now) + changed = True + for shipment in list(world["freight"]): + if now >= shipment["at"] + FREIGHT_WAIT / speed(world): + stock = world.at(shipment["from"])["city"]["stockpile"] + for item, qty in shipment["items"].items(): + stock[item] = stock.get(item, 0) + qty + log(world.at(shipment["from"]), now, "order", f"{_listing(shipment['items'])} went back to the stockpile: no caravan came") + world["freight"].remove(shipment) + changed = True + return changed + + +def march_curve(world: World) -> list[float]: + """What sending 0, 1, 2โ€ฆ of this town's guards takes from it and adds elsewhere: drill plus their kit, best first.""" + stock = world["city"]["stockpile"] + armed = guards_on_duty(world) + each = _militia(world) / max(1, guard_posts(world)) + values = {} + for slot, (stat, rate) in KIT_DEFENCE.items(): + line = [] + for item in sorted((i for i in stock if kit_slot(i) == slot), key=lambda i: -ITEMS[i].get(stat, 0)): + line += [ITEMS[item].get(stat, 0) * rate] * min(stock[item], armed - len(line)) + values[slot] = line + [0] * (armed - len(line)) + curve = [0.0] + kit = {slot: 0.0 for slot in KIT_DEFENCE} + for n in range(armed): + for slot in KIT_DEFENCE: + kit[slot] += values[slot][n] + total = sum(value for slot, value in kit.items() if slot != "salve") + min(SALVE_CAP, kit["salve"]) + curve.append(round(each * (n + 1) + total, 1)) + return curve + + def _threat_glance(world: World, now: float) -> dict | None: """What this town's scouts know of its coming threat, for the war table.""" threat = upcoming_raid(world) if not threat: return None view = event_view(world, threat, now) - return {key: view[key] for key in ("id", "kind", "intel", "at_gates", "earliest", "latest", "exact", "size", "range", "strength", "main") if key in view} + return {key: view[key] for key in ("id", "kind", "intel", "at_gates", "earliest", "latest", "exact", "headline", "size", "range", "strength", + "main", "group", "trait", "camp", "sabotage", "recon", "recon_next") if key in view} -def kingdom_view(world: World, now: float) -> dict: +def kingdom_view(world: World, now: float, viewer: str | None = None) -> dict: """Every town at a glance, and what's on the road.""" cities = [] for key, city in world.doc["cities"].items(): @@ -4797,7 +5112,11 @@ def kingdom_view(world: World, now: float) -> dict: "tier": TIERS[city["tier"]]["name"], "repelled": city["repelled"], "people": [p["id"] for p in people], "founded": city["founded"], "defence": guard["total"], "guards": guard["guards"], "posts": guard["posts"], "away": guard["away"], - "garrison": [entry["id"] for entry in guard["garrison"]], "threat": _threat_glance(town, now)}) + "garrison": [entry["id"] for entry in guard["garrison"]], "threat": _threat_glance(town, now), + "problems": [{"name": PROBLEMS[problem["kind"]]["name"], "icon": PROBLEMS[problem["kind"]]["icon"]} + for problem in city["problems"] if problem["kind"] in MINOR_THREATS], + "curve": march_curve(town), "roads": building_level(town, "roads"), + "route": None if key == world.here else caravan_route(world, world.here, key)}) charter = world["charter"] return {"cities": cities, "charter": charter, "pouch": {"slots": POUCH_SLOTS, "stack": POUCH_STACK}, "founding": FOUNDING, "max": MAX_CITIES, "short": _founding_short(world), @@ -4805,6 +5124,11 @@ def kingdom_view(world: World, now: float) -> dict: "council": [p for p in world["council"] if p["status"] == "open" or now - p.get("closed", now) < 6 * HOUR / speed(world)], "marches": [{key: march[key] for key in ("id", "from", "to", "guards", "arrive", "status")} | {"power": march_power(march)} for march in world["marches"]], + "caravans": [{key: convoy.get(key) for key in ("id", "from", "to", "leader", "crew", "status", "arrive", "ambush")} + | {"load": _convoy_load(convoy), "room": caravan_route(world, convoy["from"], convoy["to"])["load"] * len(convoy["crew"]), + "mine": convoy["goods"].get(viewer) if viewer else None, "freight": convoy["freight"]} + for convoy in world["convoys"]], + "freight": world["freight"], "road": [{"id": p["id"], **{k: p["travel"][k] for k in ("from", "to", "arrive")}} for p in world["players"].values() if p["travel"]]} @@ -5327,9 +5651,9 @@ def _pay_guards(world: dict, report: dict) -> None: city["wages"] = city.get("wages", 0) - report["guards"] * GUARD_WAGE -def _muster_tick(world: World, now: float) -> bool: - """Close the votes whose hour is up and move the companies on the road.""" - changed = False +def _muster_tick(world: World, now: float, rng: random.Random | None = None) -> bool: + """Close the votes whose hour is up and move the companies and caravans on the road.""" + changed = _caravan_road_tick(world, now, rng or random.Random()) for proposal in world["council"]: if proposal["status"] == "open" and now >= proposal["ends"]: _close_vote(world, proposal, len(proposal["yes"]) > len(proposal["no"]), now) @@ -5363,7 +5687,7 @@ def _march_on(world: World, march: dict, now: float) -> None: 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 = _muster_tick(world, now) + changed = _muster_tick(world, now, rng) for key in list(world.doc["cities"]): changed = _tick_city(world.at(key), now, rng) or changed return changed @@ -7231,7 +7555,7 @@ BUILDING_GLYPHS = { "houses": ("house", "#d0a060"), "walls": ("stone-wall", "#a8a29e"), "barracks": ("barracks-tent", "#c06a4a"), "smithy": ("anvil", "#d07a3c"), "temple": ("temple-gate", "#e9dfc6"), "granary": ("granary", "#e3c060"), "lumber_shed": ("wood-pile", "#b9844e"), "well": ("well", "#5aa0d8"), "spymaster": ("hooded-figure", "#8a7fd0"), - "storehouse": ("wooden-crate", "#b9844e"), + "storehouse": ("wooden-crate", "#b9844e"), "roads": ("stone-path", "#b6a587"), } ACTION_GLYPHS = { "fight_wolves": ("wolf-head", "#9aa1ab"), "fight_scouts": ("hooded-assassin", "#a08060"), @@ -7426,6 +7750,13 @@ 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": "Caravans", "notes": [ + ("new", "Caravans: carry goods between towns. 1h, 1,000 items per crew member. Everyone aboard stops work until it arrives."), + ("new", "Town stock: war council vote, then a caravan carries it. Crew earn 5% of its worth in favour at the far end."), + ("new", "Roads: new building, 3 levels. Each level at either end: -10% time, +25% load, -10% ambush odds."), + ("new", "Ambushes: up to 30% per trip, the fuller the likelier. Win: the coming raid -2%. Lose: 30% of the cargo gone, raid +2%. Up to 5 count per raid."), + ("new", "War table: every town's threat and minor troubles, as far as its scouts know. Marches show defence before and after, for both towns."), + ]}, {"date": "2026-11-04", "title": "Favour per town", "notes": [ ("new", "Favour is earned and spent per town. What you've saved so far stays in Guildhall."), ("new", "Bank slots: favour price starts at 500 and gold at 1,000 in each town, rising there. New ones work only in that town. Ones you already own work everywhere."), diff --git a/static/app.js b/static/app.js index 394e6f4..5f010cd 100644 --- a/static/app.js +++ b/static/app.js @@ -934,15 +934,81 @@ function pageHtml() { // --- kingdom ---------------------------------------------------------------- let pouch = {}; +let cargo = {}; +const cargoFreight = new Set(); function votesWaiting() { return S.kingdom.council.filter((p) => p.status === "open" && !p.yes.includes(S.uid) && !p.no.includes(S.uid)).length; } -function threatLine(t) { - if (!t) return `

No threat rumoured

`; - const size = t.strength ? fmt(t.strength) : t.range ? `${fmt(t.range[0])} - ${fmt(t.range[1])}` : t.size || "?"; - return `

${eventIcon(t.kind)} ${eventWhen(t, true)} ยท ${esc(String(size))}${t.main ? ` Main assault` : ""}

`; +function threatSize(t) { + return t?.strength ? fmt(t.strength) : t?.range ? `${fmt(t.range[0])} - ${fmt(t.range[1])}` : t?.size || "?"; +} + +function threatLine(t, problems) { + const trouble = problems.length ? `

${problems.map((p) => `${p.icon} ${esc(p.name)}`).join(" ยท ")}

` : ""; + if (!t) return `

No threat rumoured

${trouble}`; + const pips = [1, 2, 3].map((n) => n <= t.intel ? "โ—" : "โ—‹").join(""); + return `

${eventIcon(t.kind)} ${pips} ${eventWhen(t, true)} ยท ${esc(String(threatSize(t)))}${t.main ? ` Main assault` : ""}

+ ${t.group || t.trait || t.sabotage ? `

${[t.group && upperFirst(t.group), t.trait, t.sabotage && `-${t.sabotage}%`].filter(Boolean).map((x) => esc(String(x))).join(" ยท ")}

` : ""}${trouble}`; +} + +const upperFirst = (s) => s[0].toUpperCase() + s.slice(1); + +// How a town's defence stands up to what its scouts know: โœ… holds, โš ๏ธ too close to call, โŒ falls, โ“ unknown. +function holds(defence, t) { + if (!t || !(t.strength || t.range)) return "โ“"; + const low = t.strength || t.range[0], high = t.strength || t.range[1]; + return defence >= high ? "โœ…" : defence < low ? "โŒ" : "โš ๏ธ"; +} + +// What a march does to both towns: defence now โ†’ after, against each town's threat as scouted. +function marchImpact(source, target, guards) { + const k = S.kingdom, from = k.cities.find((c) => c.id === source), to = k.cities.find((c) => c.id === target); + if (!from || !to || source === target) return ""; + const n = Math.max(0, Math.min(guards || 0, from.curve.length - 1)), power = from.curve[n]; + const incoming = k.marches.filter((m) => m.to === to.id && m.status === "marching").reduce((sum, m) => sum + m.power, 0); + const row = (c, now, after) => `${esc(c.name)} ๐Ÿ›ก๏ธ ${fmt(now)} โ†’ ${fmt(after)} vs ${c.threat ? eventIcon(c.threat.kind) : ""} ${esc(String(threatSize(c.threat)))} ${holds(after, c.threat)}`; + return `
${row(from, from.defence, from.defence - power)}${row(to, to.defence + incoming, to.defence + incoming + power)}
`; +} + +function convoyPanel() { + const k = S.kingdom, me = S.me, here = me.at; + const others = k.cities.filter((c) => c.id !== here); + const mine = k.caravans.find((c) => c.crew.includes(S.uid)); + const list = (items) => Object.entries(items || {}).map(([id, qty]) => itemChip(id, qty, undefined, false)).join(" "); + const row = (c) => { + const lead = c.leader === S.uid, aboard = c.crew.includes(S.uid), loading = c.status === "loading"; + const state = loading ? `๐Ÿ“ฆ ${fmt(c.load)} / ${fmt(c.room)}` : `๐Ÿ›ค๏ธ ${dur(Math.max(0, c.arrive - S.now))}${c.ambush ? ` ยท ${c.ambush === "won" ? "โš”๏ธ Beat an ambush" : "๐Ÿ’€ Robbed"}` : ""}`; + const buttons = !loading || me.travel ? "" : lead + ? ` ` + : c.from === here && !mine ? `` : ""; + return `
๐ŸŽ ${esc(townName(c.from))} โ†’ ${esc(townName(c.to))} ยท ${c.crew.map((uid) => esc(playerName(uid))).join(", ")}${state}${buttons}
+ ${aboard && (c.mine || Object.keys(c.freight).length) ? `

${list(c.mine)} ${list(c.freight)}

` : ""}`; + }; + const waiting = k.freight.map((f) => `
๐Ÿ“ฆ ${list(f.items)} ${esc(townName(f.from))} โ†’ ${esc(townName(f.to))}${f.from === here && !me.travel ? `` : ""}
`).join(""); + const bank = Object.keys(me.bank).filter((id) => !cargo[id]).sort((a, b) => item(a).name.localeCompare(item(b).name)); + const stock = Object.keys(S.city.stockpile).sort((a, b) => item(a).name.localeCompare(item(b).name)); + const towns = others.map((c) => ``).join(""); + const chosen = others.find((c) => c.id === $("[data-keep=caravan-to]")?.value) || others[0]; + const route = chosen?.route; + const forming = me.travel ? "" : ` +

${mine && mine.status === "loading" ? "Load more" : "Load a caravan"}

+

${Object.entries(cargo).map(([id, qty]) => ``).join(" ") || `Your bank goods, none yet`}

+
+
+ ${mine && mine.status === "loading" ? `
` + : `
+ ${route ? `

โฑ ${dur(route.time)} ยท ๐Ÿ“ฆ ${fmt(route.load)} per crew ยท โš”๏ธ up to ${Math.round(route.odds * 100)}% ambush ยท ๐Ÿ›ค๏ธ ${route.level}

` : ""}`} +

Send town stock

+
+ +
`; + return `

Caravans

+ ${k.caravans.map(row).join("")}${waiting} + ${k.caravans.length || k.freight.length ? "" : `

None on the road

`} + ${forming} +
`; } function warTable() { @@ -950,9 +1016,11 @@ function warTable() { const proposal = (p) => { const open = p.status === "open", mine = p.yes.includes(S.uid) ? "yes" : p.no.includes(S.uid) ? "no" : null; const result = { sent: "๐Ÿ›ค๏ธ Sent", rejected: "Kept home", failed: "No guards" }[p.status]; - return `
๐Ÿ’‚ ${fmt(p.guards)} ยท ${esc(townName(p.from))} โ†’ ${esc(townName(p.to))} ยท ${esc(playerName(p.by))} + const freight = p.items ? Object.entries(p.items).map(([id, qty]) => itemChip(id, qty, undefined, false)).join(" ") : null; + return `
${freight ? `๐Ÿ“ฆ ${freight}` : `๐Ÿ’‚ ${fmt(p.guards)}`} ยท ${esc(townName(p.from))} โ†’ ${esc(townName(p.to))} ยท ${esc(playerName(p.by))} โœ… ${p.yes.length} โŒ ${p.no.length}${open ? ` ยท โณ ${dur(Math.max(0, p.ends - S.now))}` : ` ยท ${result}`} - ${open ? ` ` : ""}
`; + ${open ? ` ` : ""}
+ ${open && !p.items ? marchImpact(p.from, p.to, p.guards) : ""}`; }; const march = (m) => { const target = k.cities.find((c) => c.id === m.to); @@ -969,6 +1037,7 @@ function warTable() {
โ†’
+ ${marchImpact($("[data-keep=march-from]")?.value || home, $("[data-keep=march-to]")?.value || other, Number($("[data-keep=march-guards]")?.value ?? 10))}

๐Ÿ›ค๏ธ ${dur(C.march_time / S.city_speed)} ยท vote ${dur(C.vote_time / S.city_speed)} ยท one fight, then home

`; } @@ -990,8 +1059,8 @@ function kingdom() { const region = k.regions[c.region]; return `

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

-

${esc(c.tier)} ยท ๐Ÿ‘ฅ ${fmt(c.population)} ยท ๐Ÿ† ${fmt(c.repelled)}${road ? ` ยท ๐Ÿ›ค๏ธ ${road}` : ""}

- ${threatLine(c.threat)} +

${esc(c.tier)} ยท ๐Ÿ‘ฅ ${fmt(c.population)} ยท ๐Ÿ† ${fmt(c.repelled)}${road ? ` ยท ๐Ÿšถ ${road}` : ""}${c.roads ? ` ยท ๐Ÿ›ค๏ธ ${c.roads}` : ""}

+ ${threatLine(c.threat, c.problems)}

๐Ÿ›ก๏ธ ${fmt(c.defence)} ยท ๐Ÿ’‚ ${fmt(c.guards)} / ${fmt(c.posts - c.away)}${c.away ? ` ยท ๐Ÿ›ค๏ธ ${fmt(c.away)}` : ""}${c.garrison.length ? ` ยท ๐Ÿฐ ${c.garrison.map((uid) => esc(playerName(uid))).join(", ")}` : ""}

${region ? `

${region.icon} ${esc(region.name)} ยท ${regionPerks(region, c.town_scale)}

` : ""}

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

@@ -1025,7 +1094,7 @@ function kingdom() {

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

${pack}

Found a town

${founding}
- ${k.cities.length > 1 ? warTable() : ""}`; + ${k.cities.length > 1 ? warTable() + convoyPanel() : ""}`; } // Where an item comes from: the recipe that makes it, else what finds it, else the fight that drops it. @@ -3387,6 +3456,32 @@ 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 ("cargoAdd" in d) { + const id = $("[data-keep^=cargo-item]").value, qty = Math.min(Number($("[data-keep=cargo-qty]").value) || 0, S.me.bank[id] || 0); + if (id && qty > 0) cargo[id] = qty; + return render(); + } + if (d.cargoDrop) { delete cargo[d.cargoDrop]; return render(); } + if (d.cargoFreight) { + const id = Number(d.cargoFreight); + if (cargoFreight.has(id)) cargoFreight.delete(id); else cargoFreight.add(id); + return render(); + } + if ("caravanForm" in d || d.caravanJoin || d.caravanLoad) { + const body = { goods: cargo, freight: [...cargoFreight] }; + cargo = {}; + cargoFreight.clear(); + if ("caravanForm" in d) return act("/api/caravan/form", { ...body, to: $("[data-keep=caravan-to]").value }); + return act("/api/caravan/board", { ...body, id: Number(d.caravanJoin || d.caravanLoad) }); + } + if (d.caravanDepart) { + if (!confirm("Set off? Everyone aboard stops work until it arrives.")) return; + return act("/api/caravan/depart", { id: Number(d.caravanDepart) }); + } + if (d.caravanCancel) return act("/api/caravan/cancel", { id: Number(d.caravanCancel) }); + if ("freightPropose" in d) { + return act("/api/council/freight", { to: $("[data-keep=freight-to]").value, item: $("[data-keep=freight-item]").value, qty: Number($("[data-keep=freight-qty]").value) }); + } if ("marchPropose" in d) { return act("/api/council/propose", { from: $("[data-keep=march-from]").value, to: $("[data-keep=march-to]").value, guards: Number($("[data-keep=march-guards]").value) }); } @@ -3468,7 +3563,12 @@ function pickOrderItem(id) { draft.reward = draft.item && !draft.city ? item(draft.item).value * (draft.kind === "craft" ? draft.qty : 1) : 0; } +document.addEventListener("change", (e) => { + if (e.target.matches?.("[data-keep^=march-], [data-keep=caravan-to]")) render(); +}); + document.addEventListener("input", (e) => { + if (e.target.matches?.("[data-keep=march-guards]")) render(); if (e.target.dataset.keep !== "order-search" || !draft) return; draft.search = e.target.value; render(); diff --git a/static/icons.svg b/static/icons.svg index 519bce9..15a769f 100644 --- a/static/icons.svg +++ b/static/icons.svg @@ -252,6 +252,7 @@ + diff --git a/static/styles.css b/static/styles.css index fd44e2e..1ff53a2 100644 --- a/static/styles.css +++ b/static/styles.css @@ -958,3 +958,4 @@ button.swatch { width: 36px; height: 36px; } .council-row { display: grid; grid-template-columns: minmax(0, 1fr) auto auto; gap: 10px; align-items: center; padding: 6px 0; border-bottom: 1px solid rgba(255, 255, 255, .06); } @media (max-width: 520px) { .council-row { grid-template-columns: minmax(0, 1fr) auto; } } .pouch-row select.wide { flex-basis: 100%; } +.impact { display: flex; flex-wrap: wrap; gap: 4px 18px; padding: 6px 0; } diff --git a/tests/test_game.py b/tests/test_game.py index 4f52280..6a08caf 100644 --- a/tests/test_game.py +++ b/tests/test_game.py @@ -4126,6 +4126,261 @@ class KingdomTest(unittest.TestCase): game._loot_banks(new, {"slot": 5}, 0.4, T0) self.assertEqual(self.a["bank"]["stone"], 900) + def caravan(self, new, goods=None, freight=(), now=T0): + self.assertIsNone(game.form_caravan(self.world, self.a, new.here, goods or {}, list(freight), now)) + return self.world["convoys"][-1] + + def raid_on(self, world, strength=1000.0, at=T0 + 10**6): + raid = {"id": 900 + len(world["events"]), "kind": "raid", "status": "upcoming", "fire_at": at, "slot": at, "strength": strength, + "sabotage": 0.0, "recon": 0, "jitter": 0, "group": "the Red Hand", "trait": "x", "announced": T0} + world["events"].append(raid) + return raid + + def test_a_caravan_carries_your_goods_to_your_bank_there(self): + new = self.found() + self.a["bank"] = {"stone": 1000} + convoy = self.caravan(new, {"stone": 800}) + self.assertEqual(self.a["bank"]["stone"], 200) + self.assertEqual(convoy["status"], "loading") + self.assertIsNone(game.depart_caravan(self.world, self.a, convoy["id"], T0)) + arrive = convoy["arrive"] + self.assertEqual(arrive, T0 + game.CARAVAN_TIME) + convoy["rolled"] = True + game.tick(self.world, arrive, random.Random(1)) + game.catch_up(self.world, arrive, random.Random(1)) + self.assertEqual(self.a["at"], new.here) + self.assertEqual(self.a["bank"]["stone"], 800) + self.assertEqual(self.a["banks"][game.HOME_CITY]["stone"], 200) + self.assertEqual(self.world["convoys"], []) + + def test_the_crew_stops_work_on_the_road(self): + new = self.found() + self.assertIsNone(game.start_action(self.world, self.a, "mine_stone", T0)) + convoy = self.caravan(new) + game.depart_caravan(self.world, self.a, convoy["id"], T0) + xp = self.a["xp"]["mining"] + game.process_player(self.world, self.a, convoy["arrive"] - 1) + self.assertEqual(self.a["xp"]["mining"], xp) + + def test_more_crew_means_more_load(self): + new = self.found() + self.a["bank"], self.b["bank"] = {"stone": 5000}, {"stone": 5000} + limit = game.CARAVAN_LOAD + self.assertIn("hold", game.form_caravan(self.world, self.a, new.here, {"stone": limit + 1}, [], T0)) + convoy = self.caravan(new, {"stone": limit}) + self.assertIn("hold", game.board_caravan(self.world, self.b, convoy["id"], {"stone": limit + 1}, [], T0)) + self.assertIsNone(game.board_caravan(self.world, self.b, convoy["id"], {"stone": limit}, [], T0)) + self.assertEqual(convoy["crew"], ["a", "b"]) + self.assertEqual(game._convoy_load(convoy), 2 * limit) + + def test_road_works_at_either_end_help(self): + new = self.found() + bare = game.caravan_route(self.world, game.HOME_CITY, new.here) + self.world["city"]["buildings"]["roads"]["level"] = 3 + new["city"]["buildings"]["roads"]["level"] = 1 + paved = game.caravan_route(self.world, game.HOME_CITY, new.here) + self.assertEqual(paved["level"], 4) + self.assertAlmostEqual(paved["time"], bare["time"] * 0.6) + self.assertEqual(paved["load"], bare["load"] * 2) + self.assertAlmostEqual(paved["odds"], bare["odds"] * 0.6) + + def test_roads_dont_speed_up_guards(self): + new = self.found() + self.garrisoned_home() + self.world["city"]["buildings"]["roads"]["level"] = 3 + march = self.march(new) + self.assertEqual(march["arrive"], T0 + game.MARCH_TIME) + + def test_town_stock_needs_the_council(self): + new = self.found() + self.a["last_active"] = self.b["last_active"] = T0 + stock = self.world["city"]["stockpile"] + self.assertIn("holds", game.propose_freight(self.world, self.a, new.here, "provisions", 10**6, T0)) + self.assertIsNone(game.propose_freight(self.world, self.a, new.here, "provisions", 100, T0)) + proposal = self.world["council"][-1] + self.assertEqual((proposal["status"], stock["provisions"]), ("open", 300)) + game.vote_march(self.world, self.b, proposal["id"], True, T0) + self.assertEqual((proposal["status"], stock["provisions"]), ("sent", 200)) + self.assertEqual(self.world["freight"][0]["items"], {"provisions": 100}) + + def ship(self, new, qty=100): + self.a["last_active"] = self.b["last_active"] = T0 + game.propose_freight(self.world, self.a, new.here, "provisions", qty, T0) + game.vote_march(self.world, self.b, self.world["council"][-1]["id"], True, T0) + return self.world["freight"][-1] + + def test_a_caravan_delivers_town_stock_and_earns_its_crew_favour_there(self): + new = self.found() + shipment = self.ship(new) + convoy = self.caravan(new, freight=[shipment["id"]]) + self.assertEqual(self.world["freight"], []) + game.depart_caravan(self.world, self.a, convoy["id"], T0) + convoy["rolled"] = True + before = new["city"]["stockpile"]["provisions"] + self.a["favour"] = 0 + game.tick(self.world, convoy["arrive"], random.Random(1)) + self.assertEqual(new["city"]["stockpile"]["provisions"], before + 100) + game.catch_up(self.world, convoy["arrive"], random.Random(1)) + self.assertEqual(self.a["favour"], game.ITEMS["provisions"]["value"] * 100 * game.CARRIAGE) + + def test_too_much_freight_leaves_the_rest_waiting(self): + new = self.found() + self.world["city"]["stockpile"]["provisions"] = game.CARAVAN_LOAD + 500 + shipment = self.ship(new, game.CARAVAN_LOAD + 500) + convoy = self.caravan(new, freight=[shipment["id"]]) + self.assertEqual(convoy["freight"]["provisions"], game.CARAVAN_LOAD) + self.assertEqual(self.world["freight"][0]["items"]["provisions"], 500) + + def test_unclaimed_freight_goes_home(self): + new = self.found() + self.ship(new) + stock = self.world["city"]["stockpile"] + game._caravan_road_tick(self.world, T0 + game.FREIGHT_WAIT, random.Random(1)) + self.assertEqual(stock["provisions"], 300) + self.assertEqual(self.world["freight"], []) + + def test_calling_off_a_caravan_gives_it_all_back(self): + new = self.found() + self.a["bank"] = {"stone": 100} + shipment = self.ship(new) + convoy = self.caravan(new, {"stone": 50}, [shipment["id"]]) + self.assertIn("isn't yours", game.cancel_caravan(self.world, self.b, convoy["id"])) + self.assertIsNone(game.cancel_caravan(self.world, self.a, convoy["id"])) + self.assertEqual(self.a["bank"]["stone"], 100) + self.assertEqual(self.world["freight"][0]["items"], {"provisions": 100}) + + def test_a_caravan_that_never_leaves_unloads(self): + new = self.found() + self.a["bank"] = {"stone": 100} + self.caravan(new, {"stone": 100}) + game.tick(self.world, T0 + game.CARAVAN_WAIT, random.Random(1)) + self.assertEqual(self.world["convoys"], []) + self.assertEqual(self.a["bank"]["stone"], 100) + + def test_who_left_town_stays_behind_with_their_goods(self): + new = self.found() + self.b["bank"] = {"stone": 100} + convoy = self.caravan(new) + game.board_caravan(self.world, self.b, convoy["id"], {"stone": 100}, [], T0) + self.go(self.b, new.here) + self.assertIsNone(game.depart_caravan(self.world, self.a, convoy["id"], T0)) + self.assertEqual(convoy["crew"], ["a"]) + self.assertEqual(self.b["banks"].get(game.HOME_CITY, self.b["bank"])["stone"], 100) + + def ambushed(self, new, power, raid, cargo=None): + self.a["bank"] = {"stone": 1000} + convoy = self.caravan(new, cargo or {}) + game.depart_caravan(self.world, self.a, convoy["id"], T0) + convoy["odds"] = 1.0 + self.a["xp"]["combat"] = power + game._ambush(self.world, convoy, T0, random.Random(1)) + return convoy + + def test_beating_an_ambush_weakens_the_coming_raid(self): + new = self.found() + raid = self.raid_on(self.world, 100.0) + convoy = self.ambushed(new, 10**7, raid, {"stone": 1000}) + self.assertEqual(convoy["ambush"], "won") + self.assertEqual(raid["sabotage"], game.AMBUSH_WEAKEN) + self.assertEqual(convoy["goods"]["a"]["stone"], 1000) + + def test_losing_an_ambush_costs_cargo_and_feeds_the_raid(self): + new = self.found() + raid = self.raid_on(self.world, 100000.0) + convoy = self.ambushed(new, 0, raid, {"stone": 1000}) + self.assertEqual(convoy["ambush"], "lost") + self.assertEqual(convoy["goods"]["a"]["stone"], 700) + self.assertEqual(raid["strength"], 102000.0) + self.assertEqual(raid["sabotage"], 0.0) + + def test_the_ambush_comes_from_the_bigger_raid(self): + new = self.found() + small, big = self.raid_on(new, 10.0), self.raid_on(self.world, 1000.0) + self.ambushed(new, 10**7, big) + self.assertEqual((small["sabotage"], big["sabotage"]), (0.0, game.AMBUSH_WEAKEN)) + + def test_an_empty_wagon_isnt_worth_robbing(self): + new = self.found() + self.raid_on(self.world, 1000.0) + convoy = self.caravan(new) + game.depart_caravan(self.world, self.a, convoy["id"], T0) + self.assertEqual(convoy["odds"], 0.0) + + def test_fuller_wagons_draw_more_ambushes(self): + new = self.found() + self.a["bank"] = {"stone": game.CARAVAN_LOAD} + convoy = self.caravan(new, {"stone": game.CARAVAN_LOAD // 2}) + game.depart_caravan(self.world, self.a, convoy["id"], T0) + self.assertAlmostEqual(convoy["odds"], game.AMBUSH_ODDS / 2) + + def test_only_so_many_ambushes_count_for_one_raid(self): + new = self.found() + raid = self.raid_on(self.world, 100.0) + self.a["xp"]["combat"] = 10**7 + for _ in range(game.AMBUSH_MOST + 3): + convoy = {"from": game.HOME_CITY, "to": new.here, "crew": ["a"], "goods": {}, "freight": {}, "odds": 1.0} + game._ambush(self.world, convoy, T0, random.Random(1)) + self.assertAlmostEqual(raid["sabotage"], game.AMBUSH_MOST * game.AMBUSH_WEAKEN) + + def test_no_raid_no_ambush(self): + new = self.found() + convoy = self.ambushed(new, 0, None, {"stone": 1000}) + self.assertNotIn("ambush", convoy) + + def test_a_second_crew_member_can_win_an_ambush_one_would_lose(self): + new = self.found() + for member in (self.a, self.b): + member["xp"]["combat"] = game.XP_TABLE[50] + solo = game.combat_power(self.a) + results = [] + for crew in (1, 2): + raid = self.raid_on(self.world, 1.5 * solo / game.AMBUSH_SHARE) + convoy = self.caravan(new) + if crew == 2: + game.board_caravan(self.world, self.b, convoy["id"], {}, [], T0) + game.depart_caravan(self.world, self.a, convoy["id"], T0) + convoy["odds"] = 1.0 + game._ambush(self.world, convoy, T0, random.Random(5)) + results.append(convoy["ambush"]) + self.world["events"].remove(raid) + self.world["convoys"].remove(convoy) + for member in (self.a, self.b): + member["travel"] = None + self.assertEqual(results, ["lost", "won"]) + + def test_the_curve_matches_a_real_march(self): + new = self.found() + self.garrisoned_home() + curve = game.march_curve(self.world) + before = game.defence(self.world)["total"] + march = self.march(new, 30) + self.assertAlmostEqual(curve[30], game.march_power(march), delta=1) + self.assertAlmostEqual(before - game.defence(self.world)["total"], curve[30], delta=1) + self.assertEqual(curve[0], 0.0) + + def test_the_war_table_shows_scouted_threats_at_their_level(self): + new = self.found() + game.tick(self.world, T0 + 13 * game.HOUR, random.Random(4)) + game.tick(self.world, T0 + 13 * game.HOUR + 1, random.Random(4)) + view = game.kingdom_view(self.world, T0 + 13 * game.HOUR + 1, "a") + far = next(c for c in view["cities"] if c["id"] == new.here) + self.assertEqual(far["threat"]["intel"], 0) + self.assertNotIn("strength", far["threat"]) + self.assertNotIn("range", far["threat"]) + raid = game.upcoming_raid(new) + raid["recon"] = 10**6 + now = raid["fire_at"] - 3600 + far = next(c for c in game.kingdom_view(self.world, now, "a")["cities"] if c["id"] == new.here) + self.assertEqual(far["threat"]["intel"], 3) + self.assertEqual(far["threat"]["strength"], round(raid["strength"])) + self.assertIn("group", far["threat"]) + + def test_minor_troubles_show_on_the_war_table(self): + new = self.found() + new["city"]["problems"].append({"kind": "wolves", "work": 0}) + far = next(c for c in game.kingdom_view(self.world, T0, "a")["cities"] if c["id"] == new.here) + self.assertEqual(far["problems"][0]["name"], game.PROBLEMS["wolves"]["name"]) + def test_old_saves_gain_towns(self): doc = json.loads(json.dumps(self.world.doc)) doc["version"] = 39