349 lines
10 KiB
GDScript
349 lines
10 KiB
GDScript
class_name LocalMatch
|
|
extends RefCounted
|
|
## The game controller for one person against the bot, in-process (app/src/match.ts). It holds the
|
|
## real state and runs the bot. The table only ever sees view() and picks moves from legal().
|
|
## Everything here is plain GDScript with no nodes, so tests can drive it headlessly.
|
|
##
|
|
## The bot's move is split in two so the table can run the thinking on a worker thread:
|
|
## bot_think() only reads the state, bot_apply() changes it. bot_step() does both.
|
|
|
|
signal changed
|
|
|
|
## When the game waits for you to respond to the bot: "combat" (in combat only), "all" or "never".
|
|
const STOPS: Array[String] = ["combat", "all", "never"]
|
|
const DEFAULT_OPTIONS := {"autoSkip": true, "stops": "combat", "checkInvariants": false}
|
|
|
|
var pool: Dictionary
|
|
## {seed, human, decks: [deck, deck], rules: ["K=V", ...], bot: GreedyParams-shaped Dictionary}
|
|
var setup: Dictionary
|
|
var rules: Dictionary
|
|
var human: int
|
|
var bot_side: int
|
|
var s: Dictionary
|
|
## Every action applied so far, as action keys (yours, the bot's and the automatic ones).
|
|
var actions: Array[String] = []
|
|
var options: Dictionary
|
|
## Invariant errors found, when checking is on.
|
|
var errors: Array[String] = []
|
|
## Set while a key is held: stop at the next response window whatever the stops setting says.
|
|
var hold_stop := false
|
|
## Every combat so far, the current or latest last. See _snap_combat for the shape.
|
|
var combats: Array = []
|
|
## Bumped on every change, so the table knows when to redraw.
|
|
var version := 0
|
|
|
|
var bot: Object
|
|
## End command: the game turn being ended, or -1.
|
|
var _ending := -1
|
|
var _view_cache := {"version": -1, "view": {}}
|
|
var _legal_cache := {"version": -1, "legal": []}
|
|
var _log_cache := {"version": -1, "lines": []}
|
|
|
|
|
|
## `bot` picks the bot's moves (a GreedyBot, RandomBot or anything with choose(view, actions, me)).
|
|
func _init(card_pool: Dictionary, match_setup: Dictionary, the_bot: Object, opts := {}) -> void:
|
|
pool = card_pool
|
|
setup = match_setup
|
|
rules = rules_from(setup.get("rules", []))
|
|
human = setup.human
|
|
bot_side = State.other(human)
|
|
options = DEFAULT_OPTIONS.duplicate()
|
|
options.merge(opts, true)
|
|
bot = the_bot
|
|
s = RulesEngine.create_game({"pool": pool, "decks": setup.decks, "seed": setup.seed, "rules": rules, "log": true, "events": true})
|
|
_settle()
|
|
|
|
|
|
## The rules from `K=V` overrides on the defaults.
|
|
static func rules_from(specs: Array) -> Dictionary:
|
|
var r := Rules.defaults()
|
|
for spec in specs:
|
|
if spec.strip_edges() != "":
|
|
r = Rules.with_rule(r, spec.strip_edges())
|
|
return r
|
|
|
|
|
|
## Random legal decks for both players, seeded like the sim's playGame.
|
|
static func random_decks(card_pool: Dictionary, seed: int, match_rules: Dictionary) -> Array:
|
|
return Play.deal(card_pool, seed, match_rules)
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------------
|
|
# Reading
|
|
|
|
func is_over() -> bool:
|
|
return s.over
|
|
|
|
|
|
func decider() -> Variant:
|
|
return RulesEngine.decider(s)
|
|
|
|
|
|
func human_to_act() -> bool:
|
|
return RulesEngine.decider(s) == human
|
|
|
|
|
|
func bot_to_act() -> bool:
|
|
return RulesEngine.decider(s) == bot_side
|
|
|
|
|
|
## What the human may see. Read-only.
|
|
func view() -> Dictionary:
|
|
if _view_cache.version != version:
|
|
_view_cache = {"version": version, "view": RulesEngine.view_for(s, human)}
|
|
return _view_cache.view
|
|
|
|
|
|
## Your legal moves, or none while the bot decides.
|
|
func legal() -> Array:
|
|
if not human_to_act():
|
|
return []
|
|
if _legal_cache.version != version:
|
|
_legal_cache = {"version": version, "legal": RulesEngine.legal_actions(s)}
|
|
return _legal_cache.legal
|
|
|
|
|
|
## The play-by-play as you may read it.
|
|
func log_text() -> Array:
|
|
return State.log_for(s, human)
|
|
|
|
|
|
## Log lines with their tags, with private text swapped for what you may read. Read-only.
|
|
func log_lines() -> Array:
|
|
if _log_cache.version == version:
|
|
return _log_cache.lines
|
|
var text := log_text()
|
|
var out := []
|
|
var lines: Array = s.log if s.log != null else []
|
|
for i in lines.size():
|
|
var l: Dictionary = lines[i].duplicate()
|
|
l.text = text[i]
|
|
l.erase("to")
|
|
l.erase("public")
|
|
out.append(l)
|
|
_log_cache = {"version": version, "lines": out}
|
|
return out
|
|
|
|
|
|
## How many events the game has recorded (see State.emit): pass it to events_since() later.
|
|
func event_count() -> int:
|
|
return s.events.size() if s.events != null else 0
|
|
|
|
|
|
## Events from index `from` on, as you may see them (State.events_for). Copies.
|
|
func events_since(from: int) -> Array:
|
|
return State.events_for(s, human, from)
|
|
|
|
|
|
## The current or latest combat, or null.
|
|
func combat() -> Variant:
|
|
return combats.back() if not combats.is_empty() else null
|
|
|
|
|
|
func record() -> Dictionary:
|
|
return {"version": 1, "setup": setup, "actions": actions.duplicate()}
|
|
|
|
|
|
func ending_command() -> bool:
|
|
return _ending >= 0
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------------
|
|
# Acting
|
|
|
|
## Your move. It must be one of legal().
|
|
func act(a: Dictionary) -> void:
|
|
if not human_to_act():
|
|
Util.fail("It isn't your decision")
|
|
return
|
|
_ending = -1
|
|
_apply(a, legal())
|
|
_settle()
|
|
_changed()
|
|
|
|
|
|
## Ends steps until your command is over. Stops if a prompt or response window comes up for you.
|
|
func end_command() -> void:
|
|
if not human_to_act() or s.choice != null or RulesEngine.open_window(s) != null:
|
|
return
|
|
_ending = s.turn
|
|
_settle()
|
|
_changed()
|
|
|
|
|
|
## The bot's next move, without making it. Only reads the state, so it can run on a thread while
|
|
## nothing else changes the match.
|
|
func bot_think() -> Dictionary:
|
|
var lgl := RulesEngine.legal_actions(s)
|
|
var a: Dictionary = bot.choose(RulesEngine.view_for(s, bot_side), lgl, bot_side)
|
|
return {"action": a, "legal": lgl}
|
|
|
|
|
|
## Makes a move from bot_think(), if it's still the bot's decision.
|
|
func bot_apply(thought: Dictionary) -> bool:
|
|
if not bot_to_act():
|
|
return false
|
|
_apply(thought.action, thought.legal)
|
|
_settle()
|
|
_changed()
|
|
return true
|
|
|
|
|
|
## One bot move, if it's the bot's decision. Returns whether it moved.
|
|
func bot_step() -> bool:
|
|
if not bot_to_act():
|
|
return false
|
|
return bot_apply(bot_think())
|
|
|
|
|
|
## Runs the bot until you must decide or the game ends. For tests and instant bot speed.
|
|
func run_bot(limit := 100000) -> void:
|
|
var n := 0
|
|
while bot_to_act():
|
|
n += 1
|
|
if n > limit:
|
|
Util.fail("The bot made %d moves in a row" % limit)
|
|
return
|
|
bot_step()
|
|
|
|
|
|
func set_options(o: Dictionary) -> void:
|
|
options.merge(o, true)
|
|
_settle()
|
|
_changed()
|
|
|
|
|
|
## Re-checks automatic moves, e.g. after a held key is released.
|
|
func poke() -> void:
|
|
var before := actions.size()
|
|
_settle()
|
|
if actions.size() != before:
|
|
_changed()
|
|
|
|
|
|
func _changed() -> void:
|
|
version += 1
|
|
changed.emit()
|
|
|
|
|
|
func _apply(a: Dictionary, lgl: Array) -> void:
|
|
Flow.combat_watch = _watch
|
|
RulesEngine.apply_action(s, a, lgl)
|
|
Flow.combat_watch = Callable()
|
|
actions.append(RulesEngine.action_key(a))
|
|
version += 1
|
|
if options.checkInvariants:
|
|
for e in Invariants.check(s):
|
|
errors.append("Move %d (%s), turn %d: %s" % [actions.size(), RulesEngine.action_key(a), s.turn, e])
|
|
var last = combat()
|
|
if last != null and not last.done:
|
|
# A capture in combat can win the game before the combat's end stage.
|
|
if s.over:
|
|
last.stage = "end"
|
|
last.done = true
|
|
elif s.combat != null and s.combat.id == last.id:
|
|
combats[-1] = _snap_combat(last.stage)
|
|
|
|
|
|
## Makes the moves the settings make for you: skipping empty steps, passing, End command.
|
|
func _settle() -> void:
|
|
var guard := 0
|
|
while human_to_act():
|
|
guard += 1
|
|
if guard > 10000:
|
|
Util.fail("The automatic moves are stuck in a loop")
|
|
return
|
|
var auto = _automatic()
|
|
if auto == null:
|
|
break
|
|
_apply(auto, legal())
|
|
if _ending >= 0 and (s.over or s.turn != _ending):
|
|
_ending = -1
|
|
|
|
|
|
## The move the settings make for you now, if any.
|
|
func _automatic() -> Variant:
|
|
if s.choice != null:
|
|
_ending = -1
|
|
return null
|
|
var lgl := legal()
|
|
var w = RulesEngine.open_window(s)
|
|
if w != null:
|
|
if _passes_for(w.kind):
|
|
return _find(lgl, "pass")
|
|
_ending = -1
|
|
return null
|
|
if _ending >= 0:
|
|
if s.turn == _ending:
|
|
return _find(lgl, "end")
|
|
_ending = -1
|
|
if options.autoSkip and lgl.all(func(a): return a.type == "end" or a.type == "salvage"):
|
|
return _find(lgl, "end")
|
|
return null
|
|
|
|
|
|
static func _find(lgl: Array, type: String) -> Variant:
|
|
for a in lgl:
|
|
if a.type == type:
|
|
return a
|
|
return null
|
|
|
|
|
|
## Whether the stops setting passes this response window for you.
|
|
func _passes_for(kind: String) -> bool:
|
|
if hold_stop:
|
|
return false
|
|
match options.stops:
|
|
"all":
|
|
return false
|
|
"never":
|
|
return true
|
|
# In combat only: the bot's Executions, Abilities, installs and declarations outside combat pass.
|
|
return kind == "response" and not (s.combat != null and not s.combat.ended)
|
|
|
|
|
|
func _watch(_s: Dictionary, stage: String) -> void:
|
|
var c: Dictionary = s.combat
|
|
var last = combat()
|
|
if stage == "start" or last == null or last.id != c.id:
|
|
var info := _snap_combat(stage)
|
|
info.logFrom = maxi(0, (s.log.size() if s.log != null else 1) - 1)
|
|
combats.append(info)
|
|
return
|
|
# After the damage, keep the Cores and dice from the result: the fighters may be gone by now.
|
|
if stage == "end":
|
|
last.ended = c.ended
|
|
last.stage = stage
|
|
last.done = true
|
|
else:
|
|
combats[-1] = _snap_combat(stage)
|
|
|
|
|
|
## The current combat as the readout shows it: {id, loc, kind, attacker, defenders, rolled, ended,
|
|
## stage, done, logFrom}, where a fighter is {ref, cores, parts, dice, health, healthLeft}. Call only
|
|
## while there is a combat.
|
|
func _snap_combat(stage: String) -> Dictionary:
|
|
var c: Dictionary = s.combat
|
|
var last = combat()
|
|
var prev = last if last != null and last.id == c.id else null
|
|
var info := func(r: Dictionary) -> Dictionary:
|
|
var parts := []
|
|
var cores := Query.cores_of(s, Query.fighter_of(s, r), Callable(), parts)
|
|
var in_play := State.anomaly(s, r).at != null
|
|
return {
|
|
"ref": r, "cores": cores, "parts": parts, "dice": c.dice.get(State.ref_key(r), []).duplicate(),
|
|
"health": Query.health_of(s, r) if in_play else 0, "healthLeft": Query.health_left(s, r) if in_play else 0,
|
|
}
|
|
var defenders := []
|
|
for d in c.defenders:
|
|
defenders.append(info.call(d))
|
|
# Defenders who left keep their last numbers, so the readout still shows who was there.
|
|
if prev != null:
|
|
for d in prev.defenders:
|
|
if not c.defenders.any(func(x): return State.same_ref(x, d.ref)):
|
|
defenders.append(d)
|
|
return {
|
|
"id": c.id, "loc": c.loc, "kind": c.kind, "attacker": info.call(c.attacker), "defenders": defenders,
|
|
"rolled": c.rolled, "ended": c.ended, "stage": stage, "done": false,
|
|
"logFrom": prev.logFrom if prev != null else maxi(0, (s.log.size() if s.log != null else 1) - 1),
|
|
}
|