Files
sor/Server/src/SOR.Game/GameTurnTimerService.cs
T
74af9aa4bd Phase 5: N-player ELO, spectator-for-eliminated, turn-limit/concede N-player paths
- GameEngine: GetNPlayerTurnLimitWinners() ranks surviving players by ArchSpirit HP; highest-HP player(s) win, rest lose
- GameConcedeHandler: N-player path — conceder is loser, remaining non-eliminated players are winners; delegates to FinalizeMultiPlayerGameAsync
- GameForceConcedeHandler: same N-player/1v1 branch split for inactivity forfeit
- GameEndTurnHandler: N-player path uses GetNPlayerTurnLimitWinners + FinalizeMultiPlayerGameAsync on turn-limit game-over
- GameTurnTimerService: same N-player/1v1 branch on timer-expiry game-over
- Game.gd: player_eliminated signal + game.player_eliminated push handler
- game_screen.gd: _on_player_eliminated shows AcceptDialog; sets _is_spectating=true for the local player so they can watch the rest of the game

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-03-26 05:56:01 -04:00

204 lines
7.8 KiB
C#

namespace SOR.Game;
using System.Collections.Concurrent;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using SOR.Database.Contexts;
using SOR.Database.Enums;
using SOR.Game.Handlers;
using SOR.Networking.Abstractions.EventBus;
using SOR.Networking.Abstractions.Push;
/// <summary>
/// Manages per-session turn timers. When a turn timer expires the active player's
/// turn is ended automatically (equivalent to game.end_turn fired by the engine).
///
/// Registered as both a singleton (so handlers can inject it) and as an IHostedService
/// (so StartAsync / StopAsync are called on application lifecycle events).
/// </summary>
internal sealed class GameTurnTimerService : IHostedService
{
/// <summary>
/// Static reference set in the constructor so that FinalizeGameAsync (a static method
/// on GameHandlerBase) can cancel timers without requiring DI injection.
/// Safe because the service is registered as a singleton.
/// </summary>
internal static GameTurnTimerService? Instance { get; private set; }
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<GameTurnTimerService> _logger;
private readonly ConcurrentDictionary<Guid, CancellationTokenSource> _timers = new();
private CancellationToken _stoppingToken;
public GameTurnTimerService(IServiceScopeFactory scopeFactory, ILogger<GameTurnTimerService> logger)
{
_scopeFactory = scopeFactory;
_logger = logger;
Instance = this;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_stoppingToken = cancellationToken;
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
foreach (var cts in _timers.Values)
cts.Cancel();
_timers.Clear();
return Task.CompletedTask;
}
/// <summary>
/// Reset (or start) the turn timer for a session. Cancels any existing timer first.
/// If <paramref name="turnTimerSeconds"/> is 0 the timer is simply cancelled and not restarted.
/// The effective deadline is also capped by the session time limit if one is configured.
/// </summary>
public void ResetTimer(
Guid sessionId,
int turnTimerSeconds,
int timeLimitMinutes,
DateTimeOffset sessionCreatedAt)
{
// Cancel the previous turn's timer.
if (_timers.TryRemove(sessionId, out var existing))
existing.Cancel();
if (turnTimerSeconds <= 0)
return; // No per-turn timer configured.
int effectiveSeconds = turnTimerSeconds;
// Cap by remaining session time if a time limit is configured.
if (timeLimitMinutes > 0)
{
var elapsed = DateTimeOffset.UtcNow - sessionCreatedAt;
var remaining = TimeSpan.FromMinutes(timeLimitMinutes) - elapsed;
if (remaining.TotalSeconds <= 0)
return; // Session time already exhausted; let the next action resolve it.
effectiveSeconds = Math.Min(effectiveSeconds, (int)remaining.TotalSeconds);
}
var cts = new CancellationTokenSource();
_timers[sessionId] = cts;
// Fire-and-forget: run the delay on the thread-pool.
_ = RunTimerAsync(sessionId, effectiveSeconds, cts.Token);
}
/// <summary>
/// Cancel and remove the timer for a session (called when the game ends normally).
/// </summary>
public void CancelTimer(Guid sessionId)
{
if (_timers.TryRemove(sessionId, out var cts))
cts.Cancel();
}
// -------------------------------------------------------------------------
private async Task RunTimerAsync(Guid sessionId, int seconds, CancellationToken ct)
{
try
{
await Task.Delay(TimeSpan.FromSeconds(seconds), ct);
await AutoEndTurnAsync(sessionId);
}
catch (OperationCanceledException)
{
// Timer was reset or the game ended — nothing to do.
}
catch (Exception ex)
{
_logger.LogError(ex, "Turn timer auto-end failed for session {SessionId}", sessionId);
}
}
private async Task AutoEndTurnAsync(Guid sessionId)
{
using var scope = _scopeFactory.CreateScope();
var sp = scope.ServiceProvider;
var gameDb = sp.GetRequiredService<GameDbContext>();
var identityDb = sp.GetRequiredService<SorIdentityDbContext>();
var clientPush = sp.GetRequiredService<IClientPush>();
var eventBus = sp.GetRequiredService<IEventBus>();
// Acquire a row-level lock, same pattern as LoadActiveSessionAsync.
await gameDb.Database.BeginTransactionAsync(_stoppingToken);
var session = await gameDb.GameSessions
.FromSqlInterpolated(
$"""
SELECT * FROM game.game_sessions
WHERE "Id" = {sessionId}
FOR UPDATE
""")
.SingleOrDefaultAsync(_stoppingToken);
if (session is null || session.Status != GameSessionStatus.Active)
{
// Game ended before the timer fired — roll back and exit cleanly.
await gameDb.Database.RollbackTransactionAsync(_stoppingToken);
return;
}
var state = GameEngine.Deserialize(session.StateJson!);
var actorId = state.ActivePlayerAccountId;
var (newState, gameOver) = GameEngine.EndTurn(state, actorId);
if (gameOver)
{
var dto = GameEngine.ToDto(newState, actorId);
await GameHandlerBase.SaveStateAsync(gameDb, session, newState, actorId,
"game.turn_timer_expired", null, _stoppingToken, JsonSerializer.Serialize(dto));
await GameHandlerBase.PushStateToPlayersAsync(clientPush, session, newState, _stoppingToken);
bool isMulti = session.PlayerCount > 2 ||
!string.IsNullOrEmpty(session.AdditionalPlayersJson);
if (isMulti)
{
var (winnerIds, loserIds) = GameEngine.GetNPlayerTurnLimitWinners(newState);
session.Status = GameSessionStatus.Completed;
session.WinnerAccountId = winnerIds.FirstOrDefault();
session.WinCondition = "turn_limit";
session.EndedAt = DateTimeOffset.UtcNow;
await GameHandlerBase.FinalizeMultiPlayerGameAsync(
gameDb, identityDb, clientPush, eventBus,
session, winnerIds, loserIds, "turn_limit", _stoppingToken);
}
else
{
var (winnerId, loserId) = GameEngine.GetTurnLimitWinner(newState);
session.Status = GameSessionStatus.Completed;
session.WinnerAccountId = winnerId;
session.WinCondition = "turn_limit";
session.EndedAt = DateTimeOffset.UtcNow;
await GameHandlerBase.FinalizeGameAsync(
gameDb, identityDb, clientPush, eventBus,
session, winnerId, loserId, "turn_limit", _stoppingToken);
}
}
else
{
var dto = GameEngine.ToDto(newState, actorId);
await GameHandlerBase.SaveStateAsync(gameDb, session, newState, actorId,
"game.turn_timer_expired", null, _stoppingToken, JsonSerializer.Serialize(dto));
await GameHandlerBase.PushStateToPlayersAsync(clientPush, session, newState, _stoppingToken);
// Start the timer for the new active player's turn.
ResetTimer(session.Id, newState.Rules.TurnTimerSeconds,
newState.Rules.TimeLimitMinutes, session.CreatedAt);
}
}
}