Files
SVSimServer/SVSim.EmulatedEntrypoint/Services/ArenaTwoPickService.cs
gamer147 cc40e2d2e8 feat(svc): ChooseClassAsync + ChooseCardAsync (draft state machine)
Implements the class-selection and card-pick turns for the Take Two arena draft:
- ChooseClassAsync validates class is offered, locks ClassId, generates first pick set via pool
- ChooseCardAsync appends the two picked cards, advances SelectTurn 1–15, completes draft at turn 15
- 6 new tests covering happy paths and all error codes (class_not_offered, invalid_state, invalid_selection)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-31 11:03:50 -04:00

273 lines
10 KiB
C#

using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using SVSim.Database;
using SVSim.Database.Models;
using SVSim.Database.Repositories.Globals;
using SVSim.Database.Repositories.Viewer;
using SVSim.Database.Services;
using SVSim.EmulatedEntrypoint.Models.Dtos.Common.ArenaTwoPick;
using SVSim.EmulatedEntrypoint.Models.Dtos.Responses.ArenaTwoPick;
namespace SVSim.EmulatedEntrypoint.Services;
public class ArenaTwoPickService : IArenaTwoPickService
{
private readonly IArenaTwoPickRunRepository _runs;
private readonly IArenaTwoPickRewardRepository _rewards;
private readonly IArenaTwoPickCardPoolService _pool;
private readonly IGameConfigService _config;
private readonly IViewerRepository _viewers;
private readonly RewardGrantService _grants;
private readonly IViewerEntitlements _entitlements;
private readonly IRandom _rng;
private readonly SVSimDbContext _db;
public ArenaTwoPickService(
IArenaTwoPickRunRepository runs,
IArenaTwoPickRewardRepository rewards,
IArenaTwoPickCardPoolService pool,
IGameConfigService config,
IViewerRepository viewers,
RewardGrantService grants,
IViewerEntitlements entitlements,
IRandom rng,
SVSimDbContext db)
{
_runs = runs; _rewards = rewards; _pool = pool; _config = config;
_viewers = viewers; _grants = grants; _entitlements = entitlements; _rng = rng; _db = db;
}
public async Task<TopResponseDto> GetTopAsync(long viewerId)
{
var run = await _runs.GetByViewerIdAsync(viewerId);
if (run is null) return new TopResponseDto { EntryInfo = null };
var dto = new TopResponseDto
{
EntryInfo = ProjectEntryInfo(run, viewerId),
BattleResults = ProjectBattleResults(run),
};
if (run.ClassId != 0)
{
dto.ClassInfo = ProjectClassInfo(run);
dto.DeckInfo = ProjectDeckInfo(run);
if (run.WinCount > 0 || run.LossCount > 0)
dto.LeaderSkinId = run.LeaderSkinId;
}
return dto;
}
public async Task<EntryResponseDto> EntryAsync(long viewerId, int consumeItemType)
{
if (await _runs.GetByViewerIdAsync(viewerId) is not null)
throw new ArenaTwoPickException("arena_two_pick_already_in_progress");
const long ticketItemId = 80001;
var viewer = await LoadViewerForGrantsAsync(viewerId);
var ticket = viewer.Items.FirstOrDefault(i => i.Item.Id == (int)ticketItemId);
int postStateTickets;
if (_entitlements.IsFreeplay)
{
postStateTickets = ticket?.Count ?? 0;
}
else
{
if (ticket is null || ticket.Count < 1)
throw new ArenaTwoPickException("insufficient_ticket");
ticket.Count -= 1;
postStateTickets = ticket.Count;
}
var aCfg = _config.Get<SVSim.Database.Models.Config.ArenaTwoPickConfig>();
var maxWins = Math.Max(1, await _rewards.GetMaxWinCountAsync());
var candidates = SampleCandidateClasses(aCfg.AllowedClassIds, _rng);
var run = new ViewerArenaTwoPickRun
{
ViewerId = viewerId,
EntryId = 0,
RewardScheduleId = aCfg.RewardScheduleId,
ChallengeId = aCfg.ChallengeId,
MaxBattleCount = maxWins,
ClassId = 0,
LeaderSkinId = 0,
CandidateClassIdsJson = JsonSerializer.Serialize(candidates),
SelectTurn = 0,
IsSelectCompleted = false,
SelectedCardIdsJson = "[]",
PendingPickSetsJson = "[]",
NextCandidateId = 1,
ResultListJson = "[]",
WinCount = 0,
LossCount = 0,
IsRetire = false,
};
await _runs.UpsertAsync(run);
run.EntryId = run.Id;
await _runs.UpsertAsync(run);
await _db.SaveChangesAsync();
return new EntryResponseDto
{
EntryInfo = ProjectEntryInfo(run, viewerId),
RewardList = new List<RewardEntryDto>
{
new RewardEntryDto { RewardType = 4, RewardId = ticketItemId, RewardNum = postStateTickets },
},
CandidateClassIds = candidates,
BattleResults = new BattleResultsDto { WinCount = 0, ResultList = new List<int>() },
};
}
private static List<int> SampleCandidateClasses(List<int> allowed, IRandom rng)
{
if (allowed.Count < 3)
throw new InvalidOperationException("ArenaTwoPickConfig.AllowedClassIds needs ≥3 entries");
var shuffled = allowed.OrderBy(_ => rng.Next(int.MaxValue)).ToList();
return shuffled.Take(3).ToList();
}
private async Task<SVSim.Database.Models.Viewer> LoadViewerForGrantsAsync(long viewerId)
{
return await _db.Viewers
.Include(v => v.Currency)
.Include(v => v.Items).ThenInclude(i => i.Item)
.Include(v => v.Cards)
.Include(v => v.Sleeves)
.Include(v => v.Emblems)
.Include(v => v.Degrees)
.Include(v => v.LeaderSkins)
.Include(v => v.MyPageBackgrounds)
.AsSplitQuery()
.FirstAsync(v => v.Id == viewerId);
}
public async Task<ClassChooseResponseDto> ChooseClassAsync(long viewerId, int classId)
{
var run = await _runs.GetByViewerIdAsync(viewerId)
?? throw new ArenaTwoPickException("arena_two_pick_no_active_run");
if (run.ClassId != 0)
throw new ArenaTwoPickException("arena_two_pick_invalid_state");
var candidates = JsonSerializer.Deserialize<List<int>>(run.CandidateClassIdsJson) ?? new();
if (!candidates.Contains(classId))
throw new ArenaTwoPickException("arena_two_pick_class_not_offered");
run.ClassId = classId;
run.LeaderSkinId = ResolveClassDefaultLeaderSkin(classId);
var pairs = _pool.GeneratePickSetsForTurn(classId, turn: 1, startingPairId: run.NextCandidateId, _rng);
run.NextCandidateId += pairs.Count;
run.SelectTurn = 1;
run.PendingPickSetsJson = JsonSerializer.Serialize(pairs);
await _runs.UpsertAsync(run);
return new ClassChooseResponseDto
{
ClassInfo = ProjectClassInfo(run),
DeckInfo = ProjectDeckInfo(run),
CandidateCardList = pairs.Select(p => new CandidatePairDto
{
Id = p.Id, Turn = p.Turn, SetNum = p.SetNum,
CardId1 = p.CardId1, CardId2 = p.CardId2,
IsSelected = p.IsSelected ? 1 : 0,
}).ToList(),
};
}
// Placeholder: class default skin = class id. Matches the capture's "leader_skin_id":"1" when class_id=1.
private static long ResolveClassDefaultLeaderSkin(int classId) => classId;
public async Task<CardChooseResponseDto> ChooseCardAsync(long viewerId, long selectedId)
{
var run = await _runs.GetByViewerIdAsync(viewerId)
?? throw new ArenaTwoPickException("arena_two_pick_no_active_run");
if (run.ClassId == 0 || run.IsSelectCompleted)
throw new ArenaTwoPickException("arena_two_pick_invalid_state");
var pending = JsonSerializer.Deserialize<List<CandidatePair>>(run.PendingPickSetsJson) ?? new();
var pick = pending.FirstOrDefault(p => p.Id == selectedId)
?? throw new ArenaTwoPickException("arena_two_pick_invalid_selection");
var selectedCards = JsonSerializer.Deserialize<List<long>>(run.SelectedCardIdsJson) ?? new();
selectedCards.Add(pick.CardId1);
selectedCards.Add(pick.CardId2);
run.SelectedCardIdsJson = JsonSerializer.Serialize(selectedCards);
List<CandidatePair>? nextPairs = null;
if (run.SelectTurn < 15)
{
run.SelectTurn += 1;
nextPairs = _pool.GeneratePickSetsForTurn(run.ClassId, run.SelectTurn, run.NextCandidateId, _rng);
run.NextCandidateId += nextPairs.Count;
run.PendingPickSetsJson = JsonSerializer.Serialize(nextPairs);
}
else
{
run.IsSelectCompleted = true;
run.PendingPickSetsJson = "[]";
}
await _runs.UpsertAsync(run);
return new CardChooseResponseDto
{
DeckInfo = ProjectDeckInfo(run),
CandidateCardList = nextPairs?.Select(p => new CandidatePairDto
{
Id = p.Id, Turn = p.Turn, SetNum = p.SetNum,
CardId1 = p.CardId1, CardId2 = p.CardId2,
IsSelected = p.IsSelected ? 1 : 0,
}).ToList(),
};
}
public Task<FinishResponseDto> RetireAsync(long viewerId) => throw new NotImplementedException();
public Task<FinishResponseDto> FinishAsync(long viewerId) => throw new NotImplementedException();
public Task<BattleFinishResultDto> RecordBattleResultAsync(long viewerId, bool isWin) => throw new NotImplementedException();
// --- projection helpers (kept internal so test subclasses could exercise if needed) ---
internal static EntryInfoDto ProjectEntryInfo(ViewerArenaTwoPickRun run, long viewerId) => new()
{
Id = run.EntryId,
ViewerId = viewerId,
RewardScheduleId = run.RewardScheduleId,
ChallengeId = run.ChallengeId,
MaxBattleCount = run.MaxBattleCount,
LeaderSkinId = run.LeaderSkinId,
IsRetire = run.IsRetire ? 1 : 0,
};
internal static BattleResultsDto ProjectBattleResults(ViewerArenaTwoPickRun run)
{
var bools = JsonSerializer.Deserialize<List<bool>>(run.ResultListJson) ?? new();
return new()
{
ResultList = bools.Select(b => b ? 1 : 0).ToList(),
WinCount = run.WinCount,
};
}
internal static ClassInfoDto ProjectClassInfo(ViewerArenaTwoPickRun run)
{
var ids = JsonSerializer.Deserialize<List<int>>(run.CandidateClassIdsJson) ?? new();
return new()
{
ClassId1 = ids.ElementAtOrDefault(0),
ClassId2 = ids.ElementAtOrDefault(1),
ClassId3 = ids.ElementAtOrDefault(2),
SelectedClassId = run.ClassId,
};
}
internal static DeckInfoDto ProjectDeckInfo(ViewerArenaTwoPickRun run)
{
var cards = JsonSerializer.Deserialize<List<long>>(run.SelectedCardIdsJson) ?? new();
return new()
{
TwoPickEntryId = run.EntryId,
ClassId = run.ClassId,
IsSelectCompleted = run.IsSelectCompleted,
SelectedCardIds = cards,
SelectTurn = run.SelectTurn == 0 ? 1 : run.SelectTurn,
};
}
}