extends Node3D ## GameScreen — 3D ranked game board with 2D HUD overlay. ## ## Selection modes: ## NONE — nothing selected ## CARD_FROM_HAND — hand card selected, waiting for tile target ## TERRAMORPHA_SELECT — accumulating tile targets for a Terramorpha card ## UNIT_SELECTED — friendly unit selected, shows move/attack ranges ## PLACEMENT — placing ArchSpirit during Placement phase ## SACRIFICE_SELECT — waiting for the player to pick a spirit to sacrifice ## ABILITY_TARGET — waiting for ability target (blue highlights) # ── Selection mode ──────────────────────────────────────────────────────────── enum Mode { NONE, CARD_FROM_HAND, TERRAMORPHA_SELECT, UNIT_SELECTED, PLACEMENT, SACRIFICE_SELECT, ABILITY_TARGET, } # ── Node refs ───────────────────────────────────────────────────────────────── @onready var _camera_rig : Node3D = $CameraRig @onready var _camera : Camera3D = $CameraRig/Camera3D @onready var _tiles_root : Node3D = $BoardRoot/TilesRoot @onready var _units_root : Node3D = $BoardRoot/UnitsRoot @onready var _hi_root : Node3D = $BoardRoot/HighlightsRoot @onready var _hold_timer : Timer = $HoldTimer # HUD @onready var _phase_lbl : Label = %PhaseLabel @onready var _turn_lbl : Label = %TurnLabel @onready var _opp_name_lbl : Label = %OppNameLabel @onready var _opp_hand_lbl : Label = %OppHandLabel @onready var _opp_deck_lbl : Label = %OppDeckLabel @onready var _opp_discard_btn : Button = %OppDiscardBtn @onready var _hand_cards : HBoxContainer = %HandCards @onready var _sp_lbl : Label = %SpLabel @onready var _st_lbl : Label = %StLabel @onready var _deck_lbl : Label = %DeckLabel @onready var _discard_btn : Button = %DiscardBtn @onready var _draw_btn : Button = %DrawBtn @onready var _end_turn_btn : Button = %EndTurnBtn @onready var _concede_btn : Button = %ConcedeBtn @onready var _ctx_popup : PanelContainer = %ContextPopup @onready var _ctx_tile_lbl : Label = %ContextTileLabel @onready var _ctx_unit_lbl : Label = %ContextUnitLabel @onready var _ctx_abil_lbl : Label = %ContextAbilitiesLabel @onready var _ctx_close_btn : Button = %ContextClose @onready var _dv_overlay : PanelContainer = %DiscardViewer @onready var _dv_title : Label = %DVTitle @onready var _dv_list : VBoxContainer = %DVList @onready var _dv_close_btn : Button = %DVCloseBtn @onready var _go_overlay : PanelContainer = %GameOverOverlay @onready var _go_result_lbl : Label = %GOResultLabel @onready var _go_rank_lbl : Label = %GORankLabel @onready var _go_menu_btn : Button = %GOMainMenuBtn @onready var _hud : CanvasLayer = $HUD var count : int = 0 var _last_click_frame : int = -1 var _last_click_iid : String = "" # ── Affinity colors ─────────────────────────────────────────────────────────── const AFFINITY_COLORS : Dictionary = { "Void": Color(0.18, 0.18, 0.22), "Aether": Color(0.60, 0.45, 0.85), "Lake": Color(0.28, 0.52, 0.88), "Hill": Color(0.58, 0.44, 0.26), "Forest": Color(0.22, 0.52, 0.24), "Field": Color(0.62, 0.72, 0.28), "Ocean": Color(0.10, 0.20, 0.72), "Island": Color(0.38, 0.68, 0.84), "Marsh": Color(0.38, 0.52, 0.34), "Swamp": Color(0.24, 0.33, 0.20), "Mountain": Color(0.50, 0.44, 0.38), "Steppe": Color(0.72, 0.63, 0.38), "Fort": Color(0.40, 0.34, 0.30), "Plains": Color(0.78, 0.74, 0.50), "Grove": Color(0.33, 0.58, 0.28), "Jungle": Color(0.15, 0.42, 0.20), "PerfectAether": Color(0.88, 0.72, 1.00), "PureVoid": Color(0.05, 0.05, 0.10), "UnstableAether":Color(0.70, 0.55, 0.90), "GatewayLake": Color(0.22, 0.42, 0.70), "GatewayHill": Color(0.46, 0.34, 0.18), "GatewayForest": Color(0.18, 0.42, 0.18), "GatewayField": Color(0.52, 0.60, 0.22), } const _CARD_WIDGET_SCENE := preload("res://scenes/collection/components/CardWidget.tscn") const HI_GREEN := Color(0.20, 0.90, 0.20, 0.40) const HI_RED := Color(1.00, 0.25, 0.25, 0.50) const HI_BLUE := Color(0.20, 0.50, 1.00, 0.40) const HI_YELLOW := Color(1.00, 0.85, 0.10, 0.50) const HI_ORANGE := Color(1.00, 0.60, 0.10, 0.45) # ── Camera state ────────────────────────────────────────────────────────────── var _cam_yaw : float = 0.0 var _cam_pitch : float = 40.0 var _cam_distance : float = 14.0 var _cam_pivot : Vector3 = Vector3.ZERO var _drag_active : bool = false var _press_was_on_board: bool = false # true only when the PRESS came from unhandled_input (board, not a UI card) var _camera_oriented : bool = false var _pan_active : bool = false var _last_mouse : Vector2 = Vector2.ZERO var _touch_points : Dictionary = {} var _pinch_dist : float = 0.0 # ── Selection state ─────────────────────────────────────────────────────────── var _mode : Mode = Mode.NONE var _sel_card_id : String = "" var _sel_unit_id : String = "" var _held_coord : Vector2i = Vector2i(-1, -1) # Terramorpha var _terra_targets : Array = [] # Array[Vector2i] var _terra_count : int = 0 # total tiles needed (1/2/3) # Sacrifice var _sac_arch_coord : Vector2i = Vector2i(-1, -1) # Ability var _ability_unit_id : String = "" var _ability_idx : int = -1 var _ability_panel : Control = null # ── Unit ownership lookup ───────────────────────────────────────────────────── # Rebuilt on each state update for O(1) ownership checks. var _enemy_unit_ids : Dictionary = {} # instanceId → true var _friendly_unit_ids: Dictionary = {} # instanceId → true # ── Scene refs ──────────────────────────────────────────────────────────────── var _tile_bodies : Dictionary = {} # "x,y" → StaticBody3D var _unit_meshes : Dictionary = {} # instanceId → MeshInstance3D # ── Lifecycle ───────────────────────────────────────────────────────────────── func _ready() -> void: _setup_environment() _apply_camera() _draw_btn.pressed.connect(_on_draw_pressed) _end_turn_btn.pressed.connect(_on_end_turn_pressed) _concede_btn.pressed.connect(_on_concede_pressed) _discard_btn.pressed.connect(func() -> void: _show_own_discard()) _opp_discard_btn.pressed.connect(func() -> void: _show_opp_discard()) _ctx_close_btn.pressed.connect(func() -> void: _ctx_popup.visible = false) _dv_close_btn.pressed.connect(func() -> void: _dv_overlay.visible = false) _go_menu_btn.pressed.connect(func() -> void: get_tree().change_scene_to_file("res://scenes/main/MainScreen.tscn")) _hold_timer.timeout.connect(_on_hold_timer_fired) Game.state_updated.connect(_on_state_updated) Game.game_over.connect(_on_game_over) if not Game.state.is_empty(): _on_state_updated(Game.state) else: Game.send_ready() func _exit_tree() -> void: if Game.state_updated.is_connected(_on_state_updated): Game.state_updated.disconnect(_on_state_updated) if Game.game_over.is_connected(_on_game_over): Game.game_over.disconnect(_on_game_over) # ── Environment ─────────────────────────────────────────────────────────────── func _setup_environment() -> void: var env := Environment.new() var sky := Sky.new() var proc := ProceduralSkyMaterial.new() proc.sky_top_color = Color(0.08, 0.10, 0.20) proc.sky_horizon_color = Color(0.28, 0.38, 0.55) proc.ground_bottom_color = Color(0.373, 0.374, 0.484, 1.0) proc.ground_horizon_color = Color(0.20, 0.28, 0.38) sky.sky_material = proc env.background_mode = Environment.BG_SKY env.sky = sky env.ambient_light_source = Environment.AMBIENT_SOURCE_SKY env.ambient_light_energy = 0.6 $WorldEnvironment.environment = env # ── Camera ──────────────────────────────────────────────────────────────────── func _apply_camera() -> void: var pitch_rad := deg_to_rad(_cam_pitch) _camera_rig.position = _cam_pivot _camera_rig.rotation_degrees = Vector3(0.0, _cam_yaw, 0.0) _camera.position = Vector3(0.0, _cam_distance * sin(pitch_rad), _cam_distance * cos(pitch_rad)) _camera.rotation_degrees = Vector3(-_cam_pitch, 0.0, 0.0) func _zoom(delta: float) -> void: _cam_distance = clampf(_cam_distance - delta, 4.0, 22.0) _apply_camera() # ── Input ───────────────────────────────────────────────────────────────────── func _unhandled_input(event: InputEvent) -> void: if event is InputEventMouseButton: var mb := event as InputEventMouseButton if mb.button_index == MOUSE_BUTTON_WHEEL_UP: _zoom(1.5); return elif mb.button_index == MOUSE_BUTTON_WHEEL_DOWN: _zoom(-1.5); return elif mb.button_index == MOUSE_BUTTON_MIDDLE: _pan_active = mb.pressed _last_mouse = mb.position elif mb.button_index == MOUSE_BUTTON_LEFT: if mb.pressed: # Double-click on a battlefield unit → show full card detail popup. if mb.double_click: var dbl_unit_id := _mouse_to_unit_id(mb.position) if not dbl_unit_id.is_empty(): _show_unit_detail_popup(dbl_unit_id) return _last_mouse = mb.position _drag_active = false _press_was_on_board = true # unhandled press = board area, not a UI card var coord := _mouse_to_tile_coord(mb.position) if coord.x >= 0: _held_coord = coord _hold_timer.start() else: _held_coord = Vector2i(-1, -1) else: _hold_timer.stop() if not _drag_active and _press_was_on_board: _handle_board_click(mb.position) _drag_active = false _press_was_on_board = false elif event is InputEventMouseMotion: var mm := event as InputEventMouseMotion var delta := mm.position - _last_mouse _last_mouse = mm.position if mm.button_mask & MOUSE_BUTTON_MASK_LEFT: if delta.length() > 2.0: _drag_active = true _hold_timer.stop() if _drag_active: _cam_yaw -= delta.x * 0.4 _cam_pitch = clampf(_cam_pitch + delta.y * 0.3, 15.0, 75.0) _apply_camera() if _pan_active: var ps := _cam_distance * 0.0015 var right := _camera_rig.global_basis.x * -delta.x * ps var fwd := Vector3(_camera_rig.global_basis.z.x, 0, _camera_rig.global_basis.z.z).normalized() _cam_pivot += right + fwd * delta.y * ps _cam_pivot.x = clampf(_cam_pivot.x, -6.0, 6.0) _cam_pivot.z = clampf(_cam_pivot.z, -6.0, 6.0) _apply_camera() elif event is InputEventScreenTouch: var st := event as InputEventScreenTouch if st.pressed: _touch_points[st.index] = st.position if _touch_points.size() == 2: _pinch_dist = _touch_pair_dist() _hold_timer.stop() else: _touch_points.erase(st.index) elif event is InputEventScreenDrag: var sd := event as InputEventScreenDrag _touch_points[sd.index] = sd.position if _touch_points.size() == 1: _cam_yaw -= sd.relative.x * 0.4 _cam_pitch = clampf(_cam_pitch + sd.relative.y * 0.3, 15.0, 75.0) _apply_camera() if sd.relative.length() > 2.0: _hold_timer.stop() elif _touch_points.size() == 2: var keys := _touch_points.keys() var pos_a : Vector2 = _touch_points[keys[0]] var pos_b : Vector2 = _touch_points[keys[1]] var mid := (pos_a + pos_b) * 0.5 var nd := pos_a.distance_to(pos_b) _zoom((nd - _pinch_dist) * 0.03) _pinch_dist = nd var ps := _cam_distance * 0.002 var cdelta := mid - _last_mouse _last_mouse = mid var right := _camera_rig.global_basis.x * -cdelta.x * ps var fwd := Vector3(_camera_rig.global_basis.z.x, 0, _camera_rig.global_basis.z.z).normalized() _cam_pivot += right + fwd * cdelta.y * ps _cam_pivot.x = clampf(_cam_pivot.x, -6.0, 6.0) _cam_pivot.z = clampf(_cam_pivot.z, -6.0, 6.0) _apply_camera() func _touch_pair_dist() -> float: var keys := _touch_points.keys() if keys.size() < 2: return 0.0 return (_touch_points[keys[0]] as Vector2).distance_to(_touch_points[keys[1]]) # ── Coord helpers ───────────────────────────────────────────────────────────── func _coord_to_world(x: int, y: int) -> Vector3: return Vector3(x - (Game.board_width() - 1) * 0.5, 0.0, y - (Game.board_height() - 1) * 0.5) func _mouse_to_tile_coord(mouse_pos: Vector2) -> Vector2i: var body := _raycast_body(mouse_pos) if body == null: return Vector2i(-1, -1) if body.has_meta("tile_coord"): return body.get_meta("tile_coord") as Vector2i return Vector2i(-1, -1) func _mouse_to_unit_id(mouse_pos: Vector2) -> String: var body := _raycast_body(mouse_pos) if body == null: return "" if body.has_meta("unit_id"): return str(body.get_meta("unit_id")) return "" func _raycast_body(mouse_pos: Vector2) -> PhysicsBody3D: var space := get_world_3d().direct_space_state var from := _camera.project_ray_origin(mouse_pos) var to := from + _camera.project_ray_normal(mouse_pos) * 100.0 var query := PhysicsRayQueryParameters3D.create(from, to) var result := space.intersect_ray(query) if result.is_empty(): return null return result.get("collider") as PhysicsBody3D # ── Ownership helpers ───────────────────────────────────────────────────────── func _is_enemy_unit(instance_id: String) -> bool: return _enemy_unit_ids.has(instance_id) func _is_friendly_unit(instance_id: String) -> bool: return _friendly_unit_ids.has(instance_id) func _rebuild_ownership(state: Dictionary) -> void: _enemy_unit_ids.clear() _friendly_unit_ids.clear() var my_id := Auth.user_id for p: Dictionary in state.get("players", []): var is_mine : bool = str(p.get("accountId", "")).to_lower() == my_id.to_lower() var target : Dictionary = _enemy_unit_ids if not is_mine else _friendly_unit_ids for u: Dictionary in p.get("field", []): var iid : String = u.get("instanceId", "") if not iid.is_empty(): target[iid] = true var arch : Dictionary = p.get("archSpirit", {}) var aid : String = arch.get("instanceId", "") if not aid.is_empty(): target[aid] = true # ── Board building ──────────────────────────────────────────────────────────── func _build_board(board: Dictionary) -> void: for c in _tiles_root.get_children(): c.queue_free() for c in _units_root.get_children(): c.queue_free() for c in _hi_root.get_children(): c.queue_free() _tile_bodies.clear() _unit_meshes.clear() for tile: Dictionary in board.get("tiles", []): var coord : Dictionary = tile.get("coord", {}) _add_tile(coord.get("x", 0), coord.get("y", 0), tile.get("resolvedAffinity", "Void")) func _add_tile(x: int, y: int, affinity: String) -> void: var wp := _coord_to_world(x, y) var body := StaticBody3D.new() body.position = wp + Vector3(0, 0.25, 0) body.set_meta("tile_coord", Vector2i(x, y)) var shape := CollisionShape3D.new() var box := BoxShape3D.new() box.size = Vector3(0.98, 0.5, 0.98) shape.shape = box body.add_child(shape) var mi := MeshInstance3D.new() var bm := BoxMesh.new() bm.size = Vector3(0.98, 0.5, 0.98) mi.mesh = bm var mat := StandardMaterial3D.new() mat.albedo_color = AFFINITY_COLORS.get(affinity, Color(0.2, 0.2, 0.2)) mat.roughness = 0.85 mi.material_override = mat body.add_child(mi) _tiles_root.add_child(body) _tile_bodies["%d,%d" % [x, y]] = body func _update_tile_affinity(x: int, y: int, affinity: String) -> void: var body = _tile_bodies.get("%d,%d" % [x, y]) if body == null: return for child in body.get_children(): if child is MeshInstance3D: var mat := child.material_override as StandardMaterial3D if mat: mat.albedo_color = AFFINITY_COLORS.get(affinity, Color(0.2, 0.2, 0.2)) # ── Unit meshes ─────────────────────────────────────────────────────────────── func _rebuild_units(state: Dictionary) -> void: for c in _units_root.get_children(): c.queue_free() _unit_meshes.clear() var my_id := Auth.user_id for player: Dictionary in state.get("players", []): var is_mine : bool = str(player.get("accountId", "")).to_lower() == my_id.to_lower() var color : Color = Color(0.3, 0.5, 1.0) if is_mine else Color(1.0, 0.35, 0.35) var arch : Dictionary = player.get("archSpirit", {}) if not arch.is_empty() and arch.get("position") != null: _add_unit_mesh(arch, color) for unit: Dictionary in player.get("field", []): if unit.get("position") != null: _add_unit_mesh(unit, color) func _add_unit_mesh(unit: Dictionary, team_color: Color) -> void: var pd : Dictionary = unit.get("position", {}) if pd.is_empty(): return var wp := _coord_to_world(pd.get("x", 0), pd.get("y", 0)) var card_type : String = unit.get("cardType", "Spirit") var iid : String = unit.get("instanceId", "") var body := StaticBody3D.new() body.set_meta("unit_id", iid) var shape := CollisionShape3D.new() var mi := MeshInstance3D.new() var mat := StandardMaterial3D.new() mat.roughness = 0.65 var y_offset : float match card_type: "ArchSpirit": var cyl := CylinderMesh.new() cyl.top_radius = 0.22 cyl.bottom_radius = 0.22 cyl.height = 0.8 mi.mesh = cyl mat.albedo_color = team_color.lightened(0.25) mat.emission_enabled = true mat.emission = team_color * 0.4 var cs := CylinderShape3D.new() cs.radius = 0.22; cs.height = 0.8 shape.shape = cs y_offset = 0.5 + 0.4 "Ruin": var bm := BoxMesh.new() bm.size = Vector3(0.25, 1.0, 0.25) mi.mesh = bm mat.albedo_color = Color(0.35, 0.32, 0.30) var bs := BoxShape3D.new() bs.size = Vector3(0.25, 1.0, 0.25) shape.shape = bs y_offset = 0.5 + 0.5 _: var sm := SphereMesh.new() sm.radius = 0.28 sm.height = 0.28 mi.mesh = sm mat.albedo_color = team_color var ss := SphereShape3D.new() ss.radius = 0.28 shape.shape = ss y_offset = 0.5 + 0.28 mi.material_override = mat if unit.get("isExhausted", false): mat.albedo_color = mat.albedo_color.darkened(0.45) body.add_child(shape) body.add_child(mi) body.position = wp + Vector3(0, y_offset, 0) _units_root.add_child(body) _unit_meshes[iid] = mi # ── Highlights ──────────────────────────────────────────────────────────────── func _clear_highlights() -> void: print("Clearing") for c in _hi_root.get_children(): c.queue_free() func _add_highlight(x: int, y: int, color: Color) -> void: var mi := MeshInstance3D.new() var bm := BoxMesh.new() bm.size = Vector3(0.96, 0.06, 0.96) mi.mesh = bm var mat := StandardMaterial3D.new() # Use a solid opaque base + emission so the highlight is always visible # regardless of depth-sort or transparency ordering. mat.albedo_color = Color(color.r, color.g, color.b, 1.0) mat.emission_enabled = true mat.emission = Color(color.r, color.g, color.b) mat.emission_energy_multiplier = 2.0 # Keep a mild transparency so the tile below is still readable. mat.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA mat.albedo_color.a = 0.75 mi.material_override = mat # Position clearly above the tile top (tile top = Y 0.50). mi.position = _coord_to_world(x, y) + Vector3(0, 0.58, 0) _hi_root.add_child(mi) print("[Highlight] added (%d,%d) hi_root children=%d" % [x, y, _hi_root.get_child_count()]) func _highlight_tiles(coords: Array, color: Color) -> void: for coord in coords: if coord is Vector2i: _add_highlight(coord.x, coord.y, color) elif coord is Dictionary: _add_highlight(coord.get("x", 0), coord.get("y", 0), color) # ── Valid target computation ────────────────────────────────────────────────── func _valid_play_tiles(card: Dictionary) -> Array: var results : Array = [] var card_type : String = card.get("cardType", "") var board : Dictionary = Game.get_board() var bw : int = board.get("width", 8) var bh : int = board.get("height", 8) var arch : Dictionary = Game.get_my_player().get("archSpirit", {}) var arch_pos : Dictionary = arch.get("position", {}) match card_type: "Spirit": if arch_pos.is_empty(): return results var ax : int = arch_pos.get("x", 0) var ay : int = arch_pos.get("y", 0) # Channel range is a property of the ArchSpirit. # dict.get(key, default) only uses the default when the key is ABSENT. # The server sends nullable ints (e.g. "minChannelRange": null), so the # key EXISTS but its value is null — GDScript returns null, which silently # coerces to 0 on a typed int variable, collapsing the range to nothing. # Read as Variant first, then substitute the default explicitly. var raw_min = arch.get("minChannelRange") var raw_max = arch.get("maxChannelRange") var min_r : int = 1 if raw_min == null else int(raw_min) var max_r : int = 1 if raw_max == null else int(raw_max) for tx in range(bw): for ty in range(bh): var dist : int = abs(tx - ax) + abs(ty - ay) if dist < min_r or dist > max_r: continue if Game.get_tile(tx, ty).get("occupantId"): continue print("Adding tiles") results.append(Vector2i(tx, ty)) print("results: ", results) "Terramorpha": for tx in range(bw): for ty in range(bh): results.append(Vector2i(tx, ty)) "Repentance", "Instinct", "Ruin": pass # No tile target — played directly (server handles placement). return results func _terra_count_for_card(card: Dictionary) -> int: match card.get("terramorphaMode", ""): "Mono": return 1 "Di": return 2 "Tri": return 3 return 1 func _valid_move_tiles(unit: Dictionary) -> Array: var results : Array = [] var pos : Dictionary = unit.get("position", {}) if pos.is_empty(): return results var ux : int = pos.get("x", 0) var uy : int = pos.get("y", 0) var mp : int = unit.get("currentMp", 0) var bw : int = Game.board_width() var bh : int = Game.board_height() if mp <= 0 or unit.get("isExhausted", false): return results for tx in range(bw): for ty in range(bh): var dist : int = abs(tx - ux) + abs(ty - uy) if dist == 0 or dist > mp: continue if Game.get_tile(tx, ty).get("occupantId"): continue results.append(Vector2i(tx, ty)) return results func _valid_attack_target_coords(unit: Dictionary) -> Array: var results : Array = [] var pos : Dictionary = unit.get("position", {}) if pos.is_empty(): return results var ux : int = pos.get("x", 0) var uy : int = pos.get("y", 0) var min_r : int = unit.get("minAttackRange", 1) var max_r : int = unit.get("maxAttackRange", 1) if unit.get("isExhausted", false) and unit.get("extraAttacksRemaining", 0) == 0: return results var opp := Game.get_opponent() var to_check : Array = [] to_check.append_array(opp.get("field", [])) var opp_arch : Dictionary = opp.get("archSpirit", {}) if not opp_arch.is_empty(): to_check.append(opp_arch) for t: Dictionary in to_check: if not t.get("canBeAttacked", true): continue var tp : Dictionary = t.get("position", {}) if tp.is_empty(): continue var dist : int = abs(tp.get("x", 0) - ux) + abs(tp.get("y", 0) - uy) if dist >= min_r and dist <= max_r: results.append(tp) return results func _valid_attack_target_ids(unit: Dictionary) -> Array: var results : Array = [] var pos : Dictionary = unit.get("position", {}) if pos.is_empty(): return results var ux : int = pos.get("x", 0) var uy : int = pos.get("y", 0) var min_r : int = unit.get("minAttackRange", 1) var max_r : int = unit.get("maxAttackRange", 1) if unit.get("isExhausted", false) and unit.get("extraAttacksRemaining", 0) == 0: return results var opp := Game.get_opponent() var to_check : Array = [] to_check.append_array(opp.get("field", [])) var opp_arch : Dictionary = opp.get("archSpirit", {}) if not opp_arch.is_empty(): to_check.append(opp_arch) for t: Dictionary in to_check: if not t.get("canBeAttacked", true): continue var tp : Dictionary = t.get("position", {}) if tp.is_empty(): continue var dist : int = abs(tp.get("x", 0) - ux) + abs(tp.get("y", 0) - uy) if dist >= min_r and dist <= max_r: results.append(t.get("instanceId", "")) return results ## All tiles within a unit's attack range (regardless of occupancy). ## Used to show the orange reach area for ranged units. func _attack_range_tiles(unit: Dictionary) -> Array: var results : Array = [] var pos : Dictionary = unit.get("position", {}) if pos.is_empty(): return results var ux : int = pos.get("x", 0) var uy : int = pos.get("y", 0) var min_r : int = unit.get("minAttackRange", 1) var max_r : int = unit.get("maxAttackRange", 1) if max_r <= 1: return results # skip melee — no separate range indicator needed var bw : int = Game.board_width() var bh : int = Game.board_height() for tx in range(bw): for ty in range(bh): var dist : int = abs(tx - ux) + abs(ty - uy) if dist >= min_r and dist <= max_r: results.append(Vector2i(tx, ty)) return results func _valid_placement_tiles() -> Array: var results : Array = [] var my_id := Auth.user_id var p1_id : String = str(Game.state.get("playerOneAccountId", "")) var bw : int = Game.board_width() var bh : int = Game.board_height() var row : int = 0 if my_id == p1_id else bh - 1 for tx in range(bw): if not Game.get_tile(tx, row).get("occupantId"): results.append(Vector2i(tx, row)) return results ## Friendly spirits adjacent to own ArchSpirit (sacrifice candidates). func _valid_sacrifice_spirits() -> Array: var results : Array = [] var arch : Dictionary = Game.get_my_player().get("archSpirit", {}) var arch_pos : Dictionary = arch.get("position", {}) if arch_pos.is_empty(): return results var ax : int = arch_pos.get("x", 0) var ay : int = arch_pos.get("y", 0) for unit: Dictionary in Game.get_field(): var up : Dictionary = unit.get("position", {}) if up.is_empty(): continue var ux : int = up.get("x", 0) var uy : int = up.get("y", 0) if abs(ux - ax) + abs(uy - ay) == 1: results.append(unit) return results # ── Click handling ──────────────────────────────────────────────────────────── func _handle_board_click(mouse_pos: Vector2) -> void: var coord := _mouse_to_tile_coord(mouse_pos) var unit_id := _mouse_to_unit_id(mouse_pos) match _mode: Mode.NONE: if not unit_id.is_empty() and _is_friendly_unit(unit_id) \ and Game.is_my_turn() and Game.get_phase() != "Placement": _select_unit(unit_id) Mode.CARD_FROM_HAND: var card := _find_hand_card(_sel_card_id) if card.is_empty(): print("Card empty, mode none") _set_mode(Mode.NONE); return var card_type : String = card.get("cardType", "") if card_type in ["Repentance", "Instinct", "Ruin"]: Game.send_play_card(_sel_card_id, 0, 0) _set_mode(Mode.NONE); return if coord.x < 0: print("x coor < 0") _set_mode(Mode.NONE); return Game.send_play_card(_sel_card_id, coord.x, coord.y) print("Send play card") _set_mode(Mode.NONE) Mode.TERRAMORPHA_SELECT: if coord.x < 0: _set_mode(Mode.NONE); return # Validate adjacency to previous target for Di/Tri. if _terra_targets.size() > 0: print("_terra_targets: ", _terra_targets.size()) var last : Vector2i = _terra_targets.back() if abs(coord.x - last.x) + abs(coord.y - last.y) != 1: return # must be adjacent # Avoid duplicates. print("Handle Board Click: terra targets: ", _terra_targets) if _terra_targets.has(coord): return _terra_targets.append(coord) print("Added Target") if _terra_targets.size() >= _terra_count: print("Entering here") print("_terra_count: ", _terra_count) # All tiles selected — send play. var targets := _terra_targets.map(func(v: Vector2i) -> Dictionary: return { "x": v.x, "y": v.y }) Game.send_play_card_multi(_sel_card_id, targets) _set_mode(Mode.NONE) else: # More tiles needed — re-highlight: orange for picked, green for valid next. _clear_highlights() for t: Vector2i in _terra_targets: _add_highlight(t.x, t.y, HI_ORANGE) var last2 : Vector2i = _terra_targets.back() var bw2 := Game.board_width() var bh2 := Game.board_height() for d: Vector2i in [Vector2i(1,0), Vector2i(-1,0), Vector2i(0,1), Vector2i(0,-1)]: var nx := last2.x + d.x var ny := last2.y + d.y if nx < 0 or ny < 0 or nx >= bw2 or ny >= bh2: continue if _terra_targets.has(Vector2i(nx, ny)): continue _add_highlight(nx, ny, HI_GREEN) Mode.UNIT_SELECTED: if not unit_id.is_empty(): if _is_enemy_unit(unit_id): Game.send_attack(_sel_unit_id, unit_id) _set_mode(Mode.NONE) elif _is_friendly_unit(unit_id): _select_unit(unit_id) # switch to new unit elif coord.x >= 0: Game.send_move_unit(_sel_unit_id, coord.x, coord.y) _set_mode(Mode.NONE) Mode.PLACEMENT: if coord.x >= 0: Game.send_place_arch_spirit(coord.x, coord.y) _set_mode(Mode.NONE) Mode.SACRIFICE_SELECT: # Player clicks a highlighted friendly spirit adjacent to ArchSpirit. if unit_id.is_empty() or not _is_friendly_unit(unit_id): _set_mode(Mode.NONE); return var unit := Game.get_unit_by_id(unit_id) if unit.is_empty() or unit.get("cardType", "") == "ArchSpirit": _set_mode(Mode.NONE); return _confirm_sacrifice(unit_id, unit.get("name", "this spirit")) Mode.ABILITY_TARGET: # Blue-highlighted target clicked. if not unit_id.is_empty(): Game.send_activate_ability(_ability_unit_id, _ability_idx) elif coord.x >= 0: Game.send_activate_ability(_ability_unit_id, _ability_idx) _set_mode(Mode.NONE) func _select_unit(unit_id: String) -> void: var unit := Game.get_unit_by_id(unit_id) if unit.is_empty(): return _hide_ability_panel() _sel_unit_id = unit_id _set_mode(Mode.UNIT_SELECTED) _clear_highlights() # Highlight own tile. var upos : Dictionary = unit.get("position", {}) if not upos.is_empty(): _add_highlight(upos.get("x", 0), upos.get("y", 0), HI_YELLOW) # Movement range (green). _highlight_tiles(_valid_move_tiles(unit), HI_GREEN) # Attack range area (orange) — visible reach even when no enemies are in range. _highlight_tiles(_attack_range_tiles(unit), HI_ORANGE) # Attackable enemies (red — drawn on top of orange). _highlight_tiles(_valid_attack_target_coords(unit), HI_RED) # Show ability panel if unit has active abilities. _show_ability_panel(unit_id, unit) # Own ArchSpirit — offer Sacrifice option via menu. if unit.get("cardType", "") == "ArchSpirit" and _is_friendly_unit(unit_id): _show_arch_spirit_menu(unit_id, unit) func _set_mode(new_mode: Mode) -> void: print("Setting mode: ", new_mode) _mode = new_mode _terra_targets = [] _terra_count = 0 if new_mode == Mode.NONE: _sel_card_id = "" _sel_unit_id = "" _ability_unit_id = "" _ability_idx = -1 _clear_highlights() _hide_ability_panel() _refresh_hand_selection() # ── ArchSpirit popup menu (Sacrifice / Ascend / Transition) ─────────────────── func _show_arch_spirit_menu(unit_id: String, _unit: Dictionary) -> void: var menu := PopupMenu.new() add_child(menu) var sac_spirits := _valid_sacrifice_spirits() if not sac_spirits.is_empty(): menu.add_item("Sacrifice a Spirit", 0) # Ascend / Transition from hand. var can_ascend := false var can_transition := false var cur_tier : int = _unit.get("tier", 1) for card: Dictionary in Game.get_hand(): if card.get("cardType", "") != "ArchSpirit": continue var t : int = int(card.get("tier", 0)) if t == cur_tier + 1: can_ascend = true if t == 1: can_transition = true if can_ascend: menu.add_item("Ascend ArchSpirit", 1) if can_transition: menu.add_item("Transition ArchSpirit", 2) if menu.item_count == 0: menu.queue_free(); return menu.id_pressed.connect(func(id: int) -> void: match id: 0: _start_sacrifice_mode() 1: _pick_ascend_card() 2: _pick_transition_card() menu.queue_free()) menu.popup_hide.connect(func() -> void: menu.queue_free()) menu.position = DisplayServer.mouse_get_position() menu.reset_size() menu.popup() func _start_sacrifice_mode() -> void: _set_mode(Mode.SACRIFICE_SELECT) _clear_highlights() for spirit: Dictionary in _valid_sacrifice_spirits(): var sp : Dictionary = spirit.get("position", {}) if not sp.is_empty(): _add_highlight(sp.get("x", 0), sp.get("y", 0), HI_GREEN) func _confirm_sacrifice(unit_id: String, unit_name: String) -> void: var dlg := ConfirmationDialog.new() dlg.title = "Sacrifice" dlg.dialog_text = "Sacrifice %s?" % unit_name dlg.ok_button_text = "Sacrifice" dlg.cancel_button_text = "Cancel" dlg.min_size = Vector2(260, 90) add_child(dlg) dlg.popup_centered() dlg.confirmed.connect(func() -> void: Game.send_sacrifice(unit_id) dlg.queue_free() _set_mode(Mode.NONE)) dlg.canceled.connect(func() -> void: dlg.queue_free() _set_mode(Mode.NONE)) # ── Ascend / Transition ─────────────────────────────────────────────────────── func _pick_ascend_card() -> void: var cur_tier : int = _get_my_arch_tier() var candidates : Array = Game.get_hand().filter(func(c: Dictionary) -> bool: return c.get("cardType", "") == "ArchSpirit" and int(c.get("tier", 0)) == cur_tier + 1) if candidates.is_empty(): return if candidates.size() == 1: _confirm_ascend(candidates[0]) else: _show_card_picker("Choose Ascend Card", candidates, func(card: Dictionary) -> void: _confirm_ascend(card)) func _pick_transition_card() -> void: var candidates : Array = Game.get_hand().filter(func(c: Dictionary) -> bool: return c.get("cardType", "") == "ArchSpirit" and int(c.get("tier", 0)) == 1) if candidates.is_empty(): return if candidates.size() == 1: _confirm_transition(candidates[0]) else: _show_card_picker("Choose Transition Card", candidates, func(card: Dictionary) -> void: _confirm_transition(card)) func _confirm_ascend(card: Dictionary) -> void: var dlg := ConfirmationDialog.new() dlg.title = "Ascend" dlg.dialog_text = "Ascend to %s (Tier %d)?" % [ card.get("name", "?"), int(card.get("tier", 0))] dlg.ok_button_text = "Ascend" dlg.min_size = Vector2(280, 90) add_child(dlg) dlg.popup_centered() dlg.confirmed.connect(func() -> void: Game.send_ascend(card.get("instanceId", "")) dlg.queue_free()) dlg.canceled.connect(func() -> void: dlg.queue_free()) func _confirm_transition(card: Dictionary) -> void: var dlg := ConfirmationDialog.new() dlg.title = "Transition" dlg.dialog_text = "Swap to %s?" % card.get("name", "?") dlg.ok_button_text = "Transition" dlg.min_size = Vector2(280, 90) add_child(dlg) dlg.popup_centered() dlg.confirmed.connect(func() -> void: Game.send_transition(card.get("instanceId", "")) dlg.queue_free()) dlg.canceled.connect(func() -> void: dlg.queue_free()) func _get_my_arch_tier() -> int: var arch : Dictionary = Game.get_my_player().get("archSpirit", {}) return int(arch.get("tier", 1)) ## Generic card picker popup for when there are multiple candidates. func _show_card_picker(title: String, cards: Array, on_pick: Callable) -> void: var dlg := AcceptDialog.new() dlg.title = title dlg.min_size = Vector2(320, 200) var vbox := VBoxContainer.new() vbox.add_theme_constant_override("separation", 6) for card: Dictionary in cards: var btn := Button.new() btn.text = "%s (Tier %d)" % [card.get("name", "?"), int(card.get("tier", 0))] btn.pressed.connect(func() -> void: on_pick.call(card) dlg.queue_free()) vbox.add_child(btn) dlg.add_child(vbox) add_child(dlg) dlg.popup_centered() dlg.canceled.connect(func() -> void: dlg.queue_free()) # ── Ability panel ───────────────────────────────────────────────────────────── func _show_ability_panel(unit_id: String, unit: Dictionary) -> void: _hide_ability_panel() # Null trap: server sends "abilitiesJson": null for units with no abilities. # dict.get(key, default) returns null when key exists with null value. var _raw_abil_ap = unit.get("abilitiesJson") var abil_json : String = "" if _raw_abil_ap == null else str(_raw_abil_ap) if abil_json.is_empty(): return var parsed = JSON.parse_string(abil_json) if not parsed is Array: return # Collect Active abilities. var actives : Array = [] for i in parsed.size(): var ab : Dictionary = parsed[i] as Dictionary if ab.get("type", "") == "Active": actives.append({ "index": i, "name": ab.get("name", "Ability %d" % i), "desc": ab.get("description", "") }) if actives.is_empty(): return # Build a floating panel anchored above the hand. var panel := PanelContainer.new() panel.position = Vector2(20, 480) # fixed position; adjust if layout changes var vbox := VBoxContainer.new() vbox.add_theme_constant_override("separation", 4) var title := Label.new() title.text = "Abilities" title.add_theme_font_size_override("font_size", 12) title.add_theme_color_override("font_color", Color(0.7, 0.8, 1.0)) vbox.add_child(title) vbox.add_child(HSeparator.new()) for ab: Dictionary in actives: var btn := Button.new() btn.text = ab.get("name", "") btn.add_theme_font_size_override("font_size", 12) btn.tooltip_text = ab.get("desc", "") var idx : int = ab.get("index", 0) btn.pressed.connect(func() -> void: _ability_unit_id = unit_id _ability_idx = idx # Activate without specific target (server will validate). Game.send_activate_ability(unit_id, idx) _hide_ability_panel() _set_mode(Mode.NONE)) vbox.add_child(btn) panel.add_child(vbox) _hud.add_child(panel) _ability_panel = panel func _hide_ability_panel() -> void: if is_instance_valid(_ability_panel): _ability_panel.queue_free() _ability_panel = null func _show_unit_detail_popup(unit_id: String) -> void: var unit := Game.get_unit_by_id(unit_id) if unit.is_empty(): return var name_ : String = unit.get("name", "?") var type_ : String = unit.get("cardType", "") var aff : String = unit.get("affinity", "") _ctx_tile_lbl.text = "%s — %s [%s]" % [name_, type_, aff] _ctx_unit_lbl.text = "HP %d/%d DEF %d/%d ATK %d MP %d/%d" % [ int(unit.get("currentHealth", 0)), int(unit.get("maxHealth", 0)), int(unit.get("currentDefense", 0)), int(unit.get("maxDefense", 0)), int(unit.get("damage", 0)), int(unit.get("currentMp", 0)), int(unit.get("maxMp", 0))] var abil_str := "" var _raw = unit.get("abilitiesJson") var parsed = JSON.parse_string("[]" if _raw == null else str(_raw)) if parsed is Array: for ab: Dictionary in parsed: var ab_name := str(ab.get("name", ab.get("Name", ""))) var ab_desc := str(ab.get("description", ab.get("Description", ""))) abil_str += "• %s" % ab_name if not ab_desc.is_empty(): abil_str += ": %s" % ab_desc abil_str += "\n" _ctx_abil_lbl.text = abil_str.strip_edges() _ctx_popup.visible = true # ── Hand card ArchSpirit routing ────────────────────────────────────────────── func _on_hand_card_clicked(iid: String, _panel: PanelContainer) -> void: # Dedup: the same physical click can arrive twice if a stale queue_freed widget # still overlaps the live one (see _rebuild_hand). Ignore the second call in # the same engine frame for the same card instance. var cf := Engine.get_process_frames() if cf == _last_click_frame and _last_click_iid == iid: print("[HandClick] dedup suppressed iid=", iid.substr(0,8)) return _last_click_frame = cf _last_click_iid = iid print("Clicked x times: ", count) count += 1 if not Game.is_my_turn(): return var card := _find_hand_card(iid) #print(card.get("name", "name failed")) if card.is_empty(): return # ArchSpirit in hand → Ascend or Transition. if card.get("cardType", "") == "ArchSpirit": var tier : int = int(card.get("tier", 0)) var cur_tier : int = _get_my_arch_tier() if tier == cur_tier + 1: _confirm_ascend(card) elif tier == 1 and cur_tier >= 1: _confirm_transition(card) return # Terramorpha → multi-tile flow (only if player can afford it). if card.get("cardType", "") == "Terramorpha": if Game.get_my_player().get("currentSp", 0) < card.get("spCost", 0): return _sel_card_id = iid _terra_targets = [] print("_terra Array clean. _terra_count: ", _terra_count) _set_mode(Mode.TERRAMORPHA_SELECT) _terra_count = _terra_count_for_card(card) _clear_highlights() _highlight_tiles(_valid_play_tiles(card), HI_GREEN) return # Ruin — server auto-places it; channel immediately on click. if card.get("cardType", "") == "Ruin": Game.send_play_card(iid, 0, 0) return # Deselect if same card clicked again. if _mode == Mode.CARD_FROM_HAND and _sel_card_id == iid: print("Deselect") _set_mode(Mode.NONE); return # If switching cards (or coming from TERRAMORPHA_SELECT), explicitly reset # so the previous card's scale-up tween is released before entering the new mode. if _mode in [Mode.CARD_FROM_HAND, Mode.TERRAMORPHA_SELECT]: print("switching cards catch") _set_mode(Mode.NONE) # Normal Spirit / Repentance / Instinct. _sel_card_id = iid _set_mode(Mode.CARD_FROM_HAND) _clear_highlights() _highlight_tiles(_valid_play_tiles(card), HI_GREEN) # ── Hand display ────────────────────────────────────────────────────────────── func _rebuild_hand(hand: Array) -> void: # Use remove_child + queue_free (not queue_free alone) so stale widgets are # immediately pulled from the GUI tree. queue_free() alone keeps the node in # get_children() and receiving input events until end-of-frame; if two state # updates arrive in the same frame we'd have two overlapping CardWidgets at the # same position → two card_pressed emissions → double _on_hand_card_clicked. for c in _hand_cards.get_children(): _hand_cards.remove_child(c) c.queue_free() for card: Dictionary in hand: _hand_cards.add_child(_make_hand_card(card)) func _make_hand_card(card: Dictionary) -> Control: var iid : String = card.get("instanceId", "") # Instantiate the shared CardWidget scene used by the collection UI. # Build a def dict from the live card data. CardWidget reads "movementPoints" # but the CardInstanceDto field is "maxMp", so alias it here. var widget : PanelContainer = _CARD_WIDGET_SCENE.instantiate() widget.set_meta("card_instance_id", iid) var def := card.duplicate() def["movementPoints"] = card.get("maxMp", null) widget.setup(card, def) # Compact the card for the hand area: shrink art and hide the detailed # stats grid (HP/ATK/DEF/MP/range). Name, SP/ST cost, genus, and type # remain visible; long-press context popup shows full unit stats. var art_area := widget.get_node_or_null("Margin/VBox/ArtArea") if art_area is Control: (art_area as Control).custom_minimum_size = Vector2(0, 80) var stats_grid := widget.get_node_or_null("Margin/VBox/StatsGrid") if stats_grid is CanvasItem: (stats_grid as CanvasItem).visible = false # CardWidget emits card_pressed(definition_id); forward as hand-card click. widget.card_pressed.connect(func(_def_id: String) -> void: _on_hand_card_clicked(iid, widget)) return widget func _refresh_hand_selection() -> void: for widget in _hand_cards.get_children(): if not widget.has_meta("card_instance_id"): continue var iid : String = str(widget.get_meta("card_instance_id")) var sel : bool = ((_mode == Mode.CARD_FROM_HAND or _mode == Mode.TERRAMORPHA_SELECT) and _sel_card_id == iid) var prev_sel : bool = widget.get_meta("_sel", false) if widget.has_method("set_selected"): widget.set_selected(sel) # Tween scale on selection change. # IMPORTANT: defer the tween + z_index update so they run AFTER the # current input event is fully processed. Setting z_index synchronously # while a mouse button is held causes Godot 4 to re-evaluate GUI focus # and deliver a synthetic second pressed=true event → immediate deselect. if sel != prev_sel: widget.set_meta("_sel", sel) _tween_hand_card.call_deferred(widget, sel) func _tween_hand_card(widget: Control, sel: bool) -> void: if not is_instance_valid(widget): return widget.pivot_offset = widget.size * 0.5 var tw := create_tween() if sel: tw.tween_property(widget, "scale", Vector2(1.12, 1.12), 0.14) widget.z_index = 20 else: tw.tween_property(widget, "scale", Vector2(1.0, 1.0), 0.10) widget.z_index = 0 func _find_hand_card(iid: String) -> Dictionary: for card: Dictionary in Game.get_hand(): if card.get("instanceId", "") == iid: return card return {} # ── HUD update ──────────────────────────────────────────────────────────────── func _update_hud(state: Dictionary) -> void: var phase : String = state.get("phase", "") var turn : int = state.get("turnNumber", 1) var is_mine : bool = Game.is_my_turn() var my : Dictionary = Game.get_my_player() var opp : Dictionary = Game.get_opponent() _phase_lbl.text = "Phase: %s" % phase _turn_lbl.text = "Turn %d — %s" % [turn, "Your turn" if is_mine else "Opponent's turn"] _turn_lbl.modulate = Color(0.4, 1.0, 0.5) if is_mine else Color(1.0, 0.6, 0.6) _sp_lbl.text = "SP: %d" % int(my.get("currentSp", 0)) _st_lbl.text = "ST: %d" % int(my.get("currentSt", 0)) _deck_lbl.text = "Deck: %d" % int(my.get("deckCount", 0)) _opp_name_lbl.text = Game.opponent_name if not Game.opponent_name.is_empty() \ else str(opp.get("accountId", "Opponent")).substr(0, 8) _opp_hand_lbl.text = "Hand: %d" % int(opp.get("handCount", 0)) _opp_deck_lbl.text = "Deck: %d" % int(opp.get("deckCount", 0)) _draw_btn.visible = (phase == "Draw" and is_mine) _end_turn_btn.visible = (phase == "Main" and is_mine) _end_turn_btn.disabled = not is_mine if phase == "Placement": var my_arch : Dictionary = my.get("archSpirit", {}) var i_have_placed : bool = not my_arch.is_empty() and my_arch.get("position") != null if not i_have_placed: _phase_lbl.text = "Phase: Placement — click a tile to place your ArchSpirit" if _mode != Mode.PLACEMENT: _set_mode(Mode.PLACEMENT) _clear_highlights() _highlight_tiles(_valid_placement_tiles(), HI_GREEN) else: _phase_lbl.text = "Phase: Placement — waiting for opponent…" if _mode == Mode.PLACEMENT: _set_mode(Mode.NONE) # ── Discard viewer ──────────────────────────────────────────────────────────── func _show_own_discard() -> void: _show_discard_for("Your Discard", Game.get_my_player().get("discard", [])) func _show_opp_discard() -> void: _show_discard_for("Opponent Discard", Game.get_opponent().get("discard", [])) func _show_discard_for(title: String, cards: Array) -> void: _dv_title.text = "%s (%d)" % [title, cards.size()] for c in _dv_list.get_children(): c.queue_free() if cards.is_empty(): var lbl := Label.new() lbl.text = "(empty)" lbl.add_theme_color_override("font_color", Color(0.55, 0.55, 0.6)) _dv_list.add_child(lbl) else: for card: Dictionary in cards: _dv_list.add_child(_make_discard_row(card)) _dv_overlay.visible = true func _make_discard_row(card: Dictionary) -> Control: var hbox := HBoxContainer.new() hbox.add_theme_constant_override("separation", 8) hbox.custom_minimum_size = Vector2(0, 32) var type_lbl := Label.new() type_lbl.text = "[%s]" % card.get("cardType", "?") type_lbl.add_theme_font_size_override("font_size", 11) type_lbl.add_theme_color_override("font_color", Color(0.6, 0.6, 0.7)) type_lbl.custom_minimum_size = Vector2(90, 0) type_lbl.size_flags_vertical = Control.SIZE_SHRINK_CENTER hbox.add_child(type_lbl) var name_lbl := Label.new() name_lbl.text = card.get("name", "Unknown") name_lbl.add_theme_font_size_override("font_size", 13) name_lbl.size_flags_horizontal = Control.SIZE_EXPAND_FILL name_lbl.size_flags_vertical = Control.SIZE_SHRINK_CENTER hbox.add_child(name_lbl) var aff_lbl := Label.new() aff_lbl.text = card.get("affinity", "") aff_lbl.add_theme_font_size_override("font_size", 11) aff_lbl.add_theme_color_override("font_color", Color(0.6, 0.7, 0.85)) aff_lbl.size_flags_vertical = Control.SIZE_SHRINK_CENTER hbox.add_child(aff_lbl) return hbox # ── Hold timer → context popup ──────────────────────────────────────────────── func _on_hold_timer_fired() -> void: if _held_coord.x < 0: return var tile := Game.get_tile(_held_coord.x, _held_coord.y) if tile.is_empty(): return var aff : String = tile.get("resolvedAffinity", "Void") _ctx_tile_lbl.text = "Tile (%d,%d) — %s" % [_held_coord.x, _held_coord.y, aff] var _raw_occ = tile.get("occupantId") var occupant_id : String = _raw_occ if _raw_occ is String else "" if occupant_id.is_empty(): _ctx_unit_lbl.text = "" _ctx_abil_lbl.text = "" else: var unit := Game.get_unit_by_id(occupant_id) _ctx_unit_lbl.text = "%s HP %d/%d DEF %d/%d ATK %d" % [ unit.get("name", "?"), int(unit.get("currentHealth", 0)), int(unit.get("maxHealth", 0)), int(unit.get("currentDefense", 0)), int(unit.get("maxDefense", 0)), int(unit.get("damage", 0))] var abil_str := "" var _raw_abil_hud = unit.get("abilitiesJson") var parsed = JSON.parse_string("[]" if _raw_abil_hud == null else str(_raw_abil_hud)) if parsed is Array: for ab: Dictionary in parsed: abil_str += "• %s\n" % str(ab.get("name", "")) _ctx_abil_lbl.text = abil_str.strip_edges() _ctx_popup.visible = true # ── Game over ───────────────────────────────────────────────────────────────── func _on_game_over(winner_id: String, win_condition: String, winner_delta: int, loser_delta: int) -> void: var i_won : bool = (winner_id == Auth.user_id) _go_result_lbl.text = "Victory!" if i_won else "Defeat" _go_result_lbl.modulate = Color(0.4, 1.0, 0.5) if i_won else Color(1.0, 0.4, 0.4) var my_delta : int = winner_delta if i_won else loser_delta _go_rank_lbl.text = "Win by %s | Rank %s%d" % [ win_condition, "+" if my_delta >= 0 else "", my_delta] _go_overlay.visible = true # ── State → scene ───────────────────────────────────────────────────────────── func _on_state_updated(state: Dictionary) -> void: print("[StateUpdate] phase=", state.get("phase","?"), " mode=", _mode, " sel_card=", _sel_card_id.substr(0, 8) if not _sel_card_id.is_empty() else "none") _rebuild_ownership(state) # Orient camera behind the local player's row on the first state with playerOneAccountId. if not _camera_oriented: var p1_id : String = str(state.get("playerOneAccountId", "")) if not p1_id.is_empty(): _camera_oriented = true var bh := float(Game.board_height()) # Shift cam_pivot toward the opponent's side (30 % of board half-length) # so the player's own row appears in the lower-middle of the screen, # above the hand panel — not hidden behind it. var pivot_offset := (bh - 1.0) * 0.3 if Auth.user_id.to_lower() == p1_id.to_lower(): # P1 row is at world -Z. Camera looks from -Z toward +Z → yaw=180°. # Shift pivot toward world -Z so P1's row is NOT at the very bottom. _cam_yaw = 180.0 _cam_pivot = Vector3(0.0, 0.0, -pivot_offset) else: # P2 row is at world +Z (default yaw=0°). _cam_pivot = Vector3(0.0, 0.0, pivot_offset) _apply_camera() var board : Dictionary = state.get("board", {}) if _tile_bodies.is_empty() and not board.is_empty(): _build_board(board) elif not board.is_empty(): for tile: Dictionary in board.get("tiles", []): var c : Dictionary = tile.get("coord", {}) _update_tile_affinity(c.get("x", 0), c.get("y", 0), tile.get("resolvedAffinity", "Void")) _rebuild_units(state) var hand := Game.get_hand() print("[GameScreen] state phase=", state.get("phase","?"), " my_player_found=", not Game.get_my_player().is_empty(), " hand_size=", hand.size(), " my_id=", Auth.user_id.substr(0,8)) _rebuild_hand(hand) _update_hud(state) # After a state update, preserve hand-card and unit selections where possible. # A state push from the server (e.g. opponent action, draw echo) must not # silently clear tile highlights that the player just set up. match _mode: Mode.NONE, Mode.PLACEMENT: pass # placement highlights are managed in _update_hud above Mode.CARD_FROM_HAND, Mode.TERRAMORPHA_SELECT: # Keep selection only if the card is still in our hand. var sel_card := _find_hand_card(_sel_card_id) if sel_card.is_empty(): print("[StateUpdate] selected card gone — clearing mode") _set_mode(Mode.NONE) else: # Re-apply highlights: board/units may have changed. print("[StateUpdate] preserving CARD_FROM_HAND, re-highlighting") _clear_highlights() _highlight_tiles(_valid_play_tiles(sel_card), HI_GREEN) _refresh_hand_selection() # mark the (new) widget as selected _: # Unit selected, sacrifice, ability — clear these on any state change # because unit positions / health / eligibility may have changed. print("This is firing") _set_mode(Mode.NONE) # Auto-draw. if state.get("phase", "") == "Draw" and Game.is_my_turn(): await get_tree().create_timer(0.3).timeout Game.send_draw() # ── Action buttons ──────────────────────────────────────────────────────────── func _on_draw_pressed() -> void: Game.send_draw() func _on_end_turn_pressed() -> void: _set_mode(Mode.NONE); Game.send_end_turn() func _on_concede_pressed() -> void: var dlg := ConfirmationDialog.new() dlg.title = "Concede" dlg.dialog_text = "Are you sure you want to concede?" dlg.ok_button_text = "Concede" dlg.cancel_button_text = "Cancel" dlg.min_size = Vector2(280, 100) add_child(dlg) dlg.popup_centered() dlg.confirmed.connect(func() -> void: Game.send_concede(); dlg.queue_free()) dlg.canceled.connect(func() -> void: dlg.queue_free())