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
+1 -1
View File
@@ -1255,7 +1255,7 @@ public static class GameEngine
throw new GameException($"INVALID_PHASE:{state.Phase}");
}
private static CardInstanceDto ToCardDto(CardInstance c)
internal static CardInstanceDto ToCardDto(CardInstance c)
{
var fc = c as FieldCard;
return new(
+72
View File
@@ -389,6 +389,78 @@ public sealed record LobbyRuleSuggestionPush(
/// <summary>Pushed to the guest when the host rejects their rule suggestion.</summary>
public sealed record LobbyRuleSuggestionRejectedPush(Guid LobbyId);
/// <summary>
/// Pushed to each viewer after any game action that changes state.
/// Replaces the full <see cref="GameStateUpdatePush"/> for incremental updates.
/// </summary>
public sealed record GameStateDeltaPush(GameStateDelta Delta);
/// <summary>
/// Viewer-specific state delta. Null collections mean no change for that category.
/// Own hand is shown in full; opponent hand = count only.
/// </summary>
public sealed record GameStateDelta(
int StateVersion,
IReadOnlyList<TileDelta>? ChangedTiles,
IReadOnlyList<CardInstanceDto>? AddedUnits,
IReadOnlyList<string>? RemovedUnitIds,
IReadOnlyList<UnitDelta>? ChangedUnits,
IReadOnlyList<CardInstanceDto>? HandAdded,
IReadOnlyList<string>? HandRemovedIds,
IReadOnlyList<CardInstanceDto>? DiscardAdded,
int? OpponentHandCount,
int? OpponentDeckCount,
UnitDelta? OwnArchSpiritDelta,
UnitDelta? OpponentArchSpiritDelta,
PlayerStatsDelta? OwnStatsDelta,
PlayerStatsDelta? OpponentStatsDelta,
GameMetaDelta? MetaDelta);
public sealed record TileDelta(
int X,
int Y,
string? Base1,
string? Base2,
string? ResolvedAffinity,
string? OccupantId,
bool OccupantCleared,
string? OccupantOwner,
string? RuinId,
bool RuinCleared,
string? RuinOwner);
public sealed record UnitDelta(
string InstanceId,
int? CurrentHealth,
int? MaxHealth,
int? CurrentDefense,
int? MaxDefense,
int? Damage,
bool? IsExhausted,
bool? CanMove,
bool? CanAttack,
bool? CanBeAttacked,
bool? CanUseAbility,
int? CurrentMp,
int? MaxMp,
int? ExtraAttacksRemaining,
CoordDto? Position,
string? EffectsJson,
string? AbilitiesJson,
string? AbilityUsesJson);
public sealed record PlayerStatsDelta(
int? CurrentSp,
int? CurrentSt,
int? DeckCount,
int? HandCount,
int? DiscardCount);
public sealed record GameMetaDelta(
string? Phase,
string? ActivePlayerAccountId,
int? TurnNumber);
// ── DTOs ─────────────────────────────────────────────────────────────────────
/// <summary>
+366
View File
@@ -0,0 +1,366 @@
namespace SOR.Game;
using System.Text.Json;
using SOR.Game.Grid;
/// <summary>
/// Computes a <see cref="GameStateDelta"/> from two <see cref="GameState"/> snapshots.
/// Used to send only changed data after each game action instead of the full state.
/// </summary>
internal static class GameStateDiffer
{
private static readonly JsonSerializerOptions _json = new(JsonSerializerDefaults.Web)
{
WriteIndented = false,
};
/// <summary>
/// Compute a viewer-specific delta (own hand visible; opponent hand = count only).
/// </summary>
public static GameStateDelta ComputeDelta(GameState prev, GameState next, string viewerAccountId)
{
var changedTiles = DiffTiles(prev, next);
var (addedUnits, removedIds, changed) = DiffAllFieldUnits(prev, next);
// Viewer's zones
prev.Players.TryGetValue(viewerAccountId, out var prevViewer);
next.Players.TryGetValue(viewerAccountId, out var nextViewer);
List<CardInstanceDto>? handAdded = null;
List<string>? handRemovedIds = null;
List<CardInstanceDto>? discardAdded = null;
if (prevViewer != null && nextViewer != null)
{
var prevHandIds = new HashSet<string>(prevViewer.Hand.Select(c => c.InstanceId));
var nextHandIds = new HashSet<string>(nextViewer.Hand.Select(c => c.InstanceId));
var added = nextHandIds.Except(prevHandIds).ToHashSet();
if (added.Count > 0)
handAdded = nextViewer.Hand
.Where(c => added.Contains(c.InstanceId))
.Select(GameEngine.ToCardDto)
.ToList();
var removed = prevHandIds.Except(nextHandIds).ToList();
if (removed.Count > 0)
handRemovedIds = removed;
// Discard: only appended; emit new tail entries
if (nextViewer.Discard.Count > prevViewer.Discard.Count)
discardAdded = nextViewer.Discard
.Skip(prevViewer.Discard.Count)
.Select(GameEngine.ToCardDto)
.ToList();
}
// Opponent's counts
var prevOpp = prev.Players.Values.FirstOrDefault(p => p.AccountId != viewerAccountId);
var nextOpp = next.Players.Values.FirstOrDefault(p => p.AccountId != viewerAccountId);
int? oppHandCount = null;
int? oppDeckCount = null;
if (prevOpp != null && nextOpp != null)
{
if (prevOpp.Hand.Count != nextOpp.Hand.Count) oppHandCount = nextOpp.Hand.Count;
if (prevOpp.Deck.Count != nextOpp.Deck.Count) oppDeckCount = nextOpp.Deck.Count;
}
// ArchSpirits
UnitDelta? ownArchDelta = null;
UnitDelta? oppArchDelta = null;
if (prevViewer?.ArchSpirit != null && nextViewer?.ArchSpirit != null)
ownArchDelta = DiffUnit(prevViewer.ArchSpirit, nextViewer.ArchSpirit);
if (prevOpp?.ArchSpirit != null && nextOpp?.ArchSpirit != null)
oppArchDelta = DiffUnit(prevOpp.ArchSpirit, nextOpp.ArchSpirit);
// Player stats
PlayerStatsDelta? ownStats = null;
PlayerStatsDelta? oppStats = null;
if (prevViewer != null && nextViewer != null)
ownStats = DiffPlayerStats(prevViewer, nextViewer);
if (prevOpp != null && nextOpp != null)
oppStats = DiffPlayerStats(prevOpp, nextOpp);
var metaDelta = DiffMeta(prev, next);
return new GameStateDelta(
StateVersion : next.NextActionSequence,
ChangedTiles : changedTiles,
AddedUnits : addedUnits,
RemovedUnitIds : removedIds,
ChangedUnits : changed,
HandAdded : handAdded,
HandRemovedIds : handRemovedIds,
DiscardAdded : discardAdded,
OpponentHandCount : oppHandCount,
OpponentDeckCount : oppDeckCount,
OwnArchSpiritDelta : ownArchDelta,
OpponentArchSpiritDelta : oppArchDelta,
OwnStatsDelta : ownStats,
OpponentStatsDelta : oppStats,
MetaDelta : metaDelta);
}
/// <summary>
/// Compute a spectator delta: tile/unit/archspirit/meta changes visible to all;
/// hand card details suppressed. P1 mapped to "own", P2 to "opponent" in the result.
/// </summary>
public static GameStateDelta ComputeSpectatorDelta(GameState prev, GameState next)
{
var changedTiles = DiffTiles(prev, next);
var (addedUnits, removedIds, changed) = DiffAllFieldUnits(prev, next);
// Map p1 → "own", p2 → "opponent" for archspirit and stats fields
prev.Players.TryGetValue(prev.PlayerOneAccountId, out var prevP1);
next.Players.TryGetValue(next.PlayerOneAccountId, out var nextP1);
var prevP2 = prev.Players.Values.FirstOrDefault(p => p.AccountId != prev.PlayerOneAccountId);
var nextP2 = next.Players.Values.FirstOrDefault(p => p.AccountId != next.PlayerOneAccountId);
UnitDelta? ownArchDelta = null;
UnitDelta? oppArchDelta = null;
if (prevP1?.ArchSpirit != null && nextP1?.ArchSpirit != null)
ownArchDelta = DiffUnit(prevP1.ArchSpirit, nextP1.ArchSpirit);
if (prevP2?.ArchSpirit != null && nextP2?.ArchSpirit != null)
oppArchDelta = DiffUnit(prevP2.ArchSpirit, nextP2.ArchSpirit);
PlayerStatsDelta? ownStats = null;
PlayerStatsDelta? oppStats = null;
if (prevP1 != null && nextP1 != null) ownStats = DiffPlayerStats(prevP1, nextP1);
if (prevP2 != null && nextP2 != null) oppStats = DiffPlayerStats(prevP2, nextP2);
var metaDelta = DiffMeta(prev, next);
return new GameStateDelta(
StateVersion : next.NextActionSequence,
ChangedTiles : changedTiles,
AddedUnits : addedUnits,
RemovedUnitIds : removedIds,
ChangedUnits : changed,
HandAdded : null,
HandRemovedIds : null,
DiscardAdded : null,
OpponentHandCount : null,
OpponentDeckCount : null,
OwnArchSpiritDelta : ownArchDelta,
OpponentArchSpiritDelta : oppArchDelta,
OwnStatsDelta : ownStats,
OpponentStatsDelta : oppStats,
MetaDelta : metaDelta);
}
// ── Helpers ───────────────────────────────────────────────────────────────
private static List<TileDelta>? DiffTiles(GameState prev, GameState next)
{
if (prev.Board == null || next.Board == null) return null;
List<TileDelta>? result = null;
foreach (var nextTile in next.Board.Tiles.Values)
{
var key = nextTile.Coord.ToKey();
if (!prev.Board.Tiles.TryGetValue(key, out var prevTile))
{
// New tile (board resize edge case — emit all fields)
result ??= new List<TileDelta>();
result.Add(new TileDelta(
X : nextTile.Coord.X,
Y : nextTile.Coord.Y,
Base1 : nextTile.Base1.ToString(),
Base2 : nextTile.Base2.ToString(),
ResolvedAffinity : AffinitySystem.Resolve(nextTile.Base1, nextTile.Base2).ToString(),
OccupantId : nextTile.OccupantId,
OccupantCleared : false,
OccupantOwner : nextTile.OccupantOwner,
RuinId : nextTile.RuinId,
RuinCleared : false,
RuinOwner : nextTile.RuinOwner));
continue;
}
bool base1Changed = prevTile.Base1 != nextTile.Base1;
bool base2Changed = prevTile.Base2 != nextTile.Base2;
bool occupantChanged = prevTile.OccupantId != nextTile.OccupantId;
bool occOwnerChanged = prevTile.OccupantOwner != nextTile.OccupantOwner;
bool ruinChanged = prevTile.RuinId != nextTile.RuinId;
bool ruinOwnerChanged = prevTile.RuinOwner != nextTile.RuinOwner;
if (!base1Changed && !base2Changed && !occupantChanged &&
!occOwnerChanged && !ruinChanged && !ruinOwnerChanged)
continue;
result ??= new List<TileDelta>();
result.Add(new TileDelta(
X : nextTile.Coord.X,
Y : nextTile.Coord.Y,
Base1 : base1Changed ? nextTile.Base1.ToString() : null,
Base2 : base2Changed ? nextTile.Base2.ToString() : null,
ResolvedAffinity : (base1Changed || base2Changed)
? AffinitySystem.Resolve(nextTile.Base1, nextTile.Base2).ToString()
: null,
OccupantId : occupantChanged && nextTile.OccupantId != null ? nextTile.OccupantId : null,
OccupantCleared : occupantChanged && nextTile.OccupantId == null,
OccupantOwner : occOwnerChanged ? nextTile.OccupantOwner : null,
RuinId : ruinChanged && nextTile.RuinId != null ? nextTile.RuinId : null,
RuinCleared : ruinChanged && nextTile.RuinId == null,
RuinOwner : ruinOwnerChanged ? nextTile.RuinOwner : null));
}
return result;
}
private static (List<CardInstanceDto>? added, List<string>? removed, List<UnitDelta>? changed)
DiffAllFieldUnits(GameState prev, GameState next)
{
var prevById = new Dictionary<string, CardInstance>();
var nextById = new Dictionary<string, CardInstance>();
foreach (var ps in prev.Players.Values)
foreach (var u in ps.Field)
prevById[u.InstanceId] = u;
foreach (var ps in next.Players.Values)
foreach (var u in ps.Field)
nextById[u.InstanceId] = u;
List<CardInstanceDto>? added = null;
List<string>? removed = null;
List<UnitDelta>? changed = null;
foreach (var (id, nextUnit) in nextById)
{
if (!prevById.TryGetValue(id, out var prevUnit))
{
added ??= new List<CardInstanceDto>();
added.Add(GameEngine.ToCardDto(nextUnit));
}
else
{
var delta = DiffUnit(prevUnit, nextUnit);
if (delta != null)
{
changed ??= new List<UnitDelta>();
changed.Add(delta);
}
}
}
foreach (var id in prevById.Keys)
{
if (!nextById.ContainsKey(id))
{
removed ??= new List<string>();
removed.Add(id);
}
}
return (added, removed, changed);
}
private static UnitDelta? DiffUnit(CardInstance prevC, CardInstance nextC)
{
var prevFc = prevC as FieldCard;
var nextFc = nextC as FieldCard;
bool abilityUsesChanged = !AbilityUsesEqual(prevC.AbilityUsesThisTurn, nextC.AbilityUsesThisTurn);
bool anyChange =
prevC.CurrentHealth != nextC.CurrentHealth ||
prevC.MaxHealth != nextC.MaxHealth ||
prevC.CurrentDefense != nextC.CurrentDefense ||
prevC.MaxDefense != nextC.MaxDefense ||
prevC.Damage != nextC.Damage ||
prevC.IsExhausted != nextC.IsExhausted ||
prevC.CanMove != nextC.CanMove ||
prevC.CanAttack != nextC.CanAttack ||
prevC.CanBeAttacked != nextC.CanBeAttacked ||
prevC.CanUseAbility != nextC.CanUseAbility ||
(prevFc?.CurrentMp ?? 0) != (nextFc?.CurrentMp ?? 0) ||
prevC.MaxMp != nextC.MaxMp ||
prevC.ExtraAttacksRemaining != nextC.ExtraAttacksRemaining ||
prevFc?.Position != nextFc?.Position ||
prevC.EffectsJson != nextC.EffectsJson ||
prevC.AbilitiesJson != nextC.AbilitiesJson ||
abilityUsesChanged;
if (!anyChange) return null;
CoordDto? positionDelta = null;
if (prevFc?.Position != nextFc?.Position && nextFc?.Position is { } pos)
positionDelta = new CoordDto(pos.X, pos.Y);
string? abilityUsesJson = abilityUsesChanged && nextC.AbilityUsesThisTurn != null
? JsonSerializer.Serialize(nextC.AbilityUsesThisTurn, _json)
: null;
return new UnitDelta(
InstanceId : nextC.InstanceId,
CurrentHealth : prevC.CurrentHealth != nextC.CurrentHealth ? nextC.CurrentHealth : null,
MaxHealth : prevC.MaxHealth != nextC.MaxHealth ? nextC.MaxHealth : null,
CurrentDefense : prevC.CurrentDefense != nextC.CurrentDefense ? nextC.CurrentDefense : null,
MaxDefense : prevC.MaxDefense != nextC.MaxDefense ? nextC.MaxDefense : null,
Damage : prevC.Damage != nextC.Damage ? nextC.Damage : null,
IsExhausted : prevC.IsExhausted != nextC.IsExhausted ? nextC.IsExhausted : null,
CanMove : prevC.CanMove != nextC.CanMove ? nextC.CanMove : null,
CanAttack : prevC.CanAttack != nextC.CanAttack ? nextC.CanAttack : null,
CanBeAttacked : prevC.CanBeAttacked != nextC.CanBeAttacked ? nextC.CanBeAttacked : null,
CanUseAbility : prevC.CanUseAbility != nextC.CanUseAbility ? nextC.CanUseAbility : null,
CurrentMp : (prevFc?.CurrentMp ?? 0) != (nextFc?.CurrentMp ?? 0) ? nextFc?.CurrentMp : null,
MaxMp : prevC.MaxMp != nextC.MaxMp ? nextC.MaxMp : null,
ExtraAttacksRemaining : prevC.ExtraAttacksRemaining != nextC.ExtraAttacksRemaining ? nextC.ExtraAttacksRemaining : null,
Position : positionDelta,
EffectsJson : prevC.EffectsJson != nextC.EffectsJson ? nextC.EffectsJson : null,
AbilitiesJson : prevC.AbilitiesJson != nextC.AbilitiesJson ? nextC.AbilitiesJson : null,
AbilityUsesJson : abilityUsesJson);
}
private static PlayerStatsDelta? DiffPlayerStats(PlayerState prev, PlayerState next)
{
bool spChanged = prev.CurrentSp != next.CurrentSp;
bool stChanged = prev.CurrentSt != next.CurrentSt;
bool deckChanged = prev.Deck.Count != next.Deck.Count;
bool handChanged = prev.Hand.Count != next.Hand.Count;
bool discardChanged = prev.Discard.Count != next.Discard.Count;
if (!spChanged && !stChanged && !deckChanged && !handChanged && !discardChanged)
return null;
return new PlayerStatsDelta(
CurrentSp : spChanged ? next.CurrentSp : null,
CurrentSt : stChanged ? next.CurrentSt : null,
DeckCount : deckChanged ? next.Deck.Count : null,
HandCount : handChanged ? next.Hand.Count : null,
DiscardCount : discardChanged ? next.Discard.Count : null);
}
private static GameMetaDelta? DiffMeta(GameState prev, GameState next)
{
bool phaseChanged = prev.Phase != next.Phase;
bool activeChanged = prev.ActivePlayerAccountId != next.ActivePlayerAccountId;
bool turnChanged = prev.TurnNumber != next.TurnNumber;
if (!phaseChanged && !activeChanged && !turnChanged) return null;
return new GameMetaDelta(
Phase : phaseChanged ? next.Phase.ToString() : null,
ActivePlayerAccountId : activeChanged ? next.ActivePlayerAccountId : null,
TurnNumber : turnChanged ? next.TurnNumber : null);
}
private static bool AbilityUsesEqual(Dictionary<int, int>? a, Dictionary<int, int>? b)
{
if (a == null && b == null) return true;
if (a == null || b == null) return false;
if (a.Count != b.Count) return false;
foreach (var (k, v) in a)
if (!b.TryGetValue(k, out var bv) || bv != v) return false;
return true;
}
}
@@ -48,7 +48,7 @@ internal sealed class GameActivateAbilityHandler : GameHandlerBase, IMessageHand
await SaveStateAsync(_gameDb, session, newState, actorId, "game.activate_ability",
JsonSerializer.Serialize(req), ct, JsonSerializer.Serialize(dto));
await PushStateToPlayersAsync(_clientPush, session, newState, ct);
await PushStateToPlayersAsync(_clientPush, session, newState, ct, state);
return ServerMessage.Reply("game.activate_ability.ack", message.Seq,
new GameActivateAbilityResponse(dto));
@@ -49,7 +49,7 @@ internal sealed class GameAscendHandler : GameHandlerBase, IMessageHandler
await SaveStateAsync(_gameDb, session, newState, actorId, "game.ascend",
JsonSerializer.Serialize(req), ct, JsonSerializer.Serialize(dto));
await PushStateToPlayersAsync(_clientPush, session, newState, ct);
await PushStateToPlayersAsync(_clientPush, session, newState, ct, state);
return ServerMessage.Reply("game.ascend.ack", message.Seq,
new GameAscendResponse(dto));
@@ -86,7 +86,7 @@ internal sealed class GameAttackHandler : GameHandlerBase, IMessageHandler
}
else
{
await PushStateToPlayersAsync(_clientPush, session, newState, ct);
await PushStateToPlayersAsync(_clientPush, session, newState, ct, state);
}
return ServerMessage.Reply("game.attack.ack", message.Seq,
@@ -42,7 +42,7 @@ internal sealed class GameDrawHandler : GameHandlerBase, IMessageHandler
await SaveStateAsync(_gameDb, session, newState, actorId, "game.draw",
JsonSerializer.Serialize(req), ct, JsonSerializer.Serialize(dto));
await PushStateToPlayersAsync(_clientPush, session, newState, ct);
await PushStateToPlayersAsync(_clientPush, session, newState, ct, state);
return ServerMessage.Reply("game.draw.ack", message.Seq,
new GameDrawResponse(dto));
@@ -82,7 +82,7 @@ internal sealed class GameEndTurnHandler : GameHandlerBase, IMessageHandler
await SaveStateAsync(_gameDb, session, newState, actorId, "game.end_turn",
JsonSerializer.Serialize(req), ct, JsonSerializer.Serialize(stateDto));
await PushStateToPlayersAsync(_clientPush, session, newState, ct);
await PushStateToPlayersAsync(_clientPush, session, newState, ct, state);
// Reset the turn timer for the new active player.
_timerService.ResetTimer(session.Id, newState.Rules.TurnTimerSeconds,
+59 -24
View File
@@ -90,43 +90,78 @@ internal abstract class GameHandlerBase
}
/// <summary>
/// Push the updated (filtered) game state to both players and any current spectators.
/// Spectators receive a hand-hidden view via SpectatorRegistryService.Instance.
/// Push the updated game state to both players and any current spectators.
/// When <paramref name="prevState"/> is supplied a structured delta (<c>game.state_delta</c>)
/// is sent instead of the full state, reducing payload size.
/// Falls back to a full <c>game.state_update</c> push when prevState is null.
/// </summary>
internal static async Task PushStateToPlayersAsync(
IClientPush clientPush,
GameSession session,
GameState state,
CancellationToken ct)
CancellationToken ct,
GameState? prevState = null)
{
var p1Id = session.PlayerOneAccountId.ToString();
var p2Id = session.PlayerTwoAccountId.ToString();
var tasks = new List<Task>
if (prevState != null)
{
clientPush.PushAsync(p1Id,
ServerMessage.Push("game.state_update",
new GameStateUpdatePush(GameEngine.ToDto(state, p1Id))), ct),
clientPush.PushAsync(p2Id,
ServerMessage.Push("game.state_update",
new GameStateUpdatePush(GameEngine.ToDto(state, p2Id))), ct),
};
var d1 = GameStateDiffer.ComputeDelta(prevState, state, p1Id);
var d2 = GameStateDiffer.ComputeDelta(prevState, state, p2Id);
var registry = SpectatorRegistryService.Instance;
if (registry != null)
{
var spectators = registry.GetSpectators(session.Id);
if (spectators.Count > 0)
var tasks = new List<Task>
{
var spectatorDto = GameEngine.ToDtoSpectator(state);
foreach (var specId in spectators)
tasks.Add(clientPush.PushAsync(specId.ToString(),
ServerMessage.Push("game.state_update",
new GameStateUpdatePush(spectatorDto)), ct));
}
}
clientPush.PushAsync(p1Id,
ServerMessage.Push("game.state_delta", new GameStateDeltaPush(d1)), ct),
clientPush.PushAsync(p2Id,
ServerMessage.Push("game.state_delta", new GameStateDeltaPush(d2)), ct),
};
await Task.WhenAll(tasks);
var registry = SpectatorRegistryService.Instance;
if (registry != null)
{
var spectators = registry.GetSpectators(session.Id);
if (spectators.Count > 0)
{
var sd = GameStateDiffer.ComputeSpectatorDelta(prevState, state);
foreach (var specId in spectators)
tasks.Add(clientPush.PushAsync(specId.ToString(),
ServerMessage.Push("game.state_delta", new GameStateDeltaPush(sd)), ct));
}
}
await Task.WhenAll(tasks);
}
else
{
// Fallback: no previous state — push full state (initial connect, reconnect, timer expiry)
var tasks = new List<Task>
{
clientPush.PushAsync(p1Id,
ServerMessage.Push("game.state_update",
new GameStateUpdatePush(GameEngine.ToDto(state, p1Id))), ct),
clientPush.PushAsync(p2Id,
ServerMessage.Push("game.state_update",
new GameStateUpdatePush(GameEngine.ToDto(state, p2Id))), ct),
};
var registry = SpectatorRegistryService.Instance;
if (registry != null)
{
var spectators = registry.GetSpectators(session.Id);
if (spectators.Count > 0)
{
var spectatorDto = GameEngine.ToDtoSpectator(state);
foreach (var specId in spectators)
tasks.Add(clientPush.PushAsync(specId.ToString(),
ServerMessage.Push("game.state_update",
new GameStateUpdatePush(spectatorDto)), ct));
}
}
await Task.WhenAll(tasks);
}
}
// OP config snapshot — read from RuleSnapshotJson at finalization time.
@@ -49,7 +49,7 @@ internal sealed class GameMoveUnitHandler : GameHandlerBase, IMessageHandler
await SaveStateAsync(_gameDb, session, newState, actorId, "game.move_unit",
JsonSerializer.Serialize(req), ct, JsonSerializer.Serialize(dto));
await PushStateToPlayersAsync(_clientPush, session, newState, ct);
await PushStateToPlayersAsync(_clientPush, session, newState, ct, state);
return ServerMessage.Reply("game.move_unit.ack", message.Seq,
new GameMoveUnitResponse(dto));
@@ -56,7 +56,7 @@ internal sealed class GamePlaceArchSpiritHandler : GameHandlerBase, IMessageHand
await SaveStateAsync(_gameDb, session, newState, actorId, "game.place_arch_spirit",
JsonSerializer.Serialize(req), ct, JsonSerializer.Serialize(dto));
await PushStateToPlayersAsync(_clientPush, session, newState, ct);
await PushStateToPlayersAsync(_clientPush, session, newState, ct, state);
// Start the turn timer once both players have placed and turn 1 begins.
if (bothPlaced)
@@ -55,7 +55,7 @@ internal sealed class GamePlayCardHandler : GameHandlerBase, IMessageHandler
await SaveStateAsync(_gameDb, session, newState, actorId, "game.play_card",
JsonSerializer.Serialize(req), ct, JsonSerializer.Serialize(dto));
await PushStateToPlayersAsync(_clientPush, session, newState, ct);
await PushStateToPlayersAsync(_clientPush, session, newState, ct, state);
return ServerMessage.Reply("game.play_card.ack", message.Seq, new GamePlayCardResponse(dto));
}
@@ -48,7 +48,7 @@ internal sealed class GameSacrificeHandler : GameHandlerBase, IMessageHandler
await SaveStateAsync(_gameDb, session, newState, actorId, "game.sacrifice",
JsonSerializer.Serialize(req), ct, JsonSerializer.Serialize(dto));
await PushStateToPlayersAsync(_clientPush, session, newState, ct);
await PushStateToPlayersAsync(_clientPush, session, newState, ct, state);
return ServerMessage.Reply("game.sacrifice.ack", message.Seq,
new GameSacrificeResponse(dto));
@@ -49,7 +49,7 @@ internal sealed class GameTransitionHandler : GameHandlerBase, IMessageHandler
await SaveStateAsync(_gameDb, session, newState, actorId, "game.transition",
JsonSerializer.Serialize(req), ct, JsonSerializer.Serialize(dto));
await PushStateToPlayersAsync(_clientPush, session, newState, ct);
await PushStateToPlayersAsync(_clientPush, session, newState, ct, state);
return ServerMessage.Reply("game.transition.ack", message.Seq,
new GameTransitionResponse(dto));