files-game/engine/state.gd
2026-10-01 23:01:56 -04:00

593 lines
18 KiB
GDScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

class_name State
## Small helpers for reading and changing a game state (state.ts). Nothing here knows about
## individual cards, so both the engine and the card scripts can use it.
##
## A state `s` is the TS GameState as Dictionaries and Arrays, with the same keys. An Anomaly ref
## is {player, slot}: slots 1–4 are the printed Anomalies and slot k + 4 is the copy of Anomaly k.
static func other(p: int) -> int:
return 1 if p == 0 else 0
static func def_of(s: Dictionary, id: int) -> Dictionary:
return s.defs[s.cards[id].name]
static func name_of(s: Dictionary, id: int) -> String:
return "a hidden card" if id < 0 else s.cards[id].name
static func owner_of(s: Dictionary, id: int) -> int:
return s.cards[id].owner
static func controls(s: Dictionary, p: int, loc: String) -> bool:
return s.locations[loc].owner == p
static func is_open(s: Dictionary, line: Dictionary) -> bool:
return not s.firewalls.get(line.id, 0)
## Bandwidth to place, upgrade to, or clear a Firewall of `level`, before discounts; 0 for no Firewall.
static func firewall_cost(s: Dictionary, level: int) -> int:
var costs: Array = s.rules.firewallCost
return costs[level - 1] if level >= 1 and level <= costs.size() else 0
static func grid_count(s: Dictionary, p: int) -> int:
var n := 0
for loc in GameMap.GRID:
if controls(s, p, loc):
n += 1
return n
## Rolls a d6 (or takes the next rigged result).
static func roll_die(s: Dictionary) -> int:
var rigged = s.get("rigged")
if rigged != null and not rigged.is_empty():
return rigged.pop_front()
return Rng.d6(s.rng)
## Adds a line to the play-by-play. `meta` tags what it's about; give `to` and `public` when the
## line names cards only one player may see, and the other player reads `public` instead. Null
## values are left out, as TS leaves out undefined ones.
static func say(s: Dictionary, msg: String, meta := {}) -> void:
if s.log == null:
return
var line := {"text": msg}
for k in meta:
if meta[k] != null:
line[k] = meta[k]
s.log.append(line)
## Records what just happened for the table to act out (godot-plan.md §3): `ev` is {k: kind, ...}.
## Only a game made with `events` keeps them; TS has no events, so they stay out of conformance.
static func emit(s: Dictionary, ev: Dictionary) -> void:
var events = s.get("events")
if events != null:
events.append(ev)
## Whether this game records events, to skip building ones nobody keeps.
static func has_events(s: Dictionary) -> bool:
return s.get("events") != null
## Events from index `from` as `viewer` may see them: copies, with cards they can't see as -1 (the
## other player's draws, and cards the other player takes into hand from a hidden pile).
static func events_for(s: Dictionary, viewer: int, from := 0) -> Array:
var out := []
var events = s.get("events")
if events == null:
return out
for i in range(maxi(0, from), events.size()):
var ev: Dictionary = events[i].duplicate(true)
var theirs: bool = ev.get("p", viewer) != viewer
if theirs and (ev.k == "drew" or (ev.k == "hand" and ev.get("from") in ["deck", "serverPile", ""])):
ev.card = -1
elif theirs and ev.k == "pile" and ev.get("from") == "hand":
ev.card = -1
out.append(ev)
return out
## Folded Bandwidth events must equal the Bandwidth: when a change slipped past the helpers, one more
## event makes up the difference. `before` is each player's Bandwidth at event `from`. Counted in
## event_fixes, which tests expect to stay 0.
static var event_fixes := 0
static func reconcile_bandwidth(s: Dictionary, before: Array, from: int) -> void:
var events = s.get("events")
if events == null:
return
var have := before.duplicate()
for i in range(from, events.size()):
var ev: Dictionary = events[i]
if ev.k == "bandwidth":
have[ev.p] = ev.to
for p in 2:
if have[p] != s.players[p].bandwidth:
event_fixes += 1
emit(s, {"k": "bandwidth", "p": p, "from": have[p], "to": s.players[p].bandwidth})
## The play-by-play as `viewer` may read it, or every line in full for null.
static func log_for(s: Dictionary, viewer: Variant) -> Array:
var out := []
for l in (s.log if s.log != null else []):
if viewer == null or not l.has("to") or l.to == viewer:
out.append(l.text)
else:
out.append(l.get("public", ""))
return out
static func stat(s: Dictionary, key: String, p: int, n := 1) -> void:
s.stats[key][p] += n
static func _use(s: Dictionary, card_name: String) -> Dictionary:
if not s.cardUse.has(card_name):
s.cardUse[card_name] = {"played": [0, 0], "fired": [0, 0]}
return s.cardUse[card_name]
## Counts a card being played, installed or activated.
static func played(s: Dictionary, card_name: String, p: int) -> void:
_use(s, card_name).played[p] += 1
## Counts a card's effect happening.
static func fired(s: Dictionary, card_name: String, p: int) -> void:
_use(s, card_name).fired[p] += 1
# ---------------------------------------------------------------------------------------------
# Time
static func end_of_turn(s: Dictionary) -> int:
return 2 * s.turn + 1
static func start_of(turn: int) -> int:
return 2 * turn
static func end_of(turn: int) -> int:
return 2 * turn + 1
## The turn number of `p`'s next turn (not the current one). Under the command rule, their next command.
static func next_turn_of(s: Dictionary, p: int) -> int:
if not s.rules.commands.on:
return s.turn + 2 if s.active == p else s.turn + 1
var t: int = s.turn + 1
while commander_of(s, t) != p:
t += 1
return t
# Command rule: game turns are commands. A round is 2 × perPlayer of them, alternating players,
# and the lead alternates by round.
static func _commands_per_round(s: Dictionary) -> int:
return 2 * s.rules.commands.perPlayer
## Command rule: who takes game turn `turn`.
static func commander_of(s: Dictionary, turn: int) -> int:
var leads: String = s.rules.commands.leads
var snake: bool = s.rules.commands.snake
var per := _commands_per_round(s)
var round_no := Util.floordiv(turn - 1, per)
var i := (turn - 1) % per
var mark := ""
if leads == "thue":
mark = "FS"[Util.popcount(round_no) % 2]
else:
mark = leads[posmod(round_no, leads.length())]
if mark != "F" and mark != "S":
Util.fail("commands.leads should use F and S, or be \"thue\": \"%s\"" % leads)
var lead: int = s.firstPlayer if mark == "F" else other(s.firstPlayer)
var leads_this := (i % 4 == 0 or i % 4 == 3) if snake else i % 2 == 0
return lead if leads_this else other(lead)
## Command rule: the round game turn `turn` belongs to, from 1.
static func round_of(s: Dictionary, turn: int) -> int:
return Util.floordiv(turn - 1, _commands_per_round(s)) + 1
## Command rule: whether `turn` is its commander's first command of the round.
static func first_command(s: Dictionary, turn: int) -> bool:
return (turn - 1) % _commands_per_round(s) < 2
## Rounds played so far: both players taking a turn (or all their commands).
static func rounds_played(s: Dictionary) -> int:
return round_of(s, s.turn) if s.rules.commands.on else ceili(s.turn / 2.0)
static func running(s: Dictionary, until: int) -> bool:
return until > s.clock
## Once-per-turn bookkeeping. Returns how many times `key` was used this turn.
static func used_this_turn(s: Dictionary, key: String) -> int:
return s.used.get(key, 0)
static func mark_used(s: Dictionary, key: String) -> void:
s.used[key] = s.used.get(key, 0) + 1
# ---------------------------------------------------------------------------------------------
# Anomalies
static func ref(p: int, slot: int) -> Dictionary:
return {"player": p, "slot": slot}
static func ref_key(r: Dictionary) -> String:
return "%d:%d" % [r.player, r.slot]
static func same_ref(a: Variant, b: Variant) -> bool:
return a != null and b != null and a.player == b.player and a.slot == b.slot
static func anomaly(s: Dictionary, r: Dictionary) -> Dictionary:
return s.players[r.player].anomalies[r.slot - 1]
static func is_copy(r: Dictionary) -> bool:
return r.slot > 4
## The printed Anomaly a ref belongs to (a copy's original).
static func original_of(r: Dictionary) -> Dictionary:
return ref(r.player, r.slot - 4) if r.slot > 4 else r
static func copy_of(r: Dictionary) -> Dictionary:
return ref(r.player, original_of(r).slot + 4)
static func in_play(s: Dictionary, r: Dictionary) -> bool:
return anomaly(s, r).at != null
static func anomaly_def(s: Dictionary, r: Dictionary) -> Dictionary:
return def_of(s, anomaly(s, r).card)
static func anomaly_name(s: Dictionary, r: Dictionary) -> String:
var n: int = original_of(r).slot
var card: int = anomaly(s, r).card
var nm := "?" if card < 0 else name_of(s, card)
return ("the copy of Anomaly %d (%s)" if is_copy(r) else "Anomaly %d (%s)") % [n, nm]
## Every Anomaly of `p` in play, originals first.
static func refs_in_play(s: Dictionary, p: int) -> Array:
var out := []
var avs: Array = s.players[p].anomalies
for i in avs.size():
if avs[i].at != null:
out.append(ref(p, i + 1))
return out
## Anomalies standing on `loc`. Only the location's owner can have Anomalies there.
static func anomalies_at(s: Dictionary, loc: String) -> Array:
var owner = s.locations[loc].owner
if owner == null:
return []
return refs_in_play(s, owner).filter(func(r): return anomaly(s, r).at == loc)
static func defenders_at(s: Dictionary, loc: String) -> Array:
return anomalies_at(s, loc)
## Hardware that counts for an Anomaly. A copy uses its original's Hardware.
static func hardware_of(s: Dictionary, r: Dictionary) -> Array:
return anomaly(s, original_of(r)).hardware
## The Anomaly wearing a Hardware card, if it's installed.
static func wearer_of(s: Dictionary, hw: int) -> Variant:
var p := owner_of(s, hw)
var avs: Array = s.players[p].anomalies
for i in avs.size():
if avs[i].hardware.has(hw):
return ref(p, i + 1)
return null
static func is_rooted(s: Dictionary, r: Dictionary) -> bool:
return running(s, anomaly(s, r).rootedUntil)
static func is_disabled_anomaly(s: Dictionary, r: Dictionary) -> bool:
return running(s, anomaly(s, r).disabledUntil)
## Copy-rule variant: a copy made this player-turn can't advance or attack yet. It can still defend.
static func fresh_copy(s: Dictionary, r: Dictionary) -> bool:
return is_copy(r) and s.rules.copies.waitATurn and anomaly(s, r).createdTurn == s.turn
## Can act: advance, attack, move, use its Ability.
static func can_act(s: Dictionary, r: Dictionary) -> bool:
return in_play(s, r) and not is_rooted(s, r) and not is_disabled_anomaly(s, r)
## Temporary modifiers that currently apply to an Anomaly.
static func active_mods(s: Dictionary, av: Dictionary) -> Array:
return av.mods.filter(func(m):
if m.has("combat"):
return s.combat != null and s.combat.id == m.combat
return running(s, m.get("until", 0)))
## Adds a temporary Core modifier. `scope` is {combat: id} or {until: clock}.
static func add_mod(s: Dictionary, r: Dictionary, cores: int, source: String, by: int, scope: Dictionary) -> void:
s.seq += 1
var m := {"seq": s.seq, "cores": cores, "source": source, "by": by}
m.merge(scope)
anomaly(s, r).mods.append(m)
static func infection_of(av: Dictionary) -> int:
return av.infection + av.permanentInfection
# ---------------------------------------------------------------------------------------------
# Combat
static func in_combat(s: Dictionary, r: Dictionary) -> bool:
var c = s.combat
if c == null or c.ended:
return false
if same_ref(c.attacker, r):
return true
for d in c.defenders:
if same_ref(d, r):
return true
return false
## The other side of the current combat from `r`'s point of view.
static func opponents_in_combat(s: Dictionary, r: Dictionary) -> Array:
var c = s.combat
if c == null or c.ended:
return []
if same_ref(c.attacker, r):
return c.defenders.duplicate()
for d in c.defenders:
if same_ref(d, r):
return [c.attacker]
return []
static func fighters_of(c: Dictionary) -> Array:
return [c.attacker] + c.defenders
## Anomalies "at" a location for card text: the ones standing there, plus an enemy attacking it in
## the current combat.
static func at_server(s: Dictionary, loc: String) -> Array:
var out := anomalies_at(s, loc)
var c = s.combat
if c != null and not c.ended and c.loc == loc:
var found := false
for r in out:
if same_ref(r, c.attacker):
found = true
if not found:
out.append(c.attacker)
return out
# ---------------------------------------------------------------------------------------------
# Map
## Locations joined to `loc` by a line with no Firewall.
static func neighbors(s: Dictionary, loc: String) -> Array:
var out := []
for l in GameMap.LINES_AT[loc]:
if is_open(s, l):
out.append(GameMap.other_end(l, loc))
return out
static func adjacent(s: Dictionary, a: String, b: String) -> bool:
return neighbors(s, a).has(b)
# ---------------------------------------------------------------------------------------------
# Cards moving between zones
## Clears play-time status when a card leaves play.
static func reset_card(s: Dictionary, id: int) -> void:
var c: Dictionary = s.cards[id]
c.disabledUntil = 0
c.ignoredUntil = 0
c.erase("wormTo")
c.erase("protects")
c.erase("copies")
c.erase("spent")
c.erase("pushedUntil")
## `from` and `why` only describe the move for events: from "hand", "play" (a location's Server or
## Program), "worn" (Hardware), "stack", "slot" or "deck"; why "salvage", "played", "destroyed",
## "captured", "discarded", ….
static func to_discard(s: Dictionary, id: int, from := "", why := "") -> void:
reset_card(s, id)
s.players[owner_of(s, id)].discard.append(id)
if has_events(s):
emit(s, {"k": "discard", "p": owner_of(s, id), "card": id, "from": from, "why": why})
static func to_hand(s: Dictionary, id: int, from := "") -> void:
reset_card(s, id)
s.players[owner_of(s, id)].hand.append(id)
if has_events(s):
emit(s, {"k": "hand", "p": owner_of(s, id), "card": id, "from": from})
## A Server, Program or Hardware card arriving on a location ("loc:C2") or an Anomaly
## ("anomaly:0:1"), for events.
static func emit_install(s: Dictionary, id: int, at: String) -> void:
if has_events(s):
emit(s, {"k": "install", "p": owner_of(s, id), "card": id, "at": at})
## A card going into its owner's deck or Server pile ("deck", "serverPile"), for events.
static func emit_pile(s: Dictionary, id: int, zone: String, from: String) -> void:
if has_events(s):
emit(s, {"k": "pile", "p": owner_of(s, id), "card": id, "zone": zone, "from": from})
static func emit_moved(s: Dictionary, r: Dictionary, from: Variant, to: Variant) -> void:
if not has_events(s) or from == to:
return
if from == null:
emit(s, {"k": "placed", "ref": r.duplicate(), "loc": to})
elif to == null:
emit(s, {"k": "recalled", "ref": r.duplicate(), "from": from})
else:
emit(s, {"k": "moved", "ref": r.duplicate(), "from": from, "to": to})
## The counters an Anomaly shows, for "counter" events: take them before a change and pass them to
## emit_counters after it.
static func counters_of(av: Dictionary) -> Dictionary:
return {"infection": infection_of(av), "bugs": av.bugs, "damage": av.damage}
static func emit_counters(s: Dictionary, r: Dictionary, before: Dictionary) -> void:
if not has_events(s):
return
var now := counters_of(anomaly(s, r))
for what in now:
if now[what] != before[what]:
emit(s, {"k": "counter", "ref": r.duplicate(), "what": what, "from": before[what], "to": now[what]})
static func remove_from(list: Array, id: int) -> bool:
var i := list.find(id)
if i < 0:
return false
list.remove_at(i)
return true
## Takes an installed Program off its location. Returns where it was, or null.
static func uninstall_program(s: Dictionary, id: int) -> Variant:
for loc in s.locations:
if remove_from(s.locations[loc].programs, id):
return loc
return null
static func uninstall_hardware(s: Dictionary, id: int) -> Variant:
var r = wearer_of(s, id)
if r != null:
remove_from(anomaly(s, r).hardware, id)
return r
static func program_location(s: Dictionary, id: int) -> Variant:
for loc in s.locations:
if s.locations[loc].programs.has(id):
return loc
return null
static func gain_bandwidth(s: Dictionary, p: int, n: int, key := "bandwidthFromEffects") -> void:
if n <= 0:
return
add_bandwidth(s, p, n)
stat(s, key, p, n)
## Changes a player's Bandwidth by `n` (negative to spend), with its event. No stats.
static func add_bandwidth(s: Dictionary, p: int, n: int) -> void:
var before: int = s.players[p].bandwidth
s.players[p].bandwidth = before + n
if n != 0 and has_events(s):
emit(s, {"k": "bandwidth", "p": p, "from": before, "to": before + n})
# ---------------------------------------------------------------------------------------------
# Tasks and choices
## Queues tasks to run next, in the order given.
static func push_tasks(s: Dictionary, tasks: Array) -> void:
var queue: Array = s.tasks
for i in range(tasks.size() - 1, -1, -1):
queue.push_front(tasks[i])
## Asks a player to choose. The game waits until they do.
static func ask(s: Dictionary, choice: Dictionary) -> void:
if s.choice != null:
Util.fail("Two choices at once: %s and %s" % [s.choice.kind, choice.kind])
return
if choice.options.is_empty():
Util.fail("Choice %s has no options" % choice.kind)
return
s.choice = choice
## Runs a script function after the current task, like a choice would.
static func later(card_name: String, fn: String, data: Variant = null) -> Dictionary:
return {"t": "call", "name": card_name, "fn": fn, "data": data}
static func _window(kind: String, priority: int, base: int) -> Dictionary:
return {"t": "window", "kind": kind, "priority": priority, "passes": 0, "base": base, "resolving": false}
static func start_combat(s: Dictionary, attacker: Dictionary, origin: String, loc: String, kind: String) -> Dictionary:
s.seq += 1
var combat := {
"id": s.seq,
"loc": loc,
"attacker": attacker,
"origin": origin,
"defenders": defenders_at(s, loc),
"kind": kind,
"dice": {},
"rolled": false,
"ended": false,
"suppressed": [],
"race": [null, null],
"ties": 0,
}
s.combat = combat
push_tasks(s, [
{"t": "combat", "stage": "start"},
_window("preRoll", attacker.player, s.stack.size()),
{"t": "combat", "stage": "roll"},
_window("postRoll", attacker.player, s.stack.size()),
{"t": "combat", "stage": "result"},
{"t": "combat", "stage": "end"},
])
return combat
static func push_capture(s: Dictionary, r: Dictionary, loc: String, how: String) -> void:
push_tasks(s, [{"t": "capture", "ref": r, "loc": loc, "stage": "hooks", "how": how}])
static func player_name(p: int) -> String:
return Types.PLAYER_NAMES[p]