Towns: found a second, travel with a pouch, banks per town, looted when it falls
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
11e4d98d49
commit
685aaa839e
3 changed files with 512 additions and 49 deletions
36
app.py
36
app.py
|
|
@ -201,8 +201,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 +227,9 @@ def roster(world: dict, now: float) -> list[dict]:
|
|||
return sorted(people, key=lambda p: -p["donated"])
|
||||
|
||||
|
||||
ROAD_ROUTES = ("/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 +307,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 +339,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 +356,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"), 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 +468,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 +632,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 +652,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||
"happenings": game.happenings_view(world, now),
|
||||
"history": history,
|
||||
"orders": world["orders"],
|
||||
"kingdom": game.kingdom_view(world, now),
|
||||
"threat_report": unseen and {"id": unseen["id"], "kind": unseen["kind"], "at": unseen["resolved"],
|
||||
"report": unseen["report"]},
|
||||
"players": roster(world, now),
|
||||
|
|
|
|||
318
game.py
318
game.py
|
|
@ -1684,9 +1684,15 @@ 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
|
||||
MAX_CITIES = 3
|
||||
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 +1739,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 +1763,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 +2031,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:
|
||||
|
|
@ -2347,6 +2382,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()
|
||||
|
|
@ -3427,6 +3463,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 +3777,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 +4243,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 +4427,10 @@ 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; what doesn't fit waits on the order,
|
||||
as it does while they're in another town."""
|
||||
if owner["at"] != world.here:
|
||||
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 +4532,140 @@ 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, 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 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 _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, "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["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"], "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),
|
||||
"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 +5104,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 +5155,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 +5283,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 +5323,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 +5331,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 +5418,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 +5526,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 +5545,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 +5623,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 +5642,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 +5706,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
|
||||
|
|
@ -5930,8 +6175,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":
|
||||
|
|
|
|||
|
|
@ -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,208 @@ 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):
|
||||
self.assertIsNone(game.propose_charter(self.world, self.a, name, 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", 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", 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_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()
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue