Implement AI Phase 3: MCTS engine, ELO tracking, self-play, calibration

- MCTS (UCT) decision engine for difficulty tiers 6-8 (MctsNode, MctsSimulator,
  MonteCarloEngine); tiers 6-8 updated from Heuristic → MCTS in AiDifficultyProfiles
- AiEloService: separate ELO ledger for AI accounts (ai_elo_records table)
  so calibration games don't pollute the human RankScore leaderboard
- FinalizeGameAsync / FinalizeMultiPlayerGameAsync: AI accounts are now guarded
  from RankScore and OriginPoints adjustments (IsAi check)
- AiPlayerSessionManager: async GameEnded handler calls AiEloService
- SelfPlayRunner: pure in-process AI vs AI game loop (no DB, no NATS)
- SelfPlayOrchestrator: batch runner loading real decks from DB, parallel games
- FeatureExtractor: GameState → float[1024] feature vector for ML training
- GameReplayExporter: replays completed sessions → TrainingRecord JSONL
- TrainingDataWriter: async JSONL writer
- AiCalibrationJob: pairwise self-play calibration (D1vD2…D9vD10), writes
  AiCalibrationRun rows to GameDbContext
- EF migration: ai_elo_records + ai_calibration_runs tables applied to remote DB
- SOR.Admin: references SOR.Ai; new AI section in NavMenu with ELO Leaderboard
  and Calibration pages; SelfPlayOrchestrator + AiCalibrationJob registered

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-04-12 18:35:23 -04:00
co-authored by Claude Happy
parent 57915ae6da
commit 27e1b7c8a3
27 changed files with 2242 additions and 19 deletions
@@ -163,6 +163,23 @@
</li>
</ul>
</li>
<li class="nav-item">
<NavLink class="nav-link text-white" href="/ai/elo" Match="NavLinkMatch.All">
<i class="bi bi-robot me-2"></i>AI
</NavLink>
<ul class="nav nav-pills flex-column gap-1 ps-3 mt-1">
<li class="nav-item">
<NavLink class="nav-link text-white-50 py-1" href="/ai/elo">
<i class="bi bi-trophy me-2"></i>ELO Leaderboard
</NavLink>
</li>
<li class="nav-item">
<NavLink class="nav-link text-white-50 py-1" href="/ai/calibration">
<i class="bi bi-sliders me-2"></i>Calibration
</NavLink>
</li>
</ul>
</li>
<li class="nav-item">
<NavLink class="nav-link text-white" href="/feature-flags">
<i class="bi bi-toggles me-2"></i>Feature Flags
@@ -0,0 +1,202 @@
@page "/ai/calibration"
@using Microsoft.EntityFrameworkCore
@using SOR.Ai.Calibration
@using SOR.Ai.Training
@using SOR.Database.Contexts
@inject AiCalibrationJob CalibrationJob
@inject GameDbContext Db
@inject ILogger<AiCalibrationPage> Logger
<PageTitle>AI Calibration – SOR Admin</PageTitle>
<div class="d-flex justify-content-between align-items-center mb-4">
<h1 class="mb-0">AI Calibration</h1>
<div class="d-flex gap-2">
<button class="btn btn-outline-secondary btn-sm" @onclick="LoadAsync">
<i class="bi bi-arrow-clockwise me-1"></i>Refresh
</button>
</div>
</div>
@if (_error is not null)
{
<div class="alert alert-danger">@_error</div>
}
@if (_success is not null)
{
<div class="alert alert-success">@_success</div>
}
<!-- Run calibration -->
<div class="card mb-4">
<div class="card-header">Run Self-Play Calibration</div>
<div class="card-body">
<div class="row g-3 align-items-end">
<div class="col-md-3">
<label class="form-label">Difficulty A</label>
<input class="form-control" type="number" min="1" max="10" @bind="_diffA" />
</div>
<div class="col-md-3">
<label class="form-label">Difficulty B</label>
<input class="form-control" type="number" min="1" max="10" @bind="_diffB" />
</div>
<div class="col-md-2">
<label class="form-label">Games</label>
<input class="form-control" type="number" min="2" max="200" @bind="_games" />
</div>
<div class="col-md-2">
<label class="form-label">Notes</label>
<input class="form-control" type="text" @bind="_notes" placeholder="optional" />
</div>
<div class="col-md-2">
<button class="btn btn-primary w-100" @onclick="RunPairAsync" disabled="@_running">
@if (_running) { <span class="spinner-border spinner-border-sm me-1"></span> }
Run Pair
</button>
</div>
</div>
<div class="mt-2">
<button class="btn btn-warning btn-sm" @onclick="RunAllPairsAsync" disabled="@_running">
@if (_running) { <span class="spinner-border spinner-border-sm me-1"></span> }
Run All Adjacent Pairs (1v2 … 9v10)
</button>
</div>
</div>
</div>
<!-- Run training data export -->
<div class="card mb-4">
<div class="card-header">Export Training Data</div>
<div class="card-body">
<div class="row g-3 align-items-end">
<div class="col-md-4">
<label class="form-label">Output Path</label>
<input class="form-control" type="text" @bind="_exportPath" placeholder="/data/training.jsonl" />
</div>
<div class="col-md-2">
<label class="form-label">Max Sessions</label>
<input class="form-control" type="number" min="1" max="5000" @bind="_exportMax" />
</div>
<div class="col-md-2">
<button class="btn btn-secondary w-100" @onclick="RunExportAsync" disabled="@_running">
@if (_running) { <span class="spinner-border spinner-border-sm me-1"></span> }
Export
</button>
</div>
</div>
</div>
</div>
<!-- Calibration history -->
<div class="card">
<div class="card-header">Calibration History</div>
@if (_runs is null)
{
<div class="card-body"><span class="spinner-border spinner-border-sm"></span> Loading…</div>
}
else if (_runs.Count == 0)
{
<div class="card-body text-muted">No calibration runs yet.</div>
}
else
{
<div class="table-responsive">
<table class="table table-sm table-hover mb-0">
<thead>
<tr>
<th>Date</th>
<th>Difficulty A</th>
<th>Difficulty B</th>
<th>Win Rate A</th>
<th>Games</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
@foreach (var run in _runs)
{
<tr>
<td>@run.RunAt.ToString("yyyy-MM-dd HH:mm")</td>
<td>D@(run.DifficultyA)</td>
<td>D@(run.DifficultyB)</td>
<td>
<span class="@(run.WinRateA < 0.45f ? "text-success" : run.WinRateA > 0.55f ? "text-danger" : "text-warning")">
@(run.WinRateA.ToString("P1"))
</span>
</td>
<td>@run.GameCount</td>
<td class="text-muted small">@run.Notes</td>
</tr>
}
</tbody>
</table>
</div>
}
</div>
@code {
private List<SOR.Database.Entities.Game.AiCalibrationRun>? _runs;
private bool _running;
private string? _error;
private string? _success;
private int _diffA = 1;
private int _diffB = 2;
private int _games = 20;
private string? _notes;
private string _exportPath = "/data/training.jsonl";
private int _exportMax = 500;
[Inject] private SelfPlayOrchestrator Orchestrator { get; set; } = default!;
[Inject] private GameReplayExporter Exporter { get; set; } = default!;
protected override async Task OnInitializedAsync() => await LoadAsync();
private async Task LoadAsync()
{
_runs = await Db.AiCalibrationRuns
.OrderByDescending(r => r.RunAt)
.Take(100)
.ToListAsync();
StateHasChanged();
}
private async Task RunPairAsync()
{
_running = true; _error = null; _success = null; StateHasChanged();
try
{
int created = await CalibrationJob.RunPairAsync(_diffA, _diffB, "Balanced", _games, _notes);
_success = $"Calibration run saved ({created} record(s)).";
await LoadAsync();
}
catch (Exception ex) { _error = ex.Message; }
finally { _running = false; StateHasChanged(); }
}
private async Task RunAllPairsAsync()
{
_running = true; _error = null; _success = null; StateHasChanged();
try
{
int created = await CalibrationJob.RunAllPairsAsync("Balanced", _games, _notes);
_success = $"All pairs calibrated — {created} record(s) saved.";
await LoadAsync();
}
catch (Exception ex) { _error = ex.Message; }
finally { _running = false; StateHasChanged(); }
}
private async Task RunExportAsync()
{
_running = true; _error = null; _success = null; StateHasChanged();
try
{
int written = await Exporter.ExportAsync(_exportPath, _exportMax);
_success = $"Exported {written} training records to {_exportPath}.";
}
catch (Exception ex) { _error = ex.Message; }
finally { _running = false; StateHasChanged(); }
}
}
@@ -0,0 +1,86 @@
@page "/ai/elo"
@using Microsoft.EntityFrameworkCore
@using SOR.Database.Contexts
@inject GameDbContext Db
@inject SorIdentityDbContext IdentityDb
<PageTitle>AI ELO Leaderboard – SOR Admin</PageTitle>
<div class="d-flex justify-content-between align-items-center mb-4">
<h1 class="mb-0">AI ELO Leaderboard</h1>
<button class="btn btn-outline-secondary btn-sm" @onclick="LoadAsync">
<i class="bi bi-arrow-clockwise me-1"></i>Refresh
</button>
</div>
@if (_rows is null)
{
<p><span class="spinner-border spinner-border-sm"></span> Loading…</p>
}
else if (_rows.Count == 0)
{
<p class="text-muted">No AI ELO records found. Run calibration games to populate.</p>
}
else
{
<div class="table-responsive">
<table class="table table-sm table-hover">
<thead>
<tr>
<th>#</th>
<th>Username</th>
<th>ELO</th>
<th>Wins</th>
<th>Losses</th>
<th>W/L</th>
<th>Updated</th>
</tr>
</thead>
<tbody>
@{ int rank = 1; }
@foreach (var row in _rows)
{
<tr>
<td>@(rank++)</td>
<td><code>@row.Username</code></td>
<td><strong>@row.Elo</strong></td>
<td class="text-success">@row.Wins</td>
<td class="text-danger">@row.Losses</td>
<td>@(row.Total == 0 ? "—" : $"{(float)row.Wins / row.Total:P0}")</td>
<td class="text-muted small">@row.UpdatedAt.ToString("yyyy-MM-dd HH:mm")</td>
</tr>
}
</tbody>
</table>
</div>
}
@code {
private record EloRow(string Username, int Elo, int Wins, int Losses, int Total, DateTimeOffset UpdatedAt);
private List<EloRow>? _rows;
protected override async Task OnInitializedAsync() => await LoadAsync();
private async Task LoadAsync()
{
var records = await Db.AiEloRecords
.OrderByDescending(r => r.EloScore)
.ToListAsync();
var accountIds = records.Select(r => r.AiAccountId).ToList();
var accounts = await IdentityDb.Users
.Where(a => accountIds.Contains(a.Id))
.ToDictionaryAsync(a => a.Id, a => a.UserName ?? a.Id.ToString());
_rows = records.Select(r => new EloRow(
Username : accounts.GetValueOrDefault(r.AiAccountId, r.AiAccountId.ToString()),
Elo : r.EloScore,
Wins : r.Wins,
Losses : r.Losses,
Total : r.Wins + r.Losses,
UpdatedAt : r.UpdatedAt)).ToList();
StateHasChanged();
}
}
+7
View File
@@ -14,6 +14,8 @@ using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using StackExchange.Redis;
using SOR.Admin.Components;
using SOR.Ai.Calibration;
using SOR.Ai.Training;
using SOR.Cdn;
using SOR.Database;
using SOR.Database.Contexts;
@@ -157,6 +159,11 @@ builder.Services.AddSingleton<IConnectionMultiplexer>(redis);
builder.Services.AddDataProtection()
.PersistKeysToStackExchangeRedis(redis, "SOR.Admin:DataProtection-Keys");
// ── AI calibration (admin-side only: self-play + calibration job) ─────────
builder.Services.AddScoped<SelfPlayOrchestrator>();
builder.Services.AddScoped<GameReplayExporter>();
builder.Services.AddSingleton<AiCalibrationJob>();
// ── CDN client ────────────────────────────────────────────────────────────
builder.Services.AddCdnClient(builder.Configuration);
+1
View File
@@ -18,6 +18,7 @@
<PackageReference Include="Microsoft.AspNetCore.DataProtection.StackExchangeRedis" />
<PackageReference Include="StackExchange.Redis" />
<ProjectReference Include="..\SOR.Ai\SOR.Ai.csproj" />
<ProjectReference Include="..\SOR.Cdn\SOR.Cdn.csproj" />
<ProjectReference Include="..\SOR.Database\SOR.Database.csproj" />
<ProjectReference Include="..\SOR.Shared\SOR.Shared.csproj" />
@@ -0,0 +1,111 @@
namespace SOR.Ai.Calibration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using SOR.Ai.Seeding;
using SOR.Ai.Training;
using SOR.Database.Contexts;
using SOR.Database.Entities.Game;
/// <summary>
/// Runs a full AI calibration pass: pairwise self-play for adjacent difficulty tiers,
/// then records AiCalibrationRun rows so the admin can track progression.
///
/// Triggered manually from the admin UI (AiCalibrationPage).
/// Results are written to GameDbContext.AiCalibrationRuns.
///
/// Calibration strategy: for each pair (D, D+1), run a batch with the Balanced strategy
/// and check that D+1 wins more than 50% of the time (indicating a real skill gap).
/// </summary>
public sealed class AiCalibrationJob
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<AiCalibrationJob> _logger;
public const string DefaultStrategy = "Balanced";
public const int GamesPerPair = 20;
public const int Parallelism = 4;
public AiCalibrationJob(
IServiceScopeFactory scopeFactory,
ILogger<AiCalibrationJob> logger)
{
_scopeFactory = scopeFactory;
_logger = logger;
}
/// <summary>
/// Run all adjacent-difficulty calibration pairs (1v2, 2v3, … 9v10).
/// Returns the number of calibration run records created.
/// </summary>
public async Task<int> RunAllPairsAsync(
string strategy = DefaultStrategy,
int gamesPerPair = GamesPerPair,
string? notes = null,
CancellationToken ct = default)
{
int created = 0;
for (int diffA = 1; diffA <= 9; diffA++)
{
int diffB = diffA + 1;
created += await RunPairAsync(diffA, diffB, strategy, gamesPerPair, notes, ct);
}
return created;
}
/// <summary>
/// Run one pair calibration. Returns 1 if the record was saved, 0 on error.
/// </summary>
public async Task<int> RunPairAsync(
int difficultyA,
int difficultyB,
string strategy = DefaultStrategy,
int games = GamesPerPair,
string? notes = null,
CancellationToken ct = default)
{
_logger.LogInformation(
"AiCalibrationJob: starting D{A} vs D{B} ({Strategy}, {Games} games).",
difficultyA, difficultyB, strategy, games);
try
{
await using var scope = _scopeFactory.CreateAsyncScope();
var orchestrator = scope.ServiceProvider.GetRequiredService<SelfPlayOrchestrator>();
var gameDb = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var (winsA, total) = await orchestrator.RunBatchAsync(
difficultyA, strategy,
difficultyB, strategy,
games, Parallelism, ct);
float winRateA = total > 0 ? (float)winsA / total : 0f;
var run = new AiCalibrationRun
{
DifficultyA = difficultyA,
DifficultyB = difficultyB,
WinRateA = winRateA,
GameCount = total,
Notes = notes,
};
gameDb.AiCalibrationRuns.Add(run);
await gameDb.SaveChangesAsync(ct);
_logger.LogInformation(
"AiCalibrationJob: D{A} win rate vs D{B} = {Rate:P1} ({W}/{T}).",
difficultyA, difficultyB, winRateA, winsA, total);
return 1;
}
catch (Exception ex)
{
_logger.LogError(ex,
"AiCalibrationJob: pair D{A} vs D{B} failed.", difficultyA, difficultyB);
return 0;
}
}
}
@@ -178,6 +178,7 @@ internal sealed class AiPlayerSession : IAsyncDisposable
profile.EngineType switch
{
"Heuristic" => new HeuristicDecisionEngine(profile),
"MCTS" => new MonteCarloEngine(profile),
_ => new RandomDecisionEngine(), // "Random" + any future unknown
};
@@ -6,6 +6,7 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using SOR.Ai.Tracking;
using SOR.Database.Contexts;
using SOR.Database.Enums;
using SOR.Game;
@@ -101,6 +102,7 @@ public sealed class AiPlayerSessionManager : BackgroundService
NatsSubjects.GameEnded, ct))
{
OnGameEnded(evt.GameId);
_ = Task.Run(() => RecordAiEloAsync(evt, ct), ct);
}
}
catch (OperationCanceledException) { /* normal shutdown */ }
@@ -260,6 +262,47 @@ public sealed class AiPlayerSessionManager : BackgroundService
}
}
private async Task RecordAiEloAsync(GameEndedEvent evt, CancellationToken ct)
{
try
{
await using var scope = _scopeFactory.CreateAsyncScope();
var identityDb = scope.ServiceProvider.GetRequiredService<SorIdentityDbContext>();
var gameDb = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var participantIds = new[] { evt.WinnerId, evt.LoserId };
var accounts = await identityDb.Users
.Where(a => participantIds.Contains(a.Id))
.ToListAsync(ct);
var winner = accounts.FirstOrDefault(a => a.Id == evt.WinnerId);
var loser = accounts.FirstOrDefault(a => a.Id == evt.LoserId);
if (winner is null || loser is null) return;
if (!winner.IsAi && !loser.IsAi) return;
// ELO scores: AI uses AiEloRecord; human uses Account.RankScore.
int winnerElo = winner.IsAi
? (await gameDb.AiEloRecords.FirstOrDefaultAsync(r => r.AiAccountId == winner.Id, ct))?.EloScore ?? 1200
: winner.RankScore;
int loserElo = loser.IsAi
? (await gameDb.AiEloRecords.FirstOrDefaultAsync(r => r.AiAccountId == loser.Id, ct))?.EloScore ?? 1200
: loser.RankScore;
var eloService = new AiEloService(gameDb, scope.ServiceProvider
.GetRequiredService<Microsoft.Extensions.Logging.ILogger<AiEloService>>());
await eloService.RecordOutcomeAsync(
evt.WinnerId, winner.IsAi, winnerElo,
evt.LoserId, loser.IsAi, loserElo,
ct);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "AiPlayerSessionManager: failed to record AI ELO for game {Id}.", evt.GameId);
}
}
// ── Private DTOs ──────────────────────────────────────────────────────────
private sealed class AdditionalPlayerRef
@@ -93,13 +93,12 @@ internal static class AiDifficultyProfiles
ResourceWeight = 1.0f,
},
// ── Tiers 6–10: placeholder Heuristic until MCTS/Neural are built ─────
// Phase 3 will replace EngineType with "MCTS" / "Neural".
// ── Tiers 6–8: MCTS ───────────────────────────────────────────────────
new()
{
Difficulty = 6,
DisplayName = "Master",
EngineType = "Heuristic", // TODO Phase 3: "MCTS"
EngineType = "MCTS",
MistakeRate = 0.05f,
MctsTimeBudgetMs = 500,
MctsMaxDepth = 3,
@@ -117,7 +116,7 @@ internal static class AiDifficultyProfiles
{
Difficulty = 7,
DisplayName = "Grandmaster",
EngineType = "Heuristic", // TODO Phase 3: "MCTS"
EngineType = "MCTS",
MistakeRate = 0.02f,
MctsTimeBudgetMs = 1500,
MctsMaxDepth = 5,
@@ -135,7 +134,7 @@ internal static class AiDifficultyProfiles
{
Difficulty = 8,
DisplayName = "Champion",
EngineType = "Heuristic", // TODO Phase 3: "MCTS"
EngineType = "MCTS",
MistakeRate = 0.0f,
MctsTimeBudgetMs = 4000,
MctsMaxDepth = 7,
@@ -0,0 +1,152 @@
namespace SOR.Ai.Engine;
using SOR.Ai.Core;
using SOR.Ai.Heuristics;
using SOR.Ai.MCTS;
using SOR.Database.Enums;
using SOR.Game;
/// <summary>
/// MCTS decision engine (Difficulty 6–8).
///
/// Algorithm: UCT (UCB1 applied to trees)
/// 1. Draw (always, no decision).
/// 2. Build a search tree rooted at the current state.
/// Each iteration: Select → Expand → Simulate (random playout) → Backpropagate.
/// Budget: MctsTimeBudgetMs from the difficulty profile.
/// 3. Return the root child with the highest visit count (most-explored move).
///
/// Action granularity: each MCTS "move" is ONE game action (not a full turn).
/// After each action the tree continues from the resulting state.
/// The engine builds the tree over individual actions and picks the best sequence.
/// </summary>
internal sealed class MonteCarloEngine : IAiDecisionEngine
{
private readonly AiDifficultyProfile _profile;
public MonteCarloEngine(AiDifficultyProfile profile)
{
_profile = profile;
}
public IReadOnlyList<AiAction> ComputeTurn(AiTurnContext ctx)
{
var plan = new List<AiAction>();
// ── 1. Draw phase ─────────────────────────────────────────────────────
GameState workingState;
if (ctx.State.Phase == GamePhase.Draw)
{
plan.Add(new AiDrawAction());
workingState = Clone(ctx.State);
try { (workingState, _) = GameEngine.Draw(workingState, ctx.AiAccountId); }
catch { workingState = Clone(ctx.State); }
}
else
{
workingState = Clone(ctx.State);
}
// ── 2. MCTS main phase ────────────────────────────────────────────────
var deadline = DateTime.UtcNow.AddMilliseconds(_profile.MctsTimeBudgetMs);
const int maxActions = 30; // cap planned actions per turn
int iterations = 0;
while (iterations++ < maxActions)
{
if (workingState.Phase == GamePhase.GameOver) break;
var workingCtx = new AiTurnContext(workingState, ctx.AiAccountId);
var candidates = ActionCandidateGenerator.All(workingCtx)
.Where(a => a is not AiDrawAction)
.ToList();
if (candidates.Count == 0) break;
// Build a one-ply MCTS tree for this action selection.
var root = new MctsNode(parent: null, actionFromParent: null);
root.Untried = candidates;
int sims = 0;
while (DateTime.UtcNow < deadline && sims < 200)
{
sims++;
RunIteration(root, workingState, ctx.AiAccountId);
}
// Best child by visit count (exploitation).
var best = root.Children.MaxBy(c => c.Visits);
if (best?.ActionFromParent is null) break;
plan.Add(best.ActionFromParent);
// Apply the action to the working state.
try { Apply(workingState, ctx.AiAccountId, best.ActionFromParent); }
catch { break; }
}
plan.Add(new AiEndTurnAction());
return plan;
}
// ── MCTS iteration ─────────────────────────────────────────────────────────
private void RunIteration(MctsNode root, GameState rootState, string aiAccountId)
{
// Selection: pick a leaf via UCB1.
var node = root;
var state = Clone(rootState);
while (node.Untried.Count == 0 && node.Children.Count > 0)
{
node = node.Children.MaxBy(c => c.Ucb1())!;
Apply(state, aiAccountId, node.ActionFromParent!);
}
// Expansion: try one untried action.
if (node.Untried.Count > 0)
{
int idx = Random.Shared.Next(node.Untried.Count);
var action = node.Untried[idx];
node.Untried.RemoveAt(idx);
var simState = Clone(state);
try { Apply(simState, aiAccountId, action); }
catch { return; }
var child = new MctsNode(node, action);
child.Untried = ActionCandidateGenerator.All(
new AiTurnContext(simState, aiAccountId))
.Where(a => a is not AiDrawAction)
.ToList();
node.Children.Add(child);
node = child;
state = simState;
}
// Simulation: random playout from current state.
float value = MctsSimulator.Playout(state, aiAccountId, _profile.MctsMaxDepth, _profile);
// Backpropagation.
node.Backpropagate(value);
}
// ── Helpers ───────────────────────────────────────────────────────────────
private static GameState Clone(GameState s)
=> GameEngine.Deserialize(GameEngine.Serialize(s));
private static void Apply(GameState state, string actorId, AiAction action)
{
switch (action)
{
case AiDrawAction: (state, _) = GameEngine.Draw(state, actorId); break;
case AiPlayCardAction p: GameEngine.ChannelCard(state, actorId, p.CardInstanceId, p.TargetTiles); break;
case AiMoveAction m: GameEngine.MoveUnit(state, actorId, m.UnitInstanceId, m.Target); break;
case AiAttackAction a: (state, _) = GameEngine.Attack(state, actorId, a.AttackerInstanceId, a.TargetInstanceId); break;
case AiSacrificeAction s: GameEngine.Sacrifice(state, actorId, s.UnitInstanceId); break;
case AiAscendAction asc: GameEngine.Ascend(state, actorId, asc.IncomingCardInstanceId); break;
case AiEndTurnAction: (state, _) = GameEngine.EndTurn(state, actorId); break;
}
}
}
+60
View File
@@ -0,0 +1,60 @@
namespace SOR.Ai.MCTS;
using SOR.Ai.Engine;
/// <summary>
/// A node in the Monte Carlo search tree.
///
/// Each node represents a GameState reached by a sequence of actions.
/// Children are keyed by the action that led to them.
/// Statistics (visits, totalValue) are updated during backpropagation.
/// </summary>
internal sealed class MctsNode
{
// ── Tree structure ─────────────────────────────────────────────────────────
public MctsNode? Parent { get; }
public AiAction? ActionFromParent { get; }
public List<MctsNode> Children { get; } = new();
public List<AiAction> Untried { get; set; } = new();
// ── Statistics ─────────────────────────────────────────────────────────────
/// <summary>Total number of simulations through this node.</summary>
public int Visits { get; private set; }
/// <summary>Sum of simulation outcomes (+1 win, -1 loss, 0 draw).</summary>
public float TotalValue { get; private set; }
/// <summary>Win rate estimate from this node's perspective.</summary>
public float WinRate => Visits == 0 ? 0f : TotalValue / Visits;
public MctsNode(MctsNode? parent, AiAction? actionFromParent)
{
Parent = parent;
ActionFromParent = actionFromParent;
}
// ── UCB1 selection ─────────────────────────────────────────────────────────
/// <summary>
/// UCB1 score for child selection.
/// explorationC ≈ √2 is the standard exploration constant.
/// </summary>
public float Ucb1(float explorationC = 1.41421356f)
{
if (Visits == 0) return float.MaxValue; // always expand unvisited
float exploit = WinRate;
float explore = explorationC * MathF.Sqrt(MathF.Log(Parent!.Visits) / Visits);
return exploit + explore;
}
// ── Backpropagation ────────────────────────────────────────────────────────
public void Backpropagate(float value)
{
Visits++;
TotalValue += value;
Parent?.Backpropagate(-value); // flip sign: parent's perspective is opposite
}
}
+77
View File
@@ -0,0 +1,77 @@
namespace SOR.Ai.MCTS;
using SOR.Ai.Core;
using SOR.Ai.Engine;
using SOR.Ai.Heuristics;
using SOR.Database.Enums;
using SOR.Game;
/// <summary>
/// Performs a random playout from a given state until game over or depth limit.
/// Returns +1.0 if the AI wins, -1.0 if it loses, 0.0 for draw/inconclusive.
///
/// Uses RandomDecisionEngine for the playout to keep it fast.
/// The heuristic evaluation is used when depth limit is reached before game over.
/// </summary>
internal static class MctsSimulator
{
private static readonly RandomDecisionEngine _random = new();
public static float Playout(
GameState state,
string aiAccountId,
int maxDepth,
AiDifficultyProfile profile)
{
var simState = Clone(state);
int depth = 0;
while (simState.Phase != GamePhase.GameOver && depth++ < maxDepth)
{
var activeId = simState.ActivePlayerAccountId;
if (activeId is null) break;
var ctx = new AiTurnContext(simState, activeId);
var plan = _random.ComputeTurn(ctx);
foreach (var action in plan)
{
if (simState.Phase == GamePhase.GameOver) break;
ApplyAction(simState, activeId, action);
}
}
if (simState.Phase == GamePhase.GameOver)
{
var survivor = simState.Players.FirstOrDefault(kv => !kv.Value.IsEliminated);
if (survivor.Key == aiAccountId) return 1f;
if (survivor.Key == null) return 0f;
return -1f;
}
// Depth limit: use heuristic score normalised to [-1, 1].
float h = ScoringFunctions.Evaluate(simState, aiAccountId, profile);
return Math.Clamp(h / 500f, -1f, 1f);
}
private static GameState Clone(GameState s)
=> GameEngine.Deserialize(GameEngine.Serialize(s));
private static void ApplyAction(GameState state, string actorId, AiAction action)
{
try
{
switch (action)
{
case AiDrawAction: (state, _) = GameEngine.Draw(state, actorId); break;
case AiPlayCardAction p: GameEngine.ChannelCard(state, actorId, p.CardInstanceId, p.TargetTiles); break;
case AiMoveAction m: GameEngine.MoveUnit(state, actorId, m.UnitInstanceId, m.Target); break;
case AiAttackAction a: (state, _) = GameEngine.Attack(state, actorId, a.AttackerInstanceId, a.TargetInstanceId); break;
case AiSacrificeAction s: GameEngine.Sacrifice(state, actorId, s.UnitInstanceId); break;
case AiAscendAction asc: GameEngine.Ascend(state, actorId, asc.IncomingCardInstanceId); break;
case AiEndTurnAction: (state, _) = GameEngine.EndTurn(state, actorId); break;
}
}
catch { /* invalid action — skip */ }
}
}
+8
View File
@@ -2,12 +2,14 @@ namespace SOR.Ai;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SOR.Ai.Calibration;
using SOR.Ai.Core;
using SOR.Ai.Engine;
using SOR.Ai.Handlers;
using SOR.Ai.Heuristics;
using SOR.Ai.Lobby;
using SOR.Ai.Seeding;
using SOR.Ai.Training;
using SOR.Networking.Abstractions.Messaging;
using SOR.Shared;
@@ -49,6 +51,12 @@ public static class ServiceRegistration
// Registering here for clarity and future testability.
services.AddTransient<RandomDecisionEngine>();
services.AddTransient<HeuristicDecisionEngine>();
services.AddTransient<MonteCarloEngine>();
// ── Training / calibration (scoped — used per admin request) ─────────
services.AddScoped<SelfPlayOrchestrator>();
services.AddScoped<GameReplayExporter>();
services.AddSingleton<AiCalibrationJob>();
// ── Lobby message handlers ────────────────────────────────────────────
services.AddTransient<IMessageHandler, GameAddAiHandler>();
@@ -0,0 +1,82 @@
namespace SOR.Ai.Tracking;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using SOR.Database.Contexts;
using SOR.Database.Entities.Game;
using SOR.Game;
/// <summary>
/// Maintains a separate ELO leaderboard for AI accounts.
/// Called by AiPlayerSessionManager when a game involving an AI ends.
/// Uses the same K=32 formula as GameEngine.ComputeEloDelta but writes to
/// ai_elo_records instead of Account.RankScore.
/// </summary>
internal sealed class AiEloService
{
private readonly GameDbContext _gameDb;
private readonly ILogger<AiEloService> _logger;
public AiEloService(GameDbContext gameDb, ILogger<AiEloService> logger)
{
_gameDb = gameDb;
_logger = logger;
}
/// <summary>
/// Updates the AI ELO record for an AI winner playing against an opponent's current score.
/// If the opponent is also an AI, both records are updated.
/// </summary>
public async Task RecordOutcomeAsync(
Guid winnerAccountId,
bool winnerIsAi,
int winnerCurrentElo,
Guid loserAccountId,
bool loserIsAi,
int loserCurrentElo,
CancellationToken ct)
{
if (!winnerIsAi && !loserIsAi) return; // no AI involved
var (winnerDelta, loserDelta) = GameEngine.ComputeEloDelta(winnerCurrentElo, loserCurrentElo);
if (winnerIsAi)
{
var record = await GetOrCreateAsync(winnerAccountId, ct);
record.EloScore = Math.Max(0, record.EloScore + winnerDelta);
record.Wins++;
record.UpdatedAt = DateTimeOffset.UtcNow;
}
if (loserIsAi)
{
var record = await GetOrCreateAsync(loserAccountId, ct);
record.EloScore = Math.Max(0, record.EloScore - loserDelta);
record.Losses++;
record.UpdatedAt = DateTimeOffset.UtcNow;
}
await _gameDb.SaveChangesAsync(ct);
_logger.LogDebug(
"AiEloService: game outcome recorded. Winner {W} ({WIsAi})+{WD} Loser {L} ({LIsAi})-{LD}.",
winnerAccountId, winnerIsAi, winnerDelta,
loserAccountId, loserIsAi, loserDelta);
}
// ── Helpers ───────────────────────────────────────────────────────────────
private async Task<AiEloRecord> GetOrCreateAsync(Guid accountId, CancellationToken ct)
{
var record = await _gameDb.AiEloRecords
.FirstOrDefaultAsync(r => r.AiAccountId == accountId, ct);
if (record is null)
{
record = new AiEloRecord { AiAccountId = accountId };
_gameDb.AiEloRecords.Add(record);
}
return record;
}
}
@@ -0,0 +1,122 @@
namespace SOR.Ai.Training;
using SOR.Database.Enums;
using SOR.Game;
using SOR.Game.Grid;
/// <summary>
/// Converts a GameState into a fixed-length float feature vector for ML training.
///
/// Vector layout (1024 floats):
/// [0..399] Board tile features (10×10 grid × 4 features each)
/// [400..599] AI player features (200 floats)
/// [600..799] Opponent player features (200 floats)
/// [800..1023] Global game features (224 floats, rest zeroed)
///
/// All values are normalised to [0, 1] or [-1, 1] ranges.
/// </summary>
internal static class FeatureExtractor
{
public const int FeatureCount = 1024;
private const int BoardWidth = 10;
private const int BoardHeight = 10;
private const int TileFeat = 4;
private const int BoardEnd = BoardWidth * BoardHeight * TileFeat; // 400
private const int PlayerFeat = 200;
private const int AiStart = BoardEnd; // 400
private const int OppStart = AiStart + PlayerFeat; // 600
private const int GlobalStart = OppStart + PlayerFeat; // 800
public static float[] Extract(GameState state, string aiAccountId)
{
var vec = new float[FeatureCount];
// ── Board tiles ───────────────────────────────────────────────────────
if (state.Board is not null)
{
var zone0 = state.Board.StartingZones.TryGetValue(0, out var z0) ? z0 : null;
foreach (var tile in state.Board.Tiles.Values)
{
int cx = Math.Clamp(tile.Coord.X, 0, BoardWidth - 1);
int cy = Math.Clamp(tile.Coord.Y, 0, BoardHeight - 1);
int tileBase = (cy * BoardWidth + cx) * TileFeat;
// feature 0: tile exists
vec[tileBase + 0] = 1f;
// feature 1: has own unit (1), enemy unit (-1), empty (0)
vec[tileBase + 1] = tile.OccupantOwner is null ? 0f
: tile.OccupantOwner == aiAccountId ? 1f : -1f;
// feature 2: resolved affinity index / 10 (normalised)
var resolved = AffinitySystem.Resolve(tile.Base1, tile.Base2);
vec[tileBase + 2] = (float)(int)resolved / 10f;
// feature 3: is in AI starting zone
vec[tileBase + 3] = (zone0?.Contains(tile.Coord) == true) ? 1f : 0f;
}
}
// ── Player features ───────────────────────────────────────────────────
state.Players.TryGetValue(aiAccountId, out var aiPlayer);
PlayerState? oppPlayer = null;
foreach (var kv in state.Players)
{
if (kv.Key != aiAccountId && !kv.Value.IsEliminated) { oppPlayer = kv.Value; break; }
}
WritePlayerFeatures(vec, aiPlayer, aiAccountId, AiStart);
WritePlayerFeatures(vec, oppPlayer, null, OppStart);
// ── Global features ───────────────────────────────────────────────────
vec[GlobalStart + 0] = Math.Clamp(state.TurnNumber / 50f, 0f, 1f);
vec[GlobalStart + 1] = state.Phase == GamePhase.Draw ? 1f : 0f;
vec[GlobalStart + 2] = state.Phase == GamePhase.Main ? 1f : 0f;
vec[GlobalStart + 3] = state.Rules.SpAccumulationPerTurn / 10f;
return vec;
}
private static void WritePlayerFeatures(
float[] vec,
PlayerState? player,
string? accountId,
int offset)
{
if (player is null) return;
vec[offset + 0] = player.IsEliminated ? 0f : 1f;
// ArchSpirit HP ratio
var arch = player.ArchSpirit;
if (arch is not null)
{
float maxHp = arch.MaxHealth ?? 1;
float curHp = arch.CurrentHealth ?? 0;
vec[offset + 1] = maxHp > 0 ? curHp / maxHp : 0f;
}
// SP / ST normalised
vec[offset + 2] = Math.Clamp(player.CurrentSp / 30f, 0f, 1f);
vec[offset + 3] = Math.Clamp(player.CurrentSt / 10f, 0f, 1f);
// Field unit count
int fieldUnits = player.Field.OfType<FieldCard>().Count(f => !f.IsLeader);
vec[offset + 4] = Math.Clamp(fieldUnits / 10f, 0f, 1f);
// Hand size
vec[offset + 5] = Math.Clamp(player.Hand.Count / 10f, 0f, 1f);
// Deck size
vec[offset + 6] = Math.Clamp(player.Deck.Count / 40f, 0f, 1f);
// Unit stats (first 5 units max, 3 features each → 15 floats)
int unitSlot = 7;
foreach (var unit in player.Field.OfType<FieldCard>().Where(f => !f.IsLeader).Take(5))
{
vec[offset + unitSlot + 0] = Math.Clamp((unit.CurrentHealth ?? 0) / 30f, 0f, 1f);
vec[offset + unitSlot + 1] = Math.Clamp((unit.Damage ?? 0) / 20f, 0f, 1f);
vec[offset + unitSlot + 2] = Math.Clamp(unit.CurrentMp / 10f, 0f, 1f);
unitSlot += 3;
}
}
}
@@ -0,0 +1,100 @@
namespace SOR.Ai.Training;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using SOR.Database.Contexts;
using SOR.Database.Enums;
using SOR.Game;
/// <summary>
/// Reads completed game sessions from the DB and exports TrainingRecords to a JSONL file.
///
/// For each completed session, replays the action log step-by-step, captures the board
/// state feature vector before each action, and annotates the outcome (+1 winner, -1 loser).
///
/// Only sessions with StateJson (i.e. the full state snapshot was saved) are processed;
/// sessions where StateJson is null are skipped silently.
/// </summary>
public sealed class GameReplayExporter
{
private readonly GameDbContext _gameDb;
private readonly ILogger<GameReplayExporter> _logger;
public GameReplayExporter(GameDbContext gameDb, ILogger<GameReplayExporter> logger)
{
_gameDb = gameDb;
_logger = logger;
}
/// <summary>
/// Export up to <paramref name="maxSessions"/> recently completed sessions to
/// <paramref name="outputPath"/> (JSONL, appended).
/// Returns the number of TrainingRecords written.
/// </summary>
public async Task<int> ExportAsync(
string outputPath,
int maxSessions = 500,
DateTimeOffset? since = null,
CancellationToken ct = default)
{
var query = _gameDb.GameSessions
.Include(s => s.ActionLog.OrderBy(a => a.SequenceNumber))
.Where(s => s.Status == GameSessionStatus.Completed && s.StateJson != null);
if (since.HasValue)
query = query.Where(s => s.EndedAt >= since.Value);
var sessions = await query
.OrderByDescending(s => s.EndedAt)
.Take(maxSessions)
.ToListAsync(ct);
_logger.LogInformation("GameReplayExporter: exporting {Count} sessions to {Path}.",
sessions.Count, outputPath);
await using var writer = new TrainingDataWriter(outputPath);
int written = 0;
foreach (var session in sessions)
{
if (session.WinnerAccountId is null) continue;
if (session.ActionLog.Count == 0) continue;
if (session.StateJson is null) continue;
var loserAccountId = session.PlayerOneAccountId == session.WinnerAccountId
? session.PlayerTwoAccountId
: session.PlayerOneAccountId;
try
{
// Replay the game state through each action.
var state = GameEngine.Deserialize(session.StateJson);
foreach (var entry in session.ActionLog)
{
float outcome = entry.ActorAccountId == session.WinnerAccountId ? 1f : -1f;
var features = FeatureExtractor.Extract(state, entry.ActorAccountId.ToString());
var record = new TrainingRecord(
GameSessionId : session.Id,
TurnNumber : state.TurnNumber,
ActorAccountId : entry.ActorAccountId.ToString(),
Features : features,
ActionType : entry.ActionType,
ActionJson : entry.PayloadJson ?? "{}",
Outcome : outcome);
await writer.WriteAsync(record, ct);
written++;
}
}
catch (Exception ex)
{
_logger.LogWarning(ex, "GameReplayExporter: skipped session {Id} due to error.", session.Id);
}
}
_logger.LogInformation("GameReplayExporter: wrote {Count} records.", written);
return written;
}
}
@@ -0,0 +1,147 @@
namespace SOR.Ai.Training;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using SOR.Ai.Seeding;
using SOR.Database.Contexts;
using SOR.Database.Entities.Catalog;
/// <summary>
/// Runs batches of AI self-play games by loading AI decks from the DB.
/// Used by AiCalibrationJob and can be triggered from admin pages.
///
/// Each batch pits difficulty A vs difficulty B for <paramref name="gameCount"/> games
/// and returns the win count for player A.
/// </summary>
public sealed class SelfPlayOrchestrator
{
private readonly CollectionDbContext _collectionDb;
private readonly CatalogDbContext _catalogDb;
private readonly ILogger<SelfPlayOrchestrator> _logger;
public SelfPlayOrchestrator(
CollectionDbContext collectionDb,
CatalogDbContext catalogDb,
ILogger<SelfPlayOrchestrator> logger)
{
_collectionDb = collectionDb;
_catalogDb = catalogDb;
_logger = logger;
}
/// <summary>
/// Play <paramref name="gameCount"/> games: difficultyA (strategy A) vs difficultyB (strategy B).
/// Returns (winsA, totalCompleted).
/// Games that error out are counted as completed but as draws.
/// </summary>
public async Task<(int winsA, int total)> RunBatchAsync(
int difficultyA,
string strategyA,
int difficultyB,
string strategyB,
int gameCount = 20,
int parallelism = 4,
CancellationToken ct = default)
{
var accountIdA = AiAccountSeeder.AccountId(difficultyA, strategyA);
var accountIdB = AiAccountSeeder.AccountId(difficultyB, strategyB);
// Load deck + ArchSpirit for both accounts.
var deckA = await LoadDeckAsync(accountIdA, ct);
var deckB = await LoadDeckAsync(accountIdB, ct);
if (deckA is null || deckB is null)
{
_logger.LogWarning(
"SelfPlayOrchestrator: could not load decks for {A} or {B}. Aborting.",
accountIdA, accountIdB);
return (0, 0);
}
int winsA = 0;
int done = 0;
// Run games in parallel batches.
var sem = new SemaphoreSlim(parallelism, parallelism);
var tasks = new List<Task<bool?>>();
for (int i = 0; i < gameCount; i++)
{
int gameIndex = i;
tasks.Add(Task.Run(async () =>
{
await sem.WaitAsync(ct);
try
{
// Swap sides every other game to avoid first-mover bias.
bool swapped = gameIndex % 2 == 1;
string? winner;
if (!swapped)
winner = SelfPlayRunner.Run(
accountIdA, difficultyA, strategyA, deckA.Value.cards, deckA.Value.archSpirit,
accountIdB, difficultyB, strategyB, deckB.Value.cards, deckB.Value.archSpirit);
else
winner = SelfPlayRunner.Run(
accountIdB, difficultyB, strategyB, deckB.Value.cards, deckB.Value.archSpirit,
accountIdA, difficultyA, strategyA, deckA.Value.cards, deckA.Value.archSpirit);
bool? aWon = winner is null ? (bool?)null
: winner == accountIdA.ToString() ? true : false;
return aWon;
}
catch (Exception ex)
{
_logger.LogWarning(ex, "SelfPlayOrchestrator: game {Index} threw.", gameIndex);
return null;
}
finally { sem.Release(); }
}, ct));
}
var results = await Task.WhenAll(tasks);
foreach (var r in results)
{
done++;
if (r == true) winsA++;
}
_logger.LogInformation(
"SelfPlayOrchestrator: D{A}/{SA} vs D{B}/{SB} → {WA}/{Done} wins for A.",
difficultyA, strategyA, difficultyB, strategyB, winsA, done);
return (winsA, done);
}
// ── Deck loading ──────────────────────────────────────────────────────────
private async Task<(IList<(CardDefinition def, int qty)> cards, CardDefinition archSpirit)?>
LoadDeckAsync(Guid accountId, CancellationToken ct)
{
var deck = await _collectionDb.Decks
.Include(d => d.Cards)
.AsNoTracking()
.FirstOrDefaultAsync(d => d.AccountId == accountId, ct);
if (deck is null) return null;
var defIds = deck.Cards.Select(c => c.CardDefinitionId).ToList();
if (defIds.Count == 0) return null;
var defs = await _catalogDb.Set<CardDefinition>()
.AsNoTracking()
.Where(d => defIds.Contains(d.Id) || d.Id == deck.ArchSpiritCardDefinitionId)
.ToDictionaryAsync(d => d.Id, ct);
if (!defs.TryGetValue(deck.ArchSpiritCardDefinitionId, out var archSpirit))
return null;
var cards = deck.Cards
.Where(c => defs.ContainsKey(c.CardDefinitionId))
.Select(c => (defs[c.CardDefinitionId], c.Quantity))
.ToList();
return (cards, archSpirit);
}
}
@@ -0,0 +1,152 @@
namespace SOR.Ai.Training;
using SOR.Ai.Core;
using SOR.Ai.Engine;
using SOR.Ai.Heuristics;
using SOR.Database.Entities.Catalog;
using SOR.Database.Enums;
using SOR.Game;
using SOR.Game.Grid;
/// <summary>
/// Runs a single AI-vs-AI game synchronously in-process (no DB, no NATS, no delays).
///
/// Both players supply pre-loaded deck cards and ArchSpirit definitions.
/// The game loop:
/// 1. Placement: both AI place ArchSpirit at a random starting-zone tile.
/// 2. Main loop: alternate turns via the decision engine until GamePhase.GameOver.
///
/// Returns the winner's account ID or null if the turn limit was hit without a decision.
/// </summary>
internal sealed class SelfPlayRunner
{
private const int MaxTurns = 200; // hard guard against infinite loops
/// <summary>Run a complete AI vs AI game. Returns the winning accountId string or null.</summary>
public static string? Run(
Guid p1AccountId,
int p1Difficulty,
string p1Strategy,
IEnumerable<(CardDefinition def, int qty)> p1Deck,
CardDefinition p1ArchSpirit,
Guid p2AccountId,
int p2Difficulty,
string p2Strategy,
IEnumerable<(CardDefinition def, int qty)> p2Deck,
CardDefinition p2ArchSpirit,
GameRules? rules = null)
{
var sessionId = Guid.NewGuid();
var state = GameEngine.Initialize(
sessionId,
p1AccountId, p1Deck, p1ArchSpirit,
p2AccountId, p2Deck, p2ArchSpirit,
rules);
var p1IdStr = p1AccountId.ToString();
var p2IdStr = p2AccountId.ToString();
var profile1 = AiDifficultyProfiles.Get(p1Difficulty).WithStrategy(p1Strategy);
var profile2 = AiDifficultyProfiles.Get(p2Difficulty).WithStrategy(p2Strategy);
// ── Placement phase ──────────────────────────────────────────────────
PlaceArchSpirit(ref state, p1IdStr, seatIndex: 0);
PlaceArchSpirit(ref state, p2IdStr, seatIndex: 1);
// ── Main game loop ───────────────────────────────────────────────────
int iterations = 0;
while (state.Phase != GamePhase.GameOver && iterations++ < MaxTurns)
{
var activeId = state.ActivePlayerAccountId;
if (activeId is null) break;
var profile = activeId == p1IdStr ? profile1 : profile2;
var engine = ResolveEngine(profile);
var ctx = new AiTurnContext(state, activeId);
IReadOnlyList<AiAction> plan;
try
{
plan = engine.ComputeTurn(ctx);
}
catch
{
plan = [new AiEndTurnAction()];
}
foreach (var action in plan)
{
if (state.Phase == GamePhase.GameOver) break;
ApplyAction(ref state, activeId, action);
}
}
// Determine winner from surviving non-eliminated player.
if (state.Phase == GamePhase.GameOver)
{
var survivor = state.Players
.FirstOrDefault(kv => !kv.Value.IsEliminated);
return survivor.Key; // may be null (default) if all eliminated simultaneously
}
return null; // turn limit hit
}
// ── Helpers ───────────────────────────────────────────────────────────────
private static void PlaceArchSpirit(ref GameState state, string accountId, int seatIndex)
{
if (state.Board is null) return;
if (!state.Board.StartingZones.TryGetValue(seatIndex, out var zone) || zone.Count == 0)
return;
var tiles = zone.ToList();
var coord = tiles[Random.Shared.Next(tiles.Count)];
try { (state, _) = GameEngine.PlaceArchSpirit(state, accountId, coord); }
catch { /* fallback: try any zone tile */ }
}
private static IAiDecisionEngine ResolveEngine(AiDifficultyProfile profile) =>
profile.EngineType switch
{
"Heuristic" => new HeuristicDecisionEngine(profile),
"MCTS" => new MonteCarloEngine(profile),
_ => new RandomDecisionEngine(),
};
private static void ApplyAction(ref GameState state, string actorId, AiAction action)
{
try
{
switch (action)
{
case AiDrawAction:
(state, _) = GameEngine.Draw(state, actorId);
break;
case AiPlayCardAction play:
GameEngine.ChannelCard(state, actorId, play.CardInstanceId, play.TargetTiles);
break;
case AiMoveAction move:
GameEngine.MoveUnit(state, actorId, move.UnitInstanceId, move.Target);
break;
case AiAttackAction atk:
(state, _) = GameEngine.Attack(state, actorId, atk.AttackerInstanceId, atk.TargetInstanceId);
break;
case AiSacrificeAction sac:
GameEngine.Sacrifice(state, actorId, sac.UnitInstanceId);
break;
case AiAscendAction asc:
GameEngine.Ascend(state, actorId, asc.IncomingCardInstanceId);
break;
case AiEndTurnAction:
(state, _) = GameEngine.EndTurn(state, actorId);
break;
}
}
catch
{
// Invalid actions are silently skipped in self-play.
}
}
}
@@ -0,0 +1,32 @@
namespace SOR.Ai.Training;
using System.Text.Json;
/// <summary>
/// Writes TrainingRecords to a JSONL file (one JSON object per line).
/// Intended for offline ML training pipelines — call WriteAsync in bulk, then FlushAsync.
/// Thread-safe for sequential writes; do not call from concurrent tasks on the same instance.
/// </summary>
internal sealed class TrainingDataWriter : IAsyncDisposable
{
private readonly StreamWriter _writer;
public TrainingDataWriter(string path)
{
_writer = new StreamWriter(path, append: true, encoding: System.Text.Encoding.UTF8);
}
public async Task WriteAsync(TrainingRecord record, CancellationToken ct = default)
{
var line = JsonSerializer.Serialize(record);
await _writer.WriteLineAsync(line.AsMemory(), ct);
}
public async Task FlushAsync() => await _writer.FlushAsync();
public async ValueTask DisposeAsync()
{
await _writer.FlushAsync();
await _writer.DisposeAsync();
}
}
@@ -0,0 +1,16 @@
namespace SOR.Ai.Training;
/// <summary>
/// One training sample: a board state (as float features) paired with the action
/// that was taken and the eventual game outcome from the perspective of the acting player.
/// Written to JSONL by TrainingDataWriter.
/// </summary>
internal sealed record TrainingRecord(
Guid GameSessionId,
int TurnNumber,
string ActorAccountId,
float[] Features,
string ActionType,
string ActionJson,
float Outcome // +1.0 = acting player won, -1.0 = acting player lost, 0 = draw
);
@@ -23,13 +23,15 @@ public sealed class GameDbContext : DbContext
public GameDbContext(DbContextOptions<GameDbContext> options)
: base(options) { }
public DbSet<MatchmakingEntry> MatchmakingEntries => Set<MatchmakingEntry>();
public DbSet<GameSession> GameSessions => Set<GameSession>();
public DbSet<GameActionLog> ActionLogs => Set<GameActionLog>();
public DbSet<GameRuleSet> GameRuleSets => Set<GameRuleSet>();
public DbSet<CustomLobby> CustomLobbies => Set<CustomLobby>();
public DbSet<LobbyPreset> LobbyPresets => Set<LobbyPreset>();
public DbSet<BoardTemplate> BoardTemplates => Set<BoardTemplate>();
public DbSet<MatchmakingEntry> MatchmakingEntries => Set<MatchmakingEntry>();
public DbSet<GameSession> GameSessions => Set<GameSession>();
public DbSet<GameActionLog> ActionLogs => Set<GameActionLog>();
public DbSet<GameRuleSet> GameRuleSets => Set<GameRuleSet>();
public DbSet<CustomLobby> CustomLobbies => Set<CustomLobby>();
public DbSet<LobbyPreset> LobbyPresets => Set<LobbyPreset>();
public DbSet<BoardTemplate> BoardTemplates => Set<BoardTemplate>();
public DbSet<AiEloRecord> AiEloRecords => Set<AiEloRecord>();
public DbSet<AiCalibrationRun> AiCalibrationRuns => Set<AiCalibrationRun>();
protected override void OnModelCreating(ModelBuilder builder)
{
@@ -110,5 +112,19 @@ public sealed class GameDbContext : DbContext
e.Property(b => b.StartingZonesJson).HasColumnType("jsonb");
e.HasIndex(b => b.IsEnabled);
});
builder.Entity<AiEloRecord>(e =>
{
e.ToTable("ai_elo_records");
e.HasKey(r => r.Id);
e.HasIndex(r => r.AiAccountId).IsUnique();
});
builder.Entity<AiCalibrationRun>(e =>
{
e.ToTable("ai_calibration_runs");
e.HasKey(r => r.Id);
e.HasIndex(r => r.RunAt);
});
}
}
@@ -0,0 +1,20 @@
namespace SOR.Database.Entities.Game;
/// <summary>
/// Records the outcome of a self-play calibration batch.
/// Each row is one batch: DifficultyA vs DifficultyB over GameCount games.
/// WinRateA is A's win fraction (0.0–1.0).
/// </summary>
public sealed class AiCalibrationRun
{
public Guid Id { get; set; } = Guid.NewGuid();
public DateTimeOffset RunAt { get; set; } = DateTimeOffset.UtcNow;
public int DifficultyA { get; set; }
public int DifficultyB { get; set; }
public float WinRateA { get; set; }
public int GameCount { get; set; }
/// <summary>Optional notes (e.g. "baseline", "after weight-tuning").</summary>
public string? Notes { get; set; }
}
@@ -0,0 +1,20 @@
namespace SOR.Database.Entities.Game;
/// <summary>
/// Per-AI-account ELO record for self-play calibration.
/// Tracks a separate ELO score for each AI account, independent of the player RankScore,
/// so calibration runs don't pollute the human leaderboard.
/// </summary>
public sealed class AiEloRecord
{
public Guid Id { get; set; } = Guid.NewGuid();
public Guid AiAccountId { get; set; }
/// <summary>Internal AI ELO, seeded at 1200. Updated by AiEloService on every AI game.</summary>
public int EloScore { get; set; } = 1200;
public int Wins { get; set; }
public int Losses { get; set; }
public DateTimeOffset UpdatedAt { get; set; } = DateTimeOffset.UtcNow;
}
@@ -0,0 +1,616 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using SOR.Database.Contexts;
#nullable disable
namespace SOR.Database.Migrations.Game
{
[DbContext(typeof(GameDbContext))]
[Migration("20260412214256_AddAiEloAndCalibration")]
partial class AddAiEloAndCalibration
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasDefaultSchema("game")
.HasAnnotation("ProductVersion", "8.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("SOR.Database.Entities.Game.AiCalibrationRun", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<int>("DifficultyA")
.HasColumnType("integer");
b.Property<int>("DifficultyB")
.HasColumnType("integer");
b.Property<int>("GameCount")
.HasColumnType("integer");
b.Property<string>("Notes")
.HasColumnType("text");
b.Property<DateTimeOffset>("RunAt")
.HasColumnType("timestamp with time zone");
b.Property<float>("WinRateA")
.HasColumnType("real");
b.HasKey("Id");
b.HasIndex("RunAt");
b.ToTable("ai_calibration_runs", "game");
});
modelBuilder.Entity("SOR.Database.Entities.Game.AiEloRecord", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("AiAccountId")
.HasColumnType("uuid");
b.Property<int>("EloScore")
.HasColumnType("integer");
b.Property<int>("Losses")
.HasColumnType("integer");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.Property<int>("Wins")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("AiAccountId")
.IsUnique();
b.ToTable("ai_elo_records", "game");
});
modelBuilder.Entity("SOR.Database.Entities.Game.BoardTemplate", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("GridType")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Height")
.HasColumnType("integer");
b.Property<int>("HexPolygonSides")
.HasColumnType("integer");
b.Property<int>("HexSideLength")
.HasColumnType("integer");
b.Property<int>("HexSides")
.HasColumnType("integer");
b.Property<bool>("IsAvailableForCustom")
.HasColumnType("boolean");
b.Property<bool>("IsAvailableForRanked")
.HasColumnType("boolean");
b.Property<bool>("IsEnabled")
.HasColumnType("boolean");
b.Property<int>("MaxPlayers")
.HasColumnType("integer");
b.Property<int>("MinPlayers")
.HasColumnType("integer");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("StartingZonesJson")
.IsRequired()
.HasColumnType("jsonb");
b.Property<string>("TilesJson")
.IsRequired()
.HasColumnType("jsonb");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.Property<int>("Width")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("IsEnabled");
b.ToTable("board_templates", "game");
});
modelBuilder.Entity("SOR.Database.Entities.Game.CustomLobby", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("AdditionalPlayersJson")
.HasColumnType("text")
.HasColumnName("additional_players_json");
b.Property<string>("AiSlotsJson")
.HasColumnType("text");
b.Property<int?>("BoardHeightOverride")
.HasColumnType("integer");
b.Property<string>("BoardShapeOverride")
.HasColumnType("text");
b.Property<Guid?>("BoardTemplateIdOverride")
.HasColumnType("uuid");
b.Property<int?>("BoardWidthOverride")
.HasColumnType("integer");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<bool?>("DiscardOnMaxHandOverride")
.HasColumnType("boolean");
b.Property<int?>("DrawPerTurnOverride")
.HasColumnType("integer");
b.Property<bool?>("FirstPlayerSkipsDrawOverride")
.HasColumnType("boolean");
b.Property<string>("GameMode")
.IsRequired()
.ValueGeneratedOnAdd()
.HasColumnType("text")
.HasDefaultValue("FFA")
.HasColumnName("game_mode");
b.Property<Guid?>("GameSessionId")
.HasColumnType("uuid");
b.Property<Guid?>("GuestAccountId")
.HasColumnType("uuid");
b.Property<Guid?>("GuestDeckId")
.HasColumnType("uuid");
b.Property<string>("GuestFirstTurnPref")
.HasColumnType("text");
b.Property<bool>("GuestReady")
.HasColumnType("boolean");
b.Property<int?>("HandSizeCapOverride")
.HasColumnType("integer");
b.Property<int?>("HexSidesOverride")
.HasColumnType("integer");
b.Property<Guid>("HostAccountId")
.HasColumnType("uuid");
b.Property<Guid>("HostDeckId")
.HasColumnType("uuid");
b.Property<string>("HostFirstTurnPref")
.HasColumnType("text");
b.Property<bool>("HostReady")
.HasColumnType("boolean");
b.Property<int?>("MaxArchTier1Override")
.HasColumnType("integer");
b.Property<int?>("MaxDeckSizeOverride")
.HasColumnType("integer");
b.Property<int>("MaxPlayers")
.HasColumnType("integer");
b.Property<int?>("MinDeckSizeOverride")
.HasColumnType("integer");
b.Property<int?>("MpBuffOverride")
.HasColumnType("integer");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<int?>("OpeningHandSizeOverride")
.HasColumnType("integer");
b.Property<string>("Password")
.HasColumnType("text");
b.Property<int?>("SpAccumulationPerTurnOverride")
.HasColumnType("integer");
b.Property<int?>("SpCapOverride")
.HasColumnType("integer");
b.Property<bool?>("SpHasCapOverride")
.HasColumnType("boolean");
b.Property<int?>("StartingRandomTilePctOverride")
.HasColumnType("integer");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("text");
b.Property<string>("TeamAssignmentsJson")
.HasColumnType("text");
b.Property<int>("TeamCount")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasDefaultValue(1)
.HasColumnName("team_count");
b.Property<int?>("TimeLimitMinutesOverride")
.HasColumnType("integer");
b.Property<int?>("TurnLimitOverride")
.HasColumnType("integer");
b.Property<int?>("TurnTimerSecondsOverride")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("HostAccountId");
b.HasIndex("Status", "CreatedAt");
b.ToTable("custom_lobbies", "game");
});
modelBuilder.Entity("SOR.Database.Entities.Game.GameActionLog", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ActionType")
.IsRequired()
.HasColumnType("text");
b.Property<Guid>("ActorAccountId")
.HasColumnType("uuid");
b.Property<Guid>("GameSessionId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("OccurredAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("PayloadJson")
.HasColumnType("jsonb")
.HasColumnName("payload");
b.Property<string>("ResultJson")
.HasColumnType("jsonb")
.HasColumnName("result");
b.Property<int>("SequenceNumber")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ActorAccountId");
b.HasIndex("GameSessionId", "SequenceNumber")
.IsUnique();
b.ToTable("action_logs", "game");
});
modelBuilder.Entity("SOR.Database.Entities.Game.GameRuleSet", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<int>("BoardHeight")
.HasColumnType("integer");
b.Property<Guid?>("BoardTemplateId")
.HasColumnType("uuid");
b.Property<int>("BoardWidth")
.HasColumnType("integer");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<bool>("DiscardOnMaxHand")
.HasColumnType("boolean");
b.Property<int>("DrawPerTurn")
.HasColumnType("integer");
b.Property<bool>("FirstPlayerSkipsDraw")
.HasColumnType("boolean");
b.Property<string>("GridType")
.IsRequired()
.HasColumnType("text");
b.Property<int>("HandSizeCap")
.HasColumnType("integer");
b.Property<int>("HexSides")
.HasColumnType("integer");
b.Property<bool>("IsCustomDefault")
.HasColumnType("boolean");
b.Property<bool>("IsRankedDefault")
.HasColumnType("boolean");
b.Property<int>("LoserOpReward")
.HasColumnType("integer");
b.Property<int>("MaxArchTier1")
.HasColumnType("integer");
b.Property<int>("MaxDeckSize")
.HasColumnType("integer");
b.Property<int>("MinDeckSize")
.HasColumnType("integer");
b.Property<int>("MpBuff")
.HasColumnType("integer");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<int>("OpeningHandSize")
.HasColumnType("integer");
b.Property<int>("RankDiffOpMultiplierPct")
.HasColumnType("integer");
b.Property<int>("SpAccumulationPerTurn")
.HasColumnType("integer");
b.Property<int>("SpCap")
.HasColumnType("integer");
b.Property<bool>("SpHasCap")
.HasColumnType("boolean");
b.Property<int>("StartingRandomTilePct")
.HasColumnType("integer");
b.Property<int>("TimeLimitMinutes")
.HasColumnType("integer");
b.Property<int>("TurnLimit")
.HasColumnType("integer");
b.Property<int>("TurnTimerSeconds")
.HasColumnType("integer");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.Property<int>("WinnerOpReward")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("IsCustomDefault");
b.HasIndex("IsRankedDefault");
b.ToTable("game_rule_sets", "game");
});
modelBuilder.Entity("SOR.Database.Entities.Game.GameSession", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("AdditionalPlayersJson")
.HasColumnType("text")
.HasColumnName("additional_players_json");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset?>("EndedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("GameMode")
.IsRequired()
.ValueGeneratedOnAdd()
.HasColumnType("text")
.HasDefaultValue("FFA")
.HasColumnName("game_mode");
b.Property<DateTimeOffset?>("LastActionAt")
.HasColumnType("timestamp with time zone");
b.Property<int>("PlayerCount")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasDefaultValue(2)
.HasColumnName("player_count");
b.Property<Guid>("PlayerOneAccountId")
.HasColumnType("uuid");
b.Property<Guid>("PlayerOneDeckId")
.HasColumnType("uuid");
b.Property<bool>("PlayerOneReady")
.HasColumnType("boolean");
b.Property<int>("PlayerOneTeamIndex")
.HasColumnType("integer");
b.Property<Guid>("PlayerTwoAccountId")
.HasColumnType("uuid");
b.Property<Guid>("PlayerTwoDeckId")
.HasColumnType("uuid");
b.Property<bool>("PlayerTwoReady")
.HasColumnType("boolean");
b.Property<int>("PlayerTwoTeamIndex")
.HasColumnType("integer");
b.Property<string>("RuleSnapshotJson")
.HasColumnType("jsonb")
.HasColumnName("rule_snapshot");
b.Property<DateTimeOffset?>("StartedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("StateJson")
.HasColumnType("jsonb")
.HasColumnName("state");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("text");
b.Property<int>("TeamCount")
.HasColumnType("integer");
b.Property<string>("WinCondition")
.HasColumnType("text");
b.Property<Guid?>("WinnerAccountId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("PlayerOneAccountId");
b.HasIndex("PlayerTwoAccountId");
b.HasIndex("Status", "CreatedAt");
b.ToTable("game_sessions", "game");
});
modelBuilder.Entity("SOR.Database.Entities.Game.LobbyPreset", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<Guid>("OwnerAccountId")
.HasColumnType("uuid");
b.Property<string>("RulesJson")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("OwnerAccountId");
b.ToTable("lobby_presets", "game");
});
modelBuilder.Entity("SOR.Database.Entities.Game.MatchmakingEntry", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("AccountId")
.HasColumnType("uuid");
b.Property<Guid>("DeckId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("JoinedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid?>("MatchedGameSessionId")
.HasColumnType("uuid");
b.Property<int>("RankScore")
.HasColumnType("integer");
b.Property<DateTimeOffset?>("ResolvedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("AccountId", "Status");
b.HasIndex("Status", "RankScore");
b.ToTable("matchmaking_entries", "game");
});
modelBuilder.Entity("SOR.Database.Entities.Game.GameActionLog", b =>
{
b.HasOne("SOR.Database.Entities.Game.GameSession", "Session")
.WithMany("ActionLog")
.HasForeignKey("GameSessionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Session");
});
modelBuilder.Entity("SOR.Database.Entities.Game.GameSession", b =>
{
b.Navigation("ActionLog");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,75 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SOR.Database.Migrations.Game
{
/// <inheritdoc />
public partial class AddAiEloAndCalibration : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "ai_calibration_runs",
schema: "game",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
RunAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
DifficultyA = table.Column<int>(type: "integer", nullable: false),
DifficultyB = table.Column<int>(type: "integer", nullable: false),
WinRateA = table.Column<float>(type: "real", nullable: false),
GameCount = table.Column<int>(type: "integer", nullable: false),
Notes = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ai_calibration_runs", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ai_elo_records",
schema: "game",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
AiAccountId = table.Column<Guid>(type: "uuid", nullable: false),
EloScore = table.Column<int>(type: "integer", nullable: false),
Wins = table.Column<int>(type: "integer", nullable: false),
Losses = table.Column<int>(type: "integer", nullable: false),
UpdatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ai_elo_records", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_ai_calibration_runs_RunAt",
schema: "game",
table: "ai_calibration_runs",
column: "RunAt");
migrationBuilder.CreateIndex(
name: "IX_ai_elo_records_AiAccountId",
schema: "game",
table: "ai_elo_records",
column: "AiAccountId",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ai_calibration_runs",
schema: "game");
migrationBuilder.DropTable(
name: "ai_elo_records",
schema: "game");
}
}
}
@@ -23,6 +23,66 @@ namespace SOR.Database.Migrations.Game
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("SOR.Database.Entities.Game.AiCalibrationRun", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<int>("DifficultyA")
.HasColumnType("integer");
b.Property<int>("DifficultyB")
.HasColumnType("integer");
b.Property<int>("GameCount")
.HasColumnType("integer");
b.Property<string>("Notes")
.HasColumnType("text");
b.Property<DateTimeOffset>("RunAt")
.HasColumnType("timestamp with time zone");
b.Property<float>("WinRateA")
.HasColumnType("real");
b.HasKey("Id");
b.HasIndex("RunAt");
b.ToTable("ai_calibration_runs", "game");
});
modelBuilder.Entity("SOR.Database.Entities.Game.AiEloRecord", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("AiAccountId")
.HasColumnType("uuid");
b.Property<int>("EloScore")
.HasColumnType("integer");
b.Property<int>("Losses")
.HasColumnType("integer");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.Property<int>("Wins")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("AiAccountId")
.IsUnique();
b.ToTable("ai_elo_records", "game");
});
modelBuilder.Entity("SOR.Database.Entities.Game.BoardTemplate", b =>
{
b.Property<Guid>("Id")
@@ -332,8 +332,9 @@ internal abstract class GameHandlerBase
var (winnerDelta, loserDelta) = GameEngine.ComputeEloDelta(winner.RankScore, loser.RankScore);
winner.RankScore += winnerDelta;
loser.RankScore = Math.Max(0, loser.RankScore - loserDelta);
// AI accounts track ELO separately — don't adjust player RankScore.
if (!winner.IsAi) winner.RankScore += winnerDelta;
if (!loser.IsAi) loser.RankScore = Math.Max(0, loser.RankScore - loserDelta);
// Compute OriginPoints rewards from the rule snapshot.
var snap = JsonSerializer.Deserialize<OpSnapshot>(
@@ -345,8 +346,8 @@ internal abstract class GameHandlerBase
var winnerOp = Math.Max(1, snap.WinnerOpReward + adjustment);
var loserOp = Math.Max(0, snap.LoserOpReward - adjustment);
winner.OriginPoints += winnerOp;
loser.OriginPoints += loserOp;
if (!winner.IsAi) winner.OriginPoints += winnerOp;
if (!loser.IsAi) loser.OriginPoints += loserOp;
await identityDb.SaveChangesAsync(ct);
@@ -470,11 +471,11 @@ internal abstract class GameHandlerBase
}
}
// Apply clamped deltas.
// Apply clamped deltas — AI accounts are excluded from player RankScore/OP.
foreach (var acc in accounts)
{
acc.RankScore = Math.Max(0, acc.RankScore + rankDeltas[acc.Id]);
acc.OriginPoints += Math.Max(0, opDeltas[acc.Id]);
if (!acc.IsAi) acc.RankScore = Math.Max(0, acc.RankScore + rankDeltas[acc.Id]);
if (!acc.IsAi) acc.OriginPoints += Math.Max(0, opDeltas[acc.Id]);
}
await identityDb.SaveChangesAsync(ct);