Delta state system: replace full-push with game.state_delta

After any game action, push a structured GameStateDelta instead of
the full GameStateDto to both players and spectators. Full state is
preserved for: initial connect (game.ready), reconnect/get_state,
spectate ACK, and turn-timer expiry.

Server:
- GameMessages.cs: add GameStateDeltaPush, GameStateDelta, TileDelta,
  UnitDelta, PlayerStatsDelta, GameMetaDelta record types
- GameEngine.cs: make ToCardDto internal (used by differ)
- GameStateDiffer.cs: new file — ComputeDelta (viewer-specific) and
  ComputeSpectatorDelta; diffs tiles, field units, hands, discards,
  archs, player stats, and game meta
- GameHandlerBase.cs: PushStateToPlayersAsync gains optional prevState
  param; when provided pushes delta, else falls back to full push
- All 10 action handlers: pass prev state to PushStateToPlayersAsync

Client:
- Game.gd: _state_version tracking, _apply_delta, _merge_unit_delta,
  request_sync, game.state_delta push handler with auto-resync on gap
- in_game_settings.gd + InGameSettings.tscn: Request Sync button

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
dingo
2026-03-21 06:54:33 -04:00
co-authored by Claude Happy
parent c93aaf64c0
commit cf5089ae50
17 changed files with 735 additions and 43 deletions
+208 -8
View File
@@ -39,10 +39,11 @@ signal both_idle_warning(session_id: String)
# ── State ─────────────────────────────────────────────────────────────────────
var session_id : String = ""
var state : Dictionary = {}
var opponent_name : String = ""
var is_spectating : bool = false
var session_id : String = ""
var state : Dictionary = {}
var opponent_name : String = ""
var is_spectating : bool = false
var _state_version : int = -1
# ── Lifecycle ─────────────────────────────────────────────────────────────────
@@ -52,10 +53,11 @@ func _ready() -> void:
func _clear_state() -> void:
session_id = ""
state = {}
opponent_name = ""
is_spectating = false
session_id = ""
state = {}
opponent_name = ""
is_spectating = false
_state_version = -1
## Start spectating a game session. State is applied from the server ack.
@@ -282,13 +284,22 @@ func _apply_state_from_payload(p: Variant) -> void:
if s.is_empty():
print("[Game] _apply_state_from_payload: no 'state' key in payload ", JSON.stringify(p))
return
_state_version = int(s.get("stateVersion", -1))
print("[Game] state applied phase=", s.get("phase","?"),
" turn=", s.get("turnNumber","?"),
" ver=", _state_version,
" activePlayer=", str(s.get("activePlayerAccountId","?")).substr(0,8))
state = s
state_updated.emit(state)
## Request a full state resync from the server (e.g. from in-game settings, or auto on missed delta).
func request_sync() -> void:
if session_id.is_empty(): return
print("[Game] requesting full state sync")
_fetch_state()
func _player_by_id(account_id: String) -> Dictionary:
for p: Dictionary in state.get("players", []):
if str(p.get("accountId", "")).to_lower() == account_id.to_lower():
@@ -296,6 +307,178 @@ func _player_by_id(account_id: String) -> Dictionary:
return {}
func _apply_delta(delta: Dictionary) -> void:
# 1. Changed tiles
var changed_tiles: Array = delta.get("changedTiles", [])
if changed_tiles != null:
var tiles: Array = state.get("board", {}).get("tiles", [])
for td: Dictionary in changed_tiles:
var tx := int(td.get("x", -1))
var ty := int(td.get("y", -1))
for tile: Dictionary in tiles:
var c: Dictionary = tile.get("coord", {})
if c.get("x", -1) == tx and c.get("y", -1) == ty:
if td.has("base1") and td["base1"] != null: tile["base1"] = td["base1"]
if td.has("base2") and td["base2"] != null: tile["base2"] = td["base2"]
if td.has("resolvedAffinity") and td["resolvedAffinity"] != null: tile["resolvedAffinity"] = td["resolvedAffinity"]
if td.has("occupantCleared") and bool(td["occupantCleared"]): tile["occupantId"] = null; tile["occupantOwner"] = null
elif td.has("occupantId") and td["occupantId"] != null: tile["occupantId"] = td["occupantId"]
if td.has("occupantOwner") and td["occupantOwner"] != null: tile["occupantOwner"] = td["occupantOwner"]
if td.has("ruinCleared") and bool(td["ruinCleared"]): tile["ruinId"] = null; tile["ruinOwner"] = null
elif td.has("ruinId") and td["ruinId"] != null: tile["ruinId"] = td["ruinId"]
if td.has("ruinOwner") and td["ruinOwner"] != null: tile["ruinOwner"] = td["ruinOwner"]
break
# 2. Added units (new units entering the field)
var added_units: Array = delta.get("addedUnits", [])
if added_units != null:
for unit: Dictionary in added_units:
var owner_id := str(unit.get("ownerId", "")) # not on CardInstanceDto, use position to find by ownerId?
# CardInstanceDto doesn't carry ownerId; find the right player by checking which player
# doesn't already have this unit. We append to the player who owns the tile.
# Fallback: use the unit's position coord to find the tile's occupant owner.
var placed := false
for p: Dictionary in state.get("players", []):
var field: Array = p.get("field", [])
# Check if this player already has the unit (shouldn't happen)
var found := false
for u: Dictionary in field:
if u.get("instanceId", "") == unit.get("instanceId", ""):
found = true
break
if not found and not placed:
# Determine ownership from the tile's occupantOwner matching this player's accountId
var pos: Dictionary = unit.get("position", {})
if not pos.is_empty():
var tile := get_tile(int(pos.get("x", -1)), int(pos.get("y", -1)))
if str(tile.get("occupantOwner", "")).to_lower() == str(p.get("accountId", "")).to_lower():
field.append(unit)
placed = true
# Fallback if we couldn't place via tile: append to active player's field
if not placed:
var my_p := get_my_player()
if not my_p.is_empty():
my_p.get("field", []).append(unit)
# 3. Removed unit IDs
var removed_ids: Array = delta.get("removedUnitIds", [])
if removed_ids != null:
for iid: String in removed_ids:
for p: Dictionary in state.get("players", []):
var field: Array = p.get("field", [])
for i in range(field.size() - 1, -1, -1):
if field[i].get("instanceId", "") == iid:
field.remove_at(i)
break
# 4. Changed units (merge non-null UnitDelta fields)
var changed_units: Array = delta.get("changedUnits", [])
if changed_units != null:
for ud: Dictionary in changed_units:
var iid := str(ud.get("instanceId", ""))
var unit := get_unit_by_id(iid)
if not unit.is_empty():
_merge_unit_delta(unit, ud)
# 5. Hand added / removed (own player only)
var hand_added: Array = delta.get("handAdded", [])
if hand_added != null and not hand_added.is_empty():
var my_hand: Array = get_my_player().get("hand", [])
for card: Dictionary in hand_added:
my_hand.append(card)
var hand_removed: Array = delta.get("handRemovedIds", [])
if hand_removed != null:
var my_hand: Array = get_my_player().get("hand", [])
for iid: String in hand_removed:
for i in range(my_hand.size() - 1, -1, -1):
if my_hand[i].get("instanceId", "") == iid:
my_hand.remove_at(i)
break
# 6. Discard added
var discard_added: Array = delta.get("discardAdded", [])
if discard_added != null and not discard_added.is_empty():
var my_discard: Array = get_my_player().get("discard", [])
for card: Dictionary in discard_added:
my_discard.append(card)
# 7. Opponent hand / deck counts
var opp_hand_count = delta.get("opponentHandCount", null)
var opp_deck_count = delta.get("opponentDeckCount", null)
var opp := get_opponent()
if not opp.is_empty():
if opp_hand_count != null: opp["handCount"] = int(opp_hand_count)
if opp_deck_count != null: opp["deckCount"] = int(opp_deck_count)
# 8. ArchSpirits
var own_arch_delta: Dictionary = delta.get("ownArchSpiritDelta", {})
if own_arch_delta != null and not own_arch_delta.is_empty():
var my_arch: Dictionary = get_my_player().get("archSpirit", {})
if not my_arch.is_empty():
_merge_unit_delta(my_arch, own_arch_delta)
var opp_arch_delta: Dictionary = delta.get("opponentArchSpiritDelta", {})
if opp_arch_delta != null and not opp_arch_delta.is_empty():
var opp_arch: Dictionary = get_opponent().get("archSpirit", {})
if not opp_arch.is_empty():
_merge_unit_delta(opp_arch, opp_arch_delta)
# 9. Player stats
var own_stats: Dictionary = delta.get("ownStatsDelta", {})
if own_stats != null and not own_stats.is_empty():
var my_p := get_my_player()
if not my_p.is_empty():
if own_stats.has("currentSp") and own_stats["currentSp"] != null: my_p["currentSp"] = int(own_stats["currentSp"])
if own_stats.has("currentSt") and own_stats["currentSt"] != null: my_p["currentSt"] = int(own_stats["currentSt"])
if own_stats.has("deckCount") and own_stats["deckCount"] != null: my_p["deckCount"] = int(own_stats["deckCount"])
if own_stats.has("handCount") and own_stats["handCount"] != null: my_p["handCount"] = int(own_stats["handCount"])
if own_stats.has("discardCount") and own_stats["discardCount"] != null: my_p["discardCount"] = int(own_stats["discardCount"])
var opp_stats: Dictionary = delta.get("opponentStatsDelta", {})
if opp_stats != null and not opp_stats.is_empty():
var opp_p := get_opponent()
if not opp_p.is_empty():
if opp_stats.has("currentSp") and opp_stats["currentSp"] != null: opp_p["currentSp"] = int(opp_stats["currentSp"])
if opp_stats.has("currentSt") and opp_stats["currentSt"] != null: opp_p["currentSt"] = int(opp_stats["currentSt"])
if opp_stats.has("deckCount") and opp_stats["deckCount"] != null: opp_p["deckCount"] = int(opp_stats["deckCount"])
if opp_stats.has("handCount") and opp_stats["handCount"] != null: opp_p["handCount"] = int(opp_stats["handCount"])
if opp_stats.has("discardCount") and opp_stats["discardCount"] != null: opp_p["discardCount"] = int(opp_stats["discardCount"])
# 10. Meta
var meta: Dictionary = delta.get("metaDelta", {})
if meta != null and not meta.is_empty():
if meta.has("phase") and meta["phase"] != null: state["phase"] = meta["phase"]
if meta.has("activePlayerAccountId") and meta["activePlayerAccountId"] != null: state["activePlayerAccountId"] = meta["activePlayerAccountId"]
if meta.has("turnNumber") and meta["turnNumber"] != null: state["turnNumber"] = int(meta["turnNumber"])
_state_version = int(delta.get("stateVersion", _state_version))
print("[Game] delta applied ver=", _state_version,
" phase=", state.get("phase","?"),
" turn=", state.get("turnNumber","?"))
state_updated.emit(state)
func _merge_unit_delta(unit: Dictionary, ud: Dictionary) -> void:
if ud.has("currentHealth") and ud["currentHealth"] != null: unit["currentHealth"] = int(ud["currentHealth"])
if ud.has("maxHealth") and ud["maxHealth"] != null: unit["maxHealth"] = int(ud["maxHealth"])
if ud.has("currentDefense") and ud["currentDefense"] != null: unit["currentDefense"] = int(ud["currentDefense"])
if ud.has("maxDefense") and ud["maxDefense"] != null: unit["maxDefense"] = int(ud["maxDefense"])
if ud.has("damage") and ud["damage"] != null: unit["damage"] = int(ud["damage"])
if ud.has("isExhausted") and ud["isExhausted"] != null: unit["isExhausted"] = bool(ud["isExhausted"])
if ud.has("canMove") and ud["canMove"] != null: unit["canMove"] = bool(ud["canMove"])
if ud.has("canAttack") and ud["canAttack"] != null: unit["canAttack"] = bool(ud["canAttack"])
if ud.has("canBeAttacked") and ud["canBeAttacked"] != null: unit["canBeAttacked"] = bool(ud["canBeAttacked"])
if ud.has("canUseAbility") and ud["canUseAbility"] != null: unit["canUseAbility"] = bool(ud["canUseAbility"])
if ud.has("currentMp") and ud["currentMp"] != null: unit["currentMp"] = int(ud["currentMp"])
if ud.has("maxMp") and ud["maxMp"] != null: unit["maxMp"] = int(ud["maxMp"])
if ud.has("extraAttacksRemaining") and ud["extraAttacksRemaining"] != null: unit["extraAttacksRemaining"] = int(ud["extraAttacksRemaining"])
if ud.has("position") and ud["position"] != null: unit["position"] = ud["position"]
if ud.has("effectsJson") and ud["effectsJson"] != null: unit["effectsJson"] = ud["effectsJson"]
if ud.has("abilitiesJson") and ud["abilitiesJson"] != null: unit["abilitiesJson"] = ud["abilitiesJson"]
if ud.has("abilityUsesJson") and ud["abilityUsesJson"] != null: unit["abilityUsesJson"] = ud["abilityUsesJson"]
func _on_server_push(type: String, payload: Variant) -> void:
if type.begins_with("game.") or type.begins_with("matchmaking."):
print("[Game] PUSH ", type, " ", JSON.stringify(payload).substr(0, 200))
@@ -314,14 +497,31 @@ func _on_server_push(type: String, payload: Variant) -> void:
var d := payload as Dictionary
var s := d.get("state", {}) as Dictionary
if not s.is_empty():
_state_version = int(s.get("stateVersion", -1))
print("[Game] PUSH state_update phase=", s.get("phase","?"),
" turn=", s.get("turnNumber","?"),
" ver=", _state_version,
" activePlayer=", str(s.get("activePlayerAccountId","?")).substr(0,8))
state = s
state_updated.emit(state)
else:
print("[Game] PUSH state_update: no 'state' key")
"game.state_delta":
var d := payload as Dictionary
var delta := d.get("delta", {}) as Dictionary
if delta.is_empty(): return
var v := int(delta.get("stateVersion", -1))
if _state_version >= 0 and v <= _state_version:
# Already up to date — acting player received full state in ACK
return
if _state_version >= 0 and v > _state_version + 1:
print("[Game] WARN: missed delta (have %d, got %d) — requesting full sync" \
% [_state_version, v])
_fetch_state()
return
_apply_delta(delta)
"game.over":
var d := payload as Dictionary
var winner : String = str(d.get("winnerAccountId", ""))
@@ -111,6 +111,14 @@ text = "Center camera on selected unit"
[node name="HSeparator3" type="HSeparator" parent="MarginContainer/VBoxContainer"]
layout_mode = 2
[node name="SyncBtn" type="Button" parent="MarginContainer/VBoxContainer"]
unique_name_in_owner = true
layout_mode = 2
text = "Request Sync"
[node name="HSeparator4" type="HSeparator" parent="MarginContainer/VBoxContainer"]
layout_mode = 2
[node name="ConcedeBtn" type="Button" parent="MarginContainer/VBoxContainer"]
unique_name_in_owner = true
layout_mode = 2
@@ -7,6 +7,7 @@ extends PanelContainer
@onready var _sfx_slider : HSlider = %SfxSlider
@onready var _sfx_mute : CheckButton = %SfxMute
@onready var _cam_follow : CheckButton = %CameraFollowUnit
@onready var _sync_btn : Button = %SyncBtn
@onready var _concede_btn : Button = %ConcedeBtn
@onready var _confirm_row : HBoxContainer = %ConcedeConfirmRow
@onready var _confirm_yes : Button = %ConcedeYes
@@ -25,6 +26,7 @@ func _ready() -> void:
_sfx_mute.toggled.connect(_on_sfx_mute_toggled)
_cam_follow.toggled.connect(func(v: bool) -> void: Settings.camera_follow_unit = v)
_sync_btn.pressed.connect(_on_sync_pressed)
_concede_btn.pressed.connect(_on_concede_pressed)
_confirm_yes.pressed.connect(_on_concede_confirmed)
_confirm_no.pressed.connect(func() -> void: _confirm_row.visible = false; _concede_btn.visible = true)
@@ -68,6 +70,15 @@ func _on_sfx_mute_toggled(v: bool) -> void:
Settings.sfx_muted = v
_sfx_slider.modulate.a = 0.4 if v else 1.0
func _on_sync_pressed() -> void:
_sync_btn.text = "Syncing..."
_sync_btn.disabled = true
Game.request_sync()
get_tree().create_timer(1.5).timeout.connect(func() -> void:
if is_instance_valid(_sync_btn):
_sync_btn.text = "Request Sync"
_sync_btn.disabled = false)
func _on_concede_pressed() -> void:
_concede_btn.visible = false
_confirm_row.visible = true