- Track active effects with human-readable labels in AbilitySystem (LabelFromReversal/LabelFromTick for stat mods, status flags, DOT/HOT) - Add ActiveEffectDto to GameStateDto and GameStateDelta; delta now always includes the full effects list so clients are never stale - Add ResolveLabelFromEffectJson fallback for effects stored before the Label field was introduced (old game sessions show correct labels) - Client _append_active_effect_lines helper filters activeEffects by targetRef and appends formatted lines to the tile drawer for spirits, archspirits, spirit tokens, and ruins 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>
429 lines
19 KiB
C#
429 lines
19 KiB
C#
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 (private hand/discard only for the viewer;
|
|
/// all public data keyed by account ID).
|
|
/// </summary>
|
|
public static GameStateDelta ComputeDelta(GameState prev, GameState next, string viewerAccountId)
|
|
{
|
|
var changedTiles = DiffTiles(prev, next);
|
|
var (unitsAdded, unitsRemoved, unitsChanged) = DiffAllFieldUnits(prev, next);
|
|
|
|
var prevViewer = FindPlayer(prev, viewerAccountId);
|
|
var nextViewer = FindPlayer(next, viewerAccountId);
|
|
|
|
PrivateViewerDelta? privateByViewer = null;
|
|
if (prevViewer != null && nextViewer != null)
|
|
{
|
|
List<CardInstanceDto>? handAdded = null;
|
|
List<string>? handRemovedIds = null;
|
|
List<CardInstanceDto>? discardAdded = 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;
|
|
|
|
if (nextViewer.Discard.Count > prevViewer.Discard.Count)
|
|
discardAdded = nextViewer.Discard
|
|
.Skip(prevViewer.Discard.Count)
|
|
.Select(GameEngine.ToCardDto)
|
|
.ToList();
|
|
|
|
if (handAdded != null || handRemovedIds != null || discardAdded != null)
|
|
privateByViewer = new PrivateViewerDelta(handAdded, handRemovedIds, discardAdded);
|
|
}
|
|
|
|
var archByAccount = DiffArchByAccount(prev, next);
|
|
var statsByAccount = DiffStatsByAccount(prev, next);
|
|
var countsByAccount = DiffPublicCountsByAccount(prev, next, viewerAccountId);
|
|
var metaDelta = DiffMeta(prev, next);
|
|
|
|
return new GameStateDelta(
|
|
StateVersion: next.NextActionSequence,
|
|
ChangedTiles: changedTiles,
|
|
UnitsAdded: unitsAdded,
|
|
UnitsRemoved: unitsRemoved,
|
|
UnitsChanged: unitsChanged,
|
|
ArchSpiritByAccount: archByAccount,
|
|
PlayerStatsByAccount: statsByAccount,
|
|
PublicCountsByAccount: countsByAccount,
|
|
PrivateByViewer: privateByViewer,
|
|
MetaDelta: metaDelta,
|
|
ActiveEffects: DiffActiveEffects(next));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Compute spectator delta (public data only).
|
|
/// </summary>
|
|
public static GameStateDelta ComputeSpectatorDelta(GameState prev, GameState next)
|
|
{
|
|
var changedTiles = DiffTiles(prev, next);
|
|
var (unitsAdded, unitsRemoved, unitsChanged) = DiffAllFieldUnits(prev, next);
|
|
|
|
var archByAccount = DiffArchByAccount(prev, next);
|
|
var statsByAccount = DiffStatsByAccount(prev, next);
|
|
var countsByAccount = DiffPublicCountsByAccount(prev, next, null);
|
|
var metaDelta = DiffMeta(prev, next);
|
|
|
|
return new GameStateDelta(
|
|
StateVersion: next.NextActionSequence,
|
|
ChangedTiles: changedTiles,
|
|
UnitsAdded: unitsAdded,
|
|
UnitsRemoved: unitsRemoved,
|
|
UnitsChanged: unitsChanged,
|
|
ArchSpiritByAccount: archByAccount,
|
|
PlayerStatsByAccount: statsByAccount,
|
|
PublicCountsByAccount: countsByAccount,
|
|
PrivateByViewer: null,
|
|
MetaDelta: metaDelta,
|
|
ActiveEffects: DiffActiveEffects(next));
|
|
}
|
|
|
|
// ── Helpers ───────────────────────────────────────────────────────────────
|
|
|
|
/// <summary>
|
|
/// Always returns the full current active-effects list so every delta keeps the client in sync.
|
|
/// Active effects are a small collection; the overhead of always including them is negligible.
|
|
/// </summary>
|
|
private static IReadOnlyList<ActiveEffectDto> DiffActiveEffects(GameState next)
|
|
=> next.ActiveEffects.Select(ae => new ActiveEffectDto(
|
|
SourceInstanceId : ae.SourceInstanceId,
|
|
SourceName : GameEngine.ResolveInstanceName(next, ae.SourceInstanceId),
|
|
TargetRef : ae.TargetRef,
|
|
Label : string.IsNullOrEmpty(ae.Label)
|
|
? GameEngine.ResolveLabelFromEffectJson(ae.EffectJson)
|
|
: ae.Label,
|
|
DurationType : GameEngine.ResolveDurationType(ae.DurationJson),
|
|
TurnsRemaining : ae.TurnsRemaining)).ToList();
|
|
|
|
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<UnitSnapshot>? added, List<string>? removed, List<UnitDelta>? changed)
|
|
DiffAllFieldUnits(GameState prev, GameState next)
|
|
{
|
|
var prevById = new Dictionary<string, (CardInstance unit, string ownerId)>();
|
|
var nextById = new Dictionary<string, (CardInstance unit, string ownerId)>();
|
|
|
|
foreach (var ps in prev.Players.Values)
|
|
foreach (var u in ps.Field)
|
|
prevById[u.InstanceId] = (u, ps.AccountId);
|
|
|
|
foreach (var ps in next.Players.Values)
|
|
foreach (var u in ps.Field)
|
|
nextById[u.InstanceId] = (u, ps.AccountId);
|
|
|
|
List<UnitSnapshot>? added = null;
|
|
List<string>? removed = null;
|
|
List<UnitDelta>? changed = null;
|
|
|
|
foreach (var (id, nextEntry) in nextById)
|
|
{
|
|
if (!prevById.TryGetValue(id, out var prevEntry))
|
|
{
|
|
added ??= new List<UnitSnapshot>();
|
|
added.Add(new UnitSnapshot(nextEntry.ownerId, GameEngine.ToCardDto(nextEntry.unit)));
|
|
}
|
|
else
|
|
{
|
|
var delta = DiffUnit(prevEntry.unit, nextEntry.unit);
|
|
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 Dictionary<string, ArchSpiritUpdate>? DiffArchByAccount(GameState prev, GameState next)
|
|
{
|
|
Dictionary<string, ArchSpiritUpdate>? result = null;
|
|
|
|
foreach (var (accountId, nextPlayer) in next.Players)
|
|
{
|
|
prev.Players.TryGetValue(accountId, out var prevPlayer);
|
|
|
|
var prevArch = prevPlayer?.ArchSpirit;
|
|
var nextArch = nextPlayer.ArchSpirit;
|
|
|
|
if (prevArch == null && nextArch != null)
|
|
{
|
|
result ??= new Dictionary<string, ArchSpiritUpdate>();
|
|
result[accountId] = new ArchSpiritUpdate(
|
|
Full: GameEngine.ToCardDto(nextArch),
|
|
Delta: null);
|
|
continue;
|
|
}
|
|
|
|
if (prevArch != null && nextArch != null)
|
|
{
|
|
var d = DiffUnit(prevArch, nextArch);
|
|
if (d != null)
|
|
{
|
|
result ??= new Dictionary<string, ArchSpiritUpdate>();
|
|
result[accountId] = new ArchSpiritUpdate(
|
|
Full: null,
|
|
Delta: d);
|
|
}
|
|
}
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
private static Dictionary<string, PlayerStatsDelta>? DiffStatsByAccount(GameState prev, GameState next)
|
|
{
|
|
Dictionary<string, PlayerStatsDelta>? result = null;
|
|
|
|
foreach (var (accountId, nextPlayer) in next.Players)
|
|
{
|
|
if (!prev.Players.TryGetValue(accountId, out var prevPlayer))
|
|
continue;
|
|
|
|
var d = DiffPlayerStats(prevPlayer, nextPlayer);
|
|
if (d != null)
|
|
{
|
|
result ??= new Dictionary<string, PlayerStatsDelta>();
|
|
result[accountId] = d;
|
|
}
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
private static Dictionary<string, PublicCountsDelta>? DiffPublicCountsByAccount(
|
|
GameState prev,
|
|
GameState next,
|
|
string? viewerAccountId)
|
|
{
|
|
Dictionary<string, PublicCountsDelta>? result = null;
|
|
|
|
foreach (var (accountId, nextPlayer) in next.Players)
|
|
{
|
|
if (viewerAccountId != null && string.Equals(accountId, viewerAccountId, StringComparison.OrdinalIgnoreCase))
|
|
continue;
|
|
|
|
if (!prev.Players.TryGetValue(accountId, out var prevPlayer))
|
|
continue;
|
|
|
|
var deck = prevPlayer.Deck.Count != nextPlayer.Deck.Count ? nextPlayer.Deck.Count : (int?)null;
|
|
var hand = prevPlayer.Hand.Count != nextPlayer.Hand.Count ? nextPlayer.Hand.Count : (int?)null;
|
|
var discard = prevPlayer.Discard.Count != nextPlayer.Discard.Count ? nextPlayer.Discard.Count : (int?)null;
|
|
|
|
if (deck != null || hand != null || discard != null)
|
|
{
|
|
result ??= new Dictionary<string, PublicCountsDelta>();
|
|
result[accountId] = new PublicCountsDelta(deck, hand, discard);
|
|
}
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
private static PlayerState? FindPlayer(GameState state, string accountId)
|
|
{
|
|
if (state.Players.TryGetValue(accountId, out var direct))
|
|
return direct;
|
|
|
|
foreach (var (key, ps) in state.Players)
|
|
if (string.Equals(key, accountId, StringComparison.OrdinalIgnoreCase))
|
|
return ps;
|
|
|
|
return state.Players.Values.FirstOrDefault(p =>
|
|
string.Equals(p.AccountId, accountId, StringComparison.OrdinalIgnoreCase));
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|