Files
sor/Server/src/SOR.Game/Handlers/GameJoinCustomLobbyHandler.cs
T
9b6b7191f0 Add square grid system, positional combat, sacrifice, and Placement phase
Grid infrastructure (SOR.Game/Grid/):
- Coord — immutable (X,Y) struct with Manhattan distance, adjacency, BFS helpers
- Tile — mutable affinity slots (Base1/Base2) + occupancy tracking
- Board — 8×8 (configurable) grid, PlaceUnit/RemoveUnit/MoveUnit/BuildOccupancyMap
- Pathfinding — Walk/Flight BFS (GetReachableWithCost), Jump/Teleport range (GetJumpRange)
- LineOfSight — supercover DDA; occupied intermediate tiles block LOS
- AffinitySystem — full Resolve table for all 20+ affinities per affinity.md,
  PushAffinity, ApplyPlacementAffinity, IsAffinityValid (basic vs non-basic rules)

Combat (SOR.Game/Combat/):
- AttackSystem — Manhattan range + optional LOS validation (§6.10)
- SacrificeSystem — exact ST return formula from gameplay.md §6.15

Abilities (SOR.Game/Abilities/):
- AbilitySystem stub — future pass per abilities.md

Game engine / state changes:
- GamePhase: added Placement phase (before Draw)
- GameRuleSet + GameRules: added BoardWidth/BoardHeight (default 8×8)
- GameState: added Board, PlayerOneAccountId; CardInstance gains MovementType,
  MaxMp, MinAttackRange, MaxAttackRange, RequiresLos, MinChannelRange,
  MaxChannelRange, IsLeader (moved from FieldCard); FieldCard adds Position + CurrentMp
- [JsonPolymorphic] on CardInstance so FieldCard survives JSONB round-trip
- JsonStringEnumConverter added to GameEngine serializer options
- GameEngine.Initialize: creates Board + sets Placement phase; no opening draw yet
- GameEngine.PlaceArchSpirit: validates row, pushes affinity, triggers opening draw
  and SP gain when both players placed
- GameEngine.ChannelCard (was PlayCard): validates channeling range + affinity for Spirits
- GameEngine.MoveUnit: Walk/Flight BFS, Jump (1 MP/landing), Teleport (LOS + 1 MP)
- GameEngine.Attack: adds range+LOS validation via AttackSystem
- GameEngine.Sacrifice: adjacency + SacrificeSystem ST formula
- GameEngine.EndTurn: now also restores MP (§6.0 step 1) for next player
- ToDto: includes Board tiles with resolved affinities; CardInstanceDto gets Position,
  CurrentMp, MaxMp, MovementType

New handlers: game.place_arch_spirit, game.move_unit, game.sacrifice
Updated handlers: game.play_card (target tile), GameReadyHandler (new Initialize sig)
Migration: AddBoardDimensions (board_width/board_height on game_rule_sets)

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>
2026-02-26 11:22:30 -05:00

109 lines
4.4 KiB
C#

namespace SOR.Game.Handlers;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts;
using SOR.Database.Entities.Game;
using SOR.Database.Enums;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Push;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
/// <summary>
/// game.custom.join — guest joins an open custom lobby with their chosen deck.
///
/// When the lobby is full (both host and guest present), a GameSession is created
/// immediately and CustomLobbyGameStartedPush is sent to both players. Both players
/// then send game.ready to start the actual game.
/// </summary>
internal sealed class GameJoinCustomLobbyHandler : GameHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly GameDbContext _gameDb;
private readonly IClientPush _clientPush;
public GameJoinCustomLobbyHandler(
IMessageSerializer serializer,
GameDbContext gameDb,
IClientPush clientPush)
{
_serializer = serializer;
_gameDb = gameDb;
_clientPush = clientPush;
}
public string MessageType => "game.custom.join";
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken ct)
{
var req = _serializer.DeserializePayload<JoinCustomLobbyRequest>(message.Payload);
var accountId = Guid.Parse(connection.UserId);
var lobby = await _gameDb.CustomLobbies.FindAsync([req.LobbyId], ct)
?? throw new GameException("LOBBY_NOT_FOUND");
if (lobby.Status != CustomLobbyStatus.Open)
throw new GameException("LOBBY_NOT_OPEN");
if (lobby.HostAccountId == accountId)
throw new GameException("CANNOT_JOIN_OWN_LOBBY");
lobby.GuestAccountId = accountId;
lobby.GuestDeckId = req.DeckId;
lobby.Status = CustomLobbyStatus.Full;
// Build the effective rules from stored overrides (falling back to Default).
var rules = new GameRules
{
OpeningHandSize = lobby.OpeningHandSizeOverride ?? GameRules.Default.OpeningHandSize,
FirstPlayerSkipsDraw = lobby.FirstPlayerSkipsDrawOverride ?? GameRules.Default.FirstPlayerSkipsDraw,
SpAccumulationPerTurn = lobby.SpAccumulationPerTurnOverride ?? GameRules.Default.SpAccumulationPerTurn,
DrawPerTurn = lobby.DrawPerTurnOverride ?? GameRules.Default.DrawPerTurn,
SpHasCap = lobby.SpHasCapOverride ?? GameRules.Default.SpHasCap,
SpCap = lobby.SpCapOverride ?? GameRules.Default.SpCap,
BoardWidth = GameRules.Default.BoardWidth,
BoardHeight = GameRules.Default.BoardHeight,
};
// Create the game session with the rule snapshot.
var session = new GameSession
{
PlayerOneAccountId = lobby.HostAccountId,
PlayerOneDeckId = lobby.HostDeckId,
PlayerTwoAccountId = accountId,
PlayerTwoDeckId = req.DeckId,
Status = GameSessionStatus.Initializing,
CreatedAt = DateTimeOffset.UtcNow,
RuleSnapshotJson = JsonSerializer.Serialize(rules),
};
_gameDb.GameSessions.Add(session);
lobby.GameSessionId = session.Id;
lobby.Status = CustomLobbyStatus.Started;
await _gameDb.SaveChangesAsync(ct);
// Push game-started notification to both players.
var push = new CustomLobbyGameStartedPush(session.Id, accountId);
var pushToHost = new CustomLobbyGameStartedPush(session.Id, accountId);
var pushToGuest = new CustomLobbyGameStartedPush(session.Id, lobby.HostAccountId);
await Task.WhenAll(
_clientPush.PushAsync(lobby.HostAccountId.ToString(),
ServerMessage.Push("game.custom.started", pushToHost), ct),
_clientPush.PushAsync(accountId.ToString(),
ServerMessage.Push("game.custom.started", pushToGuest), ct));
return ServerMessage.Reply("game.custom.join.ack", message.Seq,
new JoinCustomLobbyResponse(
LobbyId : lobby.Id,
Status : "GameCreated",
GameSessionId : session.Id));
}
}