files-game/ui/hud.gd
2026-10-01 17:22:18 -04:00

826 lines
30 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 Hud
extends CanvasLayer
## The 2D layer over the table (godot-plan.md §4, "Anything with text is 2D"): the status bar,
## player panels, the action bar, prompts and menus, the card inspector, and the log, combat and
## move panels. It draws what Game hands it in refresh() and reports clicks as signals; it never
## builds an action.
signal move_chosen(move: Dictionary)
signal source_picked(key: String)
signal cancel_pressed
signal end_command_pressed
signal view_toggled
signal new_game_requested(opts: Dictionary)
signal settings_changed(settings: Dictionary)
const LEFT_W := 300
const RIGHT_W := 340
const COLORS := {
"bg": Color("#06090dE6"), "panel": Color("#0c1218EE"), "panel2": Color("#111a22"), "line": Color("#1e2a36"),
"text": Color("#d7dee6"), "muted": Color("#7d8a97"), "accent": Color("#2de2c4"), "warn": Color("#ffb454"),
"bad": Color("#ff6b6b"), "attack": Color("#ff5c7a"),
}
const OWNER_HEX: Array[String] = ["#56b4e9", "#e69f00"]
const STEPS := [["deploy", "Deploy"], ["play", "Play"], ["attack", "Attack"], ["playAgain", "Play again"]]
const STAT_LABELS := {
"capturesUnowned": "Open locations captured", "capturesUndefended": "Undefended enemy locations captured",
"capturesInCombat": "Locations won in combat", "attacks": "Attacks", "attacksWon": "Rolls won attacking",
"damageDealt": "Damage dealt", "anomaliesDestroyed": "Anomalies lost", "recalls": "Recalls",
"firewallsPlaced": "Firewalls placed", "bandwidthFromCaptures": "Gb from captures",
"bandwidthFromSalvage": "Gb from Salvage", "bandwidthOnCards": "Gb spent on cards", "cardsSalvaged": "Cards salvaged",
"hardwareInstalled": "Hardware installed", "programsInstalled": "Programs installed",
"executionsPlayed": "Executions played", "abilitiesUsed": "Abilities used",
}
var theme: Theme
var _root: Control
var _status: Label
var _stack: Label
var _banner_text: RichTextLabel
var _panels: Array[RichTextLabel] = []
var _steps: Label
var _primary: Button
var _end_command: Button
var _source_menu: PanelContainer
var _source_box: VBoxContainer
var _popover: PanelContainer
var _popover_box: VBoxContainer
var _inspector_art: TextureRect
var _inspector_text: RichTextLabel
var _tabs: TabContainer
var _log: RichTextLabel
var _combat: RichTextLabel
var _moves_box: VBoxContainer
var _modal: Control
var _modal_box: VBoxContainer
var _log_count := -1
var _moves_version := -1
var _primary_move := {}
var _art_cache := {}
var _settings := {"stops": "combat", "autoSkip": true, "checkInvariants": false, "botDelay": 0.45}
func _ready() -> void:
layer = 1
theme = _make_theme()
_root = Control.new()
_root.theme = theme
_root.set_anchors_preset(Control.PRESET_FULL_RECT)
_root.mouse_filter = Control.MOUSE_FILTER_IGNORE
add_child(_root)
_build_top()
_build_left()
_build_right()
_build_center()
_modal = Control.new()
_modal.set_anchors_preset(Control.PRESET_FULL_RECT)
_modal.visible = false
_root.add_child(_modal)
# ---------------------------------------------------------------------------------------------
# Building
func _make_theme() -> Theme:
var t := Theme.new()
var font := SystemFont.new()
font.font_names = PackedStringArray(["DejaVu Sans Mono", "Adwaita Mono", "monospace"])
t.default_font = font
t.default_font_size = 14
t.set_color("font_color", "Label", COLORS.text)
t.set_color("default_color", "RichTextLabel", COLORS.text)
var panel := _box(COLORS.panel, COLORS.line)
t.set_stylebox("panel", "PanelContainer", panel)
t.set_stylebox("normal", "Button", _box(COLORS.panel2, COLORS.line))
t.set_stylebox("hover", "Button", _box(Color("#16222c"), COLORS.accent))
t.set_stylebox("pressed", "Button", _box(Color("#0f2a2a"), COLORS.accent))
t.set_stylebox("disabled", "Button", _box(Color("#0a0f14"), Color("#141c24")))
t.set_stylebox("focus", "Button", StyleBoxEmpty.new())
t.set_color("font_color", "Button", COLORS.text)
t.set_color("font_hover_color", "Button", Color.WHITE)
t.set_color("font_disabled_color", "Button", Color("#3c4652"))
return t
static func _box(bg: Color, border: Color, radius := 5) -> StyleBoxFlat:
var b := StyleBoxFlat.new()
b.bg_color = bg
b.border_color = border
b.set_border_width_all(1)
b.set_corner_radius_all(radius)
b.content_margin_left = 9
b.content_margin_right = 9
b.content_margin_top = 6
b.content_margin_bottom = 6
return b
func _build_top() -> void:
var bar := PanelContainer.new()
bar.set_anchors_preset(Control.PRESET_TOP_WIDE)
bar.add_theme_stylebox_override("panel", _box(COLORS.bg, COLORS.line, 0))
_root.add_child(bar)
var row := HBoxContainer.new()
row.add_theme_constant_override("separation", 14)
bar.add_child(row)
var brand := Label.new()
brand.text = "FILES TCG"
brand.add_theme_color_override("font_color", COLORS.accent)
row.add_child(brand)
_status = Label.new()
row.add_child(_status)
_stack = Label.new()
_stack.add_theme_color_override("font_color", COLORS.warn)
_stack.size_flags_horizontal = Control.SIZE_EXPAND_FILL
_stack.clip_text = true
row.add_child(_stack)
row.add_child(_button("Top view T", func(): view_toggled.emit()))
row.add_child(_button("Settings", show_settings))
row.add_child(_button("New game", func(): show_start({})))
func _build_left() -> void:
var col := VBoxContainer.new()
col.position = Vector2(8, 44)
col.custom_minimum_size = Vector2(LEFT_W - 16, 0)
col.add_theme_constant_override("separation", 8)
_root.add_child(col)
for i in 2:
var pc := PanelContainer.new()
var rt := _rich()
rt.custom_minimum_size = Vector2(LEFT_W - 34, 0)
pc.add_child(rt)
col.add_child(pc)
_panels.append(rt)
var actions := PanelContainer.new()
var box := VBoxContainer.new()
box.add_theme_constant_override("separation", 6)
actions.add_child(box)
_banner_text = _rich()
_banner_text.custom_minimum_size = Vector2(LEFT_W - 34, 0)
box.add_child(_banner_text)
_steps = Label.new()
_steps.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
box.add_child(_steps)
_primary = _button("", func(): if not _primary_move.is_empty(): move_chosen.emit(_primary_move))
_primary.custom_minimum_size = Vector2(0, 38)
_primary.add_theme_color_override("font_color", COLORS.accent)
box.add_child(_primary)
_end_command = _button("End command Enter", func(): end_command_pressed.emit())
box.add_child(_end_command)
col.add_child(actions)
func _build_right() -> void:
var col := VBoxContainer.new()
col.anchor_left = 1.0
col.anchor_right = 1.0
col.anchor_bottom = 1.0
col.offset_left = -RIGHT_W + 8
col.offset_right = -8
col.offset_top = 44
col.offset_bottom = -8
col.add_theme_constant_override("separation", 8)
_root.add_child(col)
var insp := PanelContainer.new()
var ib := HBoxContainer.new()
ib.add_theme_constant_override("separation", 8)
insp.add_child(ib)
_inspector_art = TextureRect.new()
_inspector_art.custom_minimum_size = Vector2(150, 210)
_inspector_art.expand_mode = TextureRect.EXPAND_IGNORE_SIZE
_inspector_art.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_CENTERED
_inspector_art.visible = false
ib.add_child(_inspector_art)
_inspector_text = _rich()
_inspector_text.size_flags_horizontal = Control.SIZE_EXPAND_FILL
_inspector_text.custom_minimum_size = Vector2(0, 210)
_inspector_text.fit_content = false
_inspector_text.scroll_active = true
_inspector_text.add_theme_font_size_override("normal_font_size", 12)
_inspector_text.add_theme_font_size_override("bold_font_size", 13)
_inspector_text.text = "[color=#7d8a97]Point at a card, an Anomaly, a location or a gateway for its details.[/color]"
ib.add_child(_inspector_text)
col.add_child(insp)
# The picked source's moves, or your responses, between the inspector and the tabs.
_source_menu = PanelContainer.new()
_source_menu.visible = false
_source_menu.add_theme_stylebox_override("panel", _box(Color("#0d1a1c"), COLORS.accent))
col.add_child(_source_menu)
_source_box = VBoxContainer.new()
_source_menu.add_child(_source_box)
_tabs = TabContainer.new()
_tabs.size_flags_vertical = Control.SIZE_EXPAND_FILL
col.add_child(_tabs)
_log = _rich()
_log.name = "Log"
_log.fit_content = false
_log.scroll_following = true
_log.scroll_active = true
_tabs.add_child(_log)
_combat = _rich()
_combat.name = "Combat"
_combat.fit_content = false
_combat.scroll_active = true
_tabs.add_child(_combat)
var scroll := ScrollContainer.new()
scroll.name = "Moves"
scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED
_moves_box = VBoxContainer.new()
_moves_box.size_flags_horizontal = Control.SIZE_EXPAND_FILL
scroll.add_child(_moves_box)
_tabs.add_child(scroll)
func _build_center() -> void:
_popover = PanelContainer.new()
_popover.visible = false
_root.add_child(_popover)
_popover_box = VBoxContainer.new()
_popover.add_child(_popover_box)
func _rich() -> RichTextLabel:
var rt := RichTextLabel.new()
rt.bbcode_enabled = true
rt.fit_content = true
rt.scroll_active = false
rt.selection_enabled = false
return rt
func _button(text: String, fn: Callable) -> Button:
var b := Button.new()
b.text = text
b.pressed.connect(fn)
b.focus_mode = Control.FOCUS_NONE
return b
func _clear(box: Node) -> void:
for c in box.get_children():
box.remove_child(c)
c.queue_free()
# ---------------------------------------------------------------------------------------------
# Drawing
## Redraws from the game's state. `ctx` holds: match, view, moves, selected, marks, thinking, paused,
## settings, me.
func refresh(ctx: Dictionary) -> void:
var m: LocalMatch = ctx.match
var v: Dictionary = ctx.view
var me: int = m.human
var my_turn := m.human_to_act()
var window = RulesEngine.open_window(v)
var in_window: bool = my_turn and window != null and v.choice == null
var my_choice: bool = my_turn and v.choice != null and v.choice.player == me
_status.text = status_line(v, m)
var items := []
for it in v.stack:
items.append("%s (%s%s)" % [it.name.trim_prefix("Execute: "), State.player_name(it.player), " → %s" % it.target if it.target else ""])
_stack.text = "Waiting: " + " ← ".join(items) if not items.is_empty() else ""
_panels[0].text = _player_panel(v, m.bot_side, me, not my_turn and not v.over)
_panels[1].text = _player_panel(v, me, me, my_turn)
# The action bar.
if v.active == me:
var parts := []
for st in STEPS:
var on: bool = v.step == st[0] or (v.step == "resolve" and st[0] == "attack")
parts.append("[%s]" % st[1] if on else st[1])
_steps.text = " ".join(parts)
else:
_steps.text = "%s's command" % State.player_name(m.bot_side)
_primary_move = {}
for mv in ctx.moves:
if mv.action.type == "pass":
_primary_move = mv
break
if _primary_move.is_empty():
for mv in ctx.moves:
if mv.action.type == "end":
_primary_move = mv
break
if not _primary_move.is_empty() and v.choice == null:
_primary.text = "%s Space" % _primary_move.label
_primary.disabled = false
else:
_primary.text = "Game over" if v.over else ("%s is deciding…" % State.player_name(m.bot_side) if not my_turn else "Choose an option")
_primary.disabled = true
_end_command.disabled = not my_turn or v.choice != null or window != null or v.active != me
_banner_text.text = _banner_for(ctx, in_window, my_turn)
_banner_text.visible = _banner_text.text != ""
_draw_source_menu(ctx, in_window, my_choice)
_draw_log(m)
_draw_combat(m, v, ctx)
if _moves_version != m.version:
_moves_version = m.version
_draw_moves(ctx.moves, v.over)
if my_choice:
_show_choice(v, ctx.moves)
elif _modal.visible and _modal.get_meta("kind", "") == "choice":
close_modal()
if v.over and not _modal.visible and not _modal.get_meta("closed_over", false):
_show_game_over(m)
static func status_line(v: Dictionary, m: LocalMatch) -> String:
var me := m.human
if v.over:
if v.winner == null:
return "Game over: a draw"
return "Game over: %s" % ("you win" if v.winner == me else "%s wins" % State.player_name(v.winner))
var round := "Round %d · command %d" % [State.round_of(v, v.turn), v.turn] if v.rules.commands.on else "Turn %d" % v.turn
var whose := "your command" if v.active == me else "%s's command" % State.player_name(v.active)
var deciding := "your decision" if m.human_to_act() else "%s deciding" % State.player_name(m.bot_side)
return "%s · %s · %s step · %s" % [round, whose, Describe.STEP_NAMES[v.step], deciding]
func _player_panel(v: Dictionary, p: int, me: int, active: bool) -> String:
var pl: Dictionary = v.players[p]
var c: String = OWNER_HEX[p]
var held := State.grid_count(v, p)
var need: int = v.rules.winLocations
var bar := "■".repeat(held) + "□".repeat(maxi(0, need - held))
var out := "[color=%s][b]%s[/b][/color] %s%s [b]%d Gb[/b]\n" % [c, State.player_name(p), "you" if p == me else "bot", " ◀" if active else "", pl.bandwidth]
out += "[color=%s]%s[/color] %d/%d locations\n" % [c, bar, held, need]
out += "[color=#7d8a97]hand[/color] %d [color=#7d8a97]deck[/color] %d [color=#7d8a97]discard[/color] %d [color=#7d8a97]Servers[/color] %d\n" % [pl.hand.size(), pl.deck.size(), pl.discard.size(), pl.serverPile.size()]
for i in pl.anomalies.size():
var av: Dictionary = pl.anomalies[i]
var r := State.ref(p, i + 1)
if i >= 4 and av.at == null:
continue
var name := State.name_of(v, av.card) if av.card >= 0 and State.anomaly(v, State.original_of(r)).faceUp else "face down"
var where: String = av.at if av.at != null else ("in slot" if name != "face down" else "")
var n := "%d′" % (i - 3) if i >= 4 else str(i + 1)
var stats := GameTable.badge_text(v, r)
out += "[color=#7d8a97]%s[/color] %s [color=#7d8a97]%s[/color] %s\n" % [n, name, where, stats]
return out.strip_edges()
func _banner_for(ctx: Dictionary, in_window: bool, my_turn: bool) -> String:
var m: LocalMatch = ctx.match
var v: Dictionary = ctx.view
if v.over:
return ""
if in_window:
var w: Dictionary = RulesEngine.open_window(v)
var c = v.combat if v.combat != null and not v.combat.ended else null
var what := ""
var top = v.stack.back() if not v.stack.is_empty() else null
if w.kind == "preRoll" and c != null:
what = "Combat at %s, before the roll" % c.loc
elif w.kind == "postRoll" and c != null:
what = "Combat at %s, after the roll" % c.loc
elif top != null and top.player != m.human:
what = "%s %s %s%s" % [State.player_name(top.player), "plays" if top.kind == "execution" else "uses", top.name, " on %s" % top.target if top.target else ""]
else:
what = _last_by(m, m.bot_side).trim_suffix(".")
if what == "":
what = "A response window is open"
return "[color=#ffb454][b]%s: respond?[/b][/color] Pick a glowing card or Ability, or Space to pass." % what
if my_turn and v.choice == null:
var hint: String = {
"deploy": "Place, move or recall Anomalies, then advance one. A command is one advance or one attack.",
"play": "Play Hardware, Programs and Executions, and build Firewalls.",
"attack": "Attack from a location next to an enemy one.",
"resolve": "", "playAgain": "Play more cards, then end your command.",
}[v.step]
return "[color=#2de2c4][b]Your command.[/b][/color] %s" % hint
if not my_turn:
var last := _last_by(m, m.bot_side)
return "%s %s [color=#7d8a97]%s[/color]" % [State.player_name(m.bot_side), "is paused." if ctx.paused else "is deciding…", last]
return ""
static func _last_by(m: LocalMatch, p: int) -> String:
var lines := m.log_lines()
for i in range(lines.size() - 1, maxi(-1, lines.size() - 13), -1):
if lines[i].get("player") == p and lines[i].get("tag") != "turn":
return lines[i].text
return ""
func _draw_source_menu(ctx: Dictionary, in_window: bool, my_choice: bool) -> void:
_clear(_source_box)
var v: Dictionary = ctx.view
var selected: String = ctx.selected
_source_menu.visible = false
if my_choice:
return
if selected != "":
var mine := (ctx.moves as Array).filter(func(mv): return mv.source == selected)
var untargeted := mine.filter(func(mv): return mv.target == "none")
var targeted := mine.filter(func(mv): return mv.target != "none")
_source_box.add_child(_title(source_title(v, selected, ctx.match.human)))
if not targeted.is_empty():
_source_box.add_child(_muted("Click a highlighted %s." % _target_words(targeted)))
if ctx.get("preview", "") != "":
_source_box.add_child(_muted("Attack odds: %s" % ctx.preview))
for mv in untargeted:
_source_box.add_child(_move_button(mv))
_source_box.add_child(_button("Cancel Esc", func(): cancel_pressed.emit()))
_source_menu.visible = true
elif in_window:
var by_source := {}
for mv in ctx.moves:
if mv.action.type == "pass" or mv.action.type == "salvage":
continue
if not by_source.has(mv.source):
by_source[mv.source] = []
by_source[mv.source].append(mv)
_source_box.add_child(_title("Your responses"))
for src in by_source:
var list: Array = by_source[src]
if list.size() == 1:
_source_box.add_child(_move_button(list[0]))
else:
var key: String = src
_source_box.add_child(_button("%s · %d ways" % [source_title(v, key, ctx.match.human), list.size()], func(): source_picked.emit(key)))
if not _primary_move.is_empty():
_source_box.add_child(_move_button(_primary_move, "Pass Space"))
_source_menu.visible = true
func _title(text: String) -> Label:
var l := Label.new()
l.text = text
l.add_theme_color_override("font_color", COLORS.accent)
return l
func _muted(text: String) -> Label:
var l := Label.new()
l.text = text
l.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
l.add_theme_color_override("font_color", COLORS.muted)
return l
func _move_button(mv: Dictionary, text := "") -> Button:
var b := _button(text if text != "" else mv.label, func(): move_chosen.emit(mv))
b.alignment = HORIZONTAL_ALIGNMENT_LEFT
b.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
return b
static func source_title(v: Dictionary, key: String, me: int) -> String:
var r = Moves.ref_of_key(key)
if r != null:
return Describe.ref_name(v, r, me)
if key.begins_with("hand:"):
return key.substr(5)
if key.begins_with("loc:"):
var loc := key.substr(4)
var server = v.locations[loc].server
return loc + (": %s" % State.name_of(v, server) if server != null else "")
if key.begins_with("gate:"):
return "Gateway %s" % Describe.line_name(key.substr(5))
return key
static func _target_words(moves: Array) -> String:
var words := []
for mv in moves:
var kind: String = mv.target.split(":")[0]
var w: String = {"loc": "location", "anomaly": "Anomaly", "gate": "gateway", "hand": "card"}.get(kind, kind)
if not words.has(w):
words.append(w)
return " or ".join(words)
## A menu of moves at the mouse, for several moves on one target.
func show_popover(moves: Array, at: Vector2) -> void:
_clear(_popover_box)
for mv in moves:
_popover_box.add_child(_move_button(mv))
_popover_box.add_child(_button("Cancel", hide_popover))
_popover.visible = true
_popover.reset_size()
var vp := _root.get_viewport_rect().size
_popover.position = Vector2(minf(at.x, vp.x - _popover.size.x - 8), clampf(at.y, 8, vp.y - _popover.size.y - 8))
func hide_popover() -> void:
_popover.visible = false
func popover_open() -> bool:
return _popover.visible
func _draw_log(m: LocalMatch) -> void:
var lines := m.log_lines()
if lines.size() == _log_count:
return
if lines.size() < _log_count:
_log.clear()
_log_count = 0
for i in range(maxi(0, _log_count), lines.size()):
var l: Dictionary = lines[i]
if l.text == "":
continue
var color := "#7d8a97"
if l.get("tag") == "turn":
color = "#d7dee6"
elif l.get("player") != null:
color = OWNER_HEX[l.player]
elif l.get("tag") == "combat":
color = "#ff8aa0"
_log.append_text("[color=%s]%s[/color]\n" % [color, _escape(l.text)])
_log_count = lines.size()
static func _escape(t: String) -> String:
return t.replace("[", "[lb]")
func _draw_combat(m: LocalMatch, v: Dictionary, ctx: Dictionary) -> void:
var c = m.combat()
if c == null:
_combat.text = "[color=#7d8a97]No combat yet. Combats show here with each side's Cores, dice and damage.[/color]"
return
# This combat's log lines: from its start up to the next combat.
var own := m.log_lines().slice(c.logFrom)
var mine := own
for i in range(1, own.size()):
if own[i].get("tag") == "combat" and own[i].text.begins_with("Combat at"):
mine = own.slice(0, i)
break
var fighter := func(f: Dictionary, role: String) -> String:
var name := Describe.ref_name(v, f.ref, m.human)
var parts := []
for part in f.parts:
parts.append("%+d %s" % [part.cores, part.source] if part.kind != "anomaly" else "%d %s" % [part.cores, part.source])
var dice := ", ".join(f.dice.map(func(d): return str(d)))
var out := "[color=%s][b]%s[/b][/color] %s\n [b]%d Cores[/b] [color=#7d8a97]%s[/color]\n" % [
OWNER_HEX[f.ref.player], role, name, f.cores, ", ".join(parts)]
if dice != "":
out += " dice: %s = [b]%d[/b]\n" % [dice, Util.sum(f.dice)]
var took := 0
var dead := false
for l in mine:
var r = l.get("ref")
if r != null and l.get("amount") != null and State.same_ref(r, f.ref):
took += l.amount
dead = dead or l.text.contains("destroyed")
if v.rules.health.on and f.health > 0:
out += " %d/%d Health before the result" % [f.healthLeft, f.health]
if took > 0:
out += " [color=#ff6b6b][b]took %d%s[/b][/color]" % [took, ", destroyed" if dead else ""]
out += "\n"
return out
var stage := "ended early" if c.done and c.ended else ("over" if c.done else ("after the roll" if c.rolled else "before the roll"))
var kind: String = "Trace Route" if c.kind == "traceRoute" else c.kind
var out := "[b]Combat at %s[/b] [color=#7d8a97]%s · %s[/color]\n\n" % [c.loc, kind, stage]
out += fighter.call(c.attacker, "Attacker")
for d in c.defenders:
out += "\n" + fighter.call(d, "Defender")
if not c.rolled and not c.done and not ctx.thinking:
var atk: int = c.attacker.cores
var def := 0
for d in c.defenders:
def += d.cores
var o := Odds.roll_odds(atk, def)
out += "\n[color=#7d8a97]%d vs %d Cores: win %d%% · tie %d%% · lose %d%%\nAverage damage: %.1f to the defender, %.1f to the attacker[/color]\n" % [
atk, def, roundi(o.win * 100), roundi(o.tie * 100), roundi(o.lose * 100), o.damageDealt, o.damageTaken]
# What happened: the result, damage, captures and cards played in it, after the opening line.
var result := []
for i in range(1, mine.size()):
var l: Dictionary = mine[i]
if l.text == "" or l.text.begins_with("Roll:"):
continue
if l.get("tag") == "combat" or l.get("tag") == "capture":
var color: String = OWNER_HEX[l.player] if l.get("player") != null else "#d7dee6"
result.append("[color=%s]%s[/color]" % [color, _escape(l.text)])
if not result.is_empty():
out += "\n" + "\n".join(result)
_combat.text = out
func _draw_moves(moves: Array, over: bool) -> void:
_clear(_moves_box)
if moves.is_empty():
_moves_box.add_child(_muted("Game over." if over else "Nothing to do until the bot moves."))
return
for g in Moves.group_moves(moves):
_moves_box.add_child(_title(g[0]))
for mv in g[1]:
_moves_box.add_child(_move_button(mv))
## Shows a card or board object in the inspector: `info` is {art: card name or "", text: bbcode}.
func inspect(info: Dictionary) -> void:
var art: String = info.get("art", "")
_inspector_art.texture = _art(art) if art != "" else null
_inspector_art.visible = art != ""
_inspector_text.text = info.get("text", "")
func _art(card_name: String) -> Texture2D:
if not _art_cache.has(card_name):
var path := CardFaces.CARD_DIR + CardFaces.slug(card_name) + ".png"
_art_cache[card_name] = load(path) if ResourceLoader.exists(path) else null
return _art_cache[card_name]
func show_log_tab() -> void:
_tabs.current_tab = 0
func show_combat_tab() -> void:
_tabs.current_tab = 1
# ---------------------------------------------------------------------------------------------
# Dialogs
func _open_modal(kind: String, width := 520) -> VBoxContainer:
_clear(_modal)
_modal.set_meta("kind", kind)
var dim := ColorRect.new()
dim.color = Color(0, 0, 0, 0.45 if kind != "choice" else 0.2)
dim.set_anchors_preset(Control.PRESET_FULL_RECT)
_modal.add_child(dim)
var center := CenterContainer.new()
center.set_anchors_preset(Control.PRESET_FULL_RECT)
_modal.add_child(center)
var pc := PanelContainer.new()
pc.custom_minimum_size = Vector2(width, 0)
center.add_child(pc)
_modal_box = VBoxContainer.new()
_modal_box.add_theme_constant_override("separation", 8)
pc.add_child(_modal_box)
_modal.visible = true
return _modal_box
func close_modal() -> void:
_modal.visible = false
_clear(_modal)
_modal.set_meta("kind", "")
func modal_open() -> bool:
return _modal.visible
func _show_choice(v: Dictionary, moves: Array) -> void:
var key := "%s:%d:%d" % [v.choice.kind, moves.size(), v.seq]
if _modal.visible and _modal.get_meta("choice_key", "") == key:
return
var box := _open_modal("choice", 560)
_modal.set_meta("choice_key", key)
var prompt := Label.new()
prompt.text = v.choice.prompt
prompt.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
prompt.add_theme_color_override("font_color", COLORS.accent)
box.add_child(prompt)
var options := moves.filter(func(mv): return mv.action.type == "choose")
for mv in options:
box.add_child(_move_button(mv))
var blocked := []
for i in v.choice.options.size():
if not options.any(func(mv): return mv.action.index == i):
var o: Dictionary = v.choice.options[i]
blocked.append("%s (%d Gb)" % [o.label, o.get("cost", 0)])
if not blocked.is_empty():
box.add_child(_muted("Not enough Gb for: %s. Salvage a card first." % ", ".join(blocked)))
for mv in moves.filter(func(x): return x.action.type == "salvage"):
box.add_child(_move_button(mv))
func _show_game_over(m: LocalMatch) -> void:
var s := m.s
var me := m.human
var box := _open_modal("over", 560)
var title := "A draw" if s.winner == null else ("You win" if s.winner == me else "%s (the bot) wins" % State.player_name(s.winner))
box.add_child(_title(title))
var reason := "%s holds %d locations." % [State.player_name(s.winner), s.rules.winLocations] if s.endReason == "win" else "The turn limit was reached."
box.add_child(_muted("%s Round %d, seed %d." % [reason, State.round_of(s, s.turn), m.setup.seed]))
var grid := GridContainer.new()
grid.columns = 3
grid.add_theme_constant_override("h_separation", 18)
for t in ["", "%s (you)" % State.player_name(me), "%s (bot)" % State.player_name(m.bot_side)]:
grid.add_child(_title(t))
for k in Types.STAT_KEYS:
if not STAT_LABELS.has(k) or (s.stats[k][0] == 0 and s.stats[k][1] == 0):
continue
for t in [STAT_LABELS[k], str(s.stats[k][me]), str(s.stats[k][m.bot_side])]:
var l := Label.new()
l.text = t
grid.add_child(l)
box.add_child(grid)
var row := HBoxContainer.new()
row.add_child(_button("New game", func(): show_start({})))
row.add_child(_button("Rematch", func():
close_modal()
new_game_requested.emit({"seed": m.setup.seed, "human": m.human, "style": m.setup.get("style", "greedy")})))
row.add_child(_button("Look at the board", func():
close_modal()
_modal.set_meta("closed_over", true)))
box.add_child(row)
## The new-game dialog. `defaults` may hold seed, human and style.
func show_start(defaults: Dictionary) -> void:
var box := _open_modal("start", 480)
box.add_child(_title("New game against the bot"))
box.add_child(_muted("Both decks are dealt at random from Set 1, from the seed."))
var grid := GridContainer.new()
grid.columns = 2
grid.add_theme_constant_override("h_separation", 12)
box.add_child(grid)
var seed_edit := LineEdit.new()
seed_edit.text = str(defaults.get("seed", randi_range(1, 999999)))
seed_edit.custom_minimum_size = Vector2(200, 0)
grid.add_child(_label("Seed"))
grid.add_child(seed_edit)
var side := OptionButton.new()
side.add_item("South (S1)")
side.add_item("North (S2)")
side.selected = defaults.get("human", 0)
grid.add_child(_label("You play"))
grid.add_child(side)
var style := OptionButton.new()
var styles: Dictionary = GreedyBot.STYLES
var keys := styles.keys()
for k in keys:
style.add_item(styles[k].label)
style.selected = maxi(0, keys.find(defaults.get("style", "greedy")))
grid.add_child(_label("Bot"))
grid.add_child(style)
var about := _muted(styles[keys[style.selected]].about)
box.add_child(about)
style.item_selected.connect(func(i): about.text = styles[keys[i]].about)
var row := HBoxContainer.new()
row.add_child(_button("Start", func():
var opts := {"seed": int(seed_edit.text) if seed_edit.text.is_valid_int() else randi_range(1, 999999),
"human": side.selected, "style": keys[style.selected]}
close_modal()
new_game_requested.emit(opts)))
if defaults.get("cancel", true):
row.add_child(_button("Cancel", close_modal))
box.add_child(row)
func _label(text: String) -> Label:
var l := Label.new()
l.text = text
return l
## Settings: when the game stops for you, skipping, bot speed, invariant checks.
func show_settings(settings := {}) -> void:
if settings.is_empty():
settings = _settings
var box := _open_modal("settings", 520)
box.add_child(_title("Settings"))
box.add_child(_label("When the game stops for you to respond"))
var stops := OptionButton.new()
var stop_ids := ["combat", "all", "never"]
for label in ["In combat only", "Every opponent move", "Never"]:
stops.add_item(label)
stops.selected = maxi(0, stop_ids.find(settings.stops))
box.add_child(stops)
box.add_child(_muted("Hold Shift to stop at the next window anyway."))
var skip := CheckBox.new()
skip.text = "Skip steps where End and Salvage are the only moves"
skip.button_pressed = settings.autoSkip
box.add_child(skip)
var check := CheckBox.new()
check.text = "Check the rule invariants after every move"
check.button_pressed = settings.checkInvariants
box.add_child(check)
var speed_label := _label("")
box.add_child(speed_label)
var speed := HSlider.new()
speed.min_value = 0.0
speed.max_value = 1.5
speed.step = 0.05
speed.value = settings.botDelay
var show_speed := func(x): speed_label.text = "Bot speed: %.2fs per move" % x
show_speed.call(speed.value)
speed.value_changed.connect(show_speed)
box.add_child(speed)
box.add_child(_button("Done", func():
var out := {"stops": stop_ids[stops.selected], "autoSkip": skip.button_pressed, "checkInvariants": check.button_pressed, "botDelay": speed.value}
_settings = out
close_modal()
settings_changed.emit(out)))
func set_settings(settings: Dictionary) -> void:
_settings = settings.duplicate()
func reset_for_new_game() -> void:
_log.clear()
_log_count = -1
_moves_version = -1
_modal.set_meta("closed_over", false)
hide_popover()