General Basketcase REST API

High-performance Monte Carlo battle simulation, multi-participant rally resolution, simplex troop ratio optimization, and parameter sensitivity analysis.

๐ŸŒ Base URL & Root Domain Configuration

Kingshot Simulator is hosted directly as a root application at kssimbasket.duckdns.org with all API routes mounted directly under /api/v1.

Production Direct Domain
https://kssimbasket.duckdns.org/api/v1
Local Standalone (.NET Kestrel)
http://localhost:5032/api/v1
POST /api/v1/simulate/battle
1v1 Battle
Executes a high-speed Monte Carlo battle simulation between an Attacker March and a Defender Garrison across configured iterations (default 10,000) and round limits (maxBattleRounds, default 30). Hero widgets strictly adhere to authentic role-based activation (Attacker marches activate Rally widgets; Defender garrisons activate Defender widgets). Supports optional mixed-tier vanguard meat-shield stratification (attackerMeatShieldConfigs / defenderMeatShieldConfigs), Master configurations (attackerMasters / defenderMasters or player.masters for Cassia & Guinevere Swordland bonuses), and returns win rates, casualty distributions, per-side hero skill trigger & kill telemetry (attackerSkillTriggers / defenderSkillTriggers), and turn-by-turn combat replay telemetry.
import requests

url = "http://localhost:5000/api/v1/simulate/battle"

payload = {
    "selectedScenario": 0,  # 0 = PvP_SoloAttack
    "iterations": 10000,
    "maxBattleRounds": 30,  # Default 30 (Official Game & Web Calc Parity)
    "attackerPlayer": {
        "name": "Attacker Army",
        "squads": [
            { "type": 0, "tier": 10, "count": 150000, "modifiers": { "attack": 150.0, "lethality": 120.0 } },
            { "type": 1, "tier": 10, "count": 60000, "modifiers": { "attack": 150.0, "lethality": 120.0 } },
            { "type": 2, "tier": 10, "count": 90000, "modifiers": { "attack": 150.0, "lethality": 120.0 } }
        ]
    },
    "defenderPlayer": {
        "name": "Defender Garrison",
        "squads": [
            { "type": 0, "tier": 10, "count": 100000, "modifiers": { "defense": 140.0, "health": 110.0 } },
            { "type": 1, "tier": 10, "count": 100000, "modifiers": { "defense": 140.0, "health": 110.0 } },
            { "type": 2, "tier": 10, "count": 100000, "modifiers": { "defense": 140.0, "health": 110.0 } }
        ]
    }
}

response = requests.post(url, json=payload)
data = response.json()

win_rate = (data["attackerWins"] / data["iterations"]) * 100.0
print(f"Attacker Win Rate: {win_rate:.2f}% | Avg Rounds: {data['averageRounds']:.1f}")
print(f"Avg Casualties - Attacker: {data['averageAttackerCasualties']:,.0f} | Defender: {data['averageDefenderCasualties']:,.0f}")
POST /api/v1/simulate/rally
Multi-Participant Rally
Simulates Multi-Participant Rally vs Garrison warfare. Implements Captain/Host active hero skill contributions, Top 4 joiner rally skill aggregation, and distributes post-battle casualties proportionally across all joiners based on troop volume.
import requests

url = "http://localhost:5000/api/v1/simulate/rally"

payload = {
    "selectedScenario": 1,  # 1 = PvP_KingsCastle
    "iterations": 5000,
    "attackerRally": {
        "captain": {
            "name": "Rally Captain",
            "squads": [{ "type": 0, "tier": 10, "count": 300000, "modifiers": { "attack": 250.0 } }]
        },
        "joiners": [
            { "name": "Joiner Alpha", "squads": [{ "type": 1, "tier": 10, "count": 150000 }] },
            { "name": "Joiner Beta", "squads": [{ "type": 2, "tier": 10, "count": 150000 }] }
        ]
    },
    "defenderGarrison": {
        "host": {
            "name": "Castle Defender Host",
            "squads": [{ "type": 0, "tier": 10, "count": 300000, "modifiers": { "defense": 250.0 } }]
        },
        "joiners": [
            { "name": "Reinforcement 1", "squads": [{ "type": 2, "tier": 10, "count": 200000 }] }
        ]
    }
}

res = requests.post(url, json=payload).json()

print(f"Rally Win Rate: {res['attackerWins'] / res['iterations']:.1%}")
for p in res["attackerParticipants"]:
    print(f"  {p['role']} '{p['name']}': Initial {p['initialTroopCount']:,} -> Dead: {p['dead']:,}, Injured: {p['injured']:,}")
POST /api/v1/optimize/troop-ratio
Optimizer
Performs stochastic simplex grid optimization (0%โ€“100% in 5% or 10% steps) to determine the mathematically optimal Attacker troop ratio to defeat a given Defender Garrison. Supports multi-objective optimization: MaxBattleScore (0), MaxWinRate (1), CasualtyTradeRatio (2, Kill-to-Death ratio), and HospitalPreservation (3, soft casualty limits). Available at /api/v1/optimize/troop-ratio and alias /api/v1/simulate/optimize-ratio.
import requests

url = "http://localhost:5000/api/v1/optimize/troop-ratio"

payload = {
    "selectedScenario": 0,
    "constraints": {
        "totalTroopCount": 300000,
        "stepPercent": 5.0,
        "minInfantryPercent": 10.0,
        "objective": 0  # 0 = MaxBattleScore, 1 = MaxWinRate, 2 = CasualtyTradeRatio (K/D), 3 = HospitalPreservation
    },
    "attackerTemplate": {
        "name": "Attacker",
        "squads": [
            { "type": 0, "tier": 10, "modifiers": { "attack": 120.0, "lethality": 100.0 } },
            { "type": 1, "tier": 10, "modifiers": { "attack": 120.0, "lethality": 100.0 } },
            { "type": 2, "tier": 10, "modifiers": { "attack": 120.0, "lethality": 100.0 } }
        ]
    },
    "defenderPlayer": {
        "name": "Archer-Heavy Garrison",
        "squads": [
            { "type": 0, "tier": 10, "count": 50000 },
            { "type": 1, "tier": 10, "count": 50000 },
            { "type": 2, "tier": 10, "count": 200000 }
        ]
    }
}

res = requests.post(url, json=payload).json()

print(f"Optimal Ratio: {res['recommendedRatio']}")
print(f"Rationale: {res['recommendationRationale']}")
print(f"Tested {res['totalCombinationsTested']} combinations in {res['executionTimeMs']} ms")
POST /api/v1/simulate/sensitivity-sweep
Sensitivity Curves
Calculates win-rate and casualty trajectories across stat ranges (e.g. +0% to +50% Lethality vs Attack). Produces marginal gain derivatives (+X% win rate per 10% stat increase) and comparative ROI recommendations.
import requests

url = "http://localhost:5000/api/v1/simulate/sensitivity-sweep"

payload = {
    "selectedScenario": 0,
    "config": {
        "targetSide": 0,  # 0 = Attacker, 1 = Defender
        "primaryParameter": 0,  # 0 = AllSquadsLethality
        "comparisonParameter": 1,  # 1 = AllSquadsAttack
        "rangeMode": 0,  # 0 = RelativeDelta (+/- from base)
        "minValue": 0.0,
        "maxValue": 50.0,
        "stepValue": 10.0,
        "iterationsPerPoint": 50
    },
    "attackerPlayer": { "name": "Attacker", "squads": [{ "type": 0, "tier": 10, "count": 100000 }] },
    "defenderPlayer": { "name": "Defender", "squads": [{ "type": 0, "tier": 10, "count": 100000 }] }
}

res = requests.post(url, json=payload).json()

print(f"ROI Summary: {res['superiorStatSummary']}")
print(f"Insight: {res['comparativeRecommendation']}")

for pt in res["primarySeries"]["points"]:
    print(f"  {pt['label']}: Win Rate = {pt['winRate']:.1f}% | Casualties = {pt['avgAttackerCasualties']:,.0f}")
POST /api/v1/simulate/matchup-matrix
Combinatorial Simulation
Executes an $N \times N$ combinatorial Monte Carlo matchup matrix between multiple attacker and defender lineups. Evaluates 5.0โ˜… heroes at Widget Lv 10 across locked, standardized baseline stats (800% Atk/Def, 1000% Let/HP standard for S5โ€“S8 meta; 500%/700% for legacy S1โ€“S4) to isolate true skill synergies, counter-dynamics, and troop ratio advantages. Supports multi-objective optimization (optimizationGoal: 0 = MaxBattleScore, 1 = MaxWinRate, 4 = CasualtyTradeRatio, 5 = HospitalPreservation) when optimizationMode is enabled.
import requests

url = "http://localhost:5000/api/v1/simulate/matchup-matrix"
payload = {
    "presetName": "Season8",
    "baselineBaseAttackPercent": 800.0,
    "baselineBaseDefensePercent": 800.0,
    "baselineBaseHealthPercent": 1000.0,
    "baselineBaseLethalityPercent": 1000.0,
    "totalTroopCount": 1000000,
    "iterationsPerCell": 100,
    "attackers": [
        { "lineupId": "s8_meta", "displayName": "Diego / Liz / Luna [S8 Meta]", "heroNames": ["Diego", "Liz", "Luna"] },
        { "lineupId": "s7_meta", "displayName": "Charles / Ava / Wee & Woo [S7 Meta]", "heroNames": ["Charles", "Ava", "Wee & Woo"] }
    ],
    "defenders": [
        { "lineupId": "s8_meta", "displayName": "Diego / Liz / Luna [S8 Meta]", "heroNames": ["Diego", "Liz", "Luna"] },
        { "lineupId": "s7_meta", "displayName": "Charles / Ava / Wee & Woo [S7 Meta]", "heroNames": ["Charles", "Ava", "Wee & Woo"] }
    ]
}

res = requests.post(url, json=payload).json()
print(f"Completed {len(res['cells'])} matrix cells in {res['executionTimeMs']:.1f}ms")
POST /api/v1/simulate/matrix-v2
Multi-Context Matrix V2
Evaluates hero trios across 3 real PvP contexts: City Rally Attack (PvP_RallyAttack, 1.25x/1.40x defender), City Garrison Defense (PvP_ReinforcedDefense, 1.25x/1.40x defender), and Neutral Structure / Turret (PvP_Outpost_Turret, 1.00x/1.00x symmetric). Eliminates V1 win-rate saturation by tracking netCasualtyDelta, winnerSurvivorsPercent, avgRounds, Peer-Gen vs Full-Field scores, and range spread (floor, peerAvg, fullAvg, ceiling). Supports optional joinerContext (0 = None, 1 = StandardMeta4x with 4x Chenko Atk / 4x Gordon Def) and troopRatioMode (0 = Standard502030, 1 = Optimized), and returns role leaderboards (rallyLeadRankings, garrisonLeadRankings, turretLeadRankings, flexRankings), individual heroRoleBreakdowns, and joinerLiftRankings. If attackers or defenders are omitted, presets are auto-loaded from presetName and maxSeasonLimit.
import requests

url = "http://localhost:5000/api/v1/simulate/matrix-v2"
payload = {
    "presetName": "AllSeasons",
    "maxSeasonLimit": 8,
    "joinerContext": 1,       # 0 = None, 1 = StandardMeta4x (4x Chenko / 4x Gordon)
    "troopRatioMode": 0,      # 0 = Standard502030, 1 = Optimized
    "iterationsPerCell": 100,
    "includeJoinerLift": True,
    "joinerLiftIterations": 50
}

res = requests.post(url, json=payload).json()
print(f"Simulated {res['totalBattlesSimulated']} battles in {res['executionTimeMs']:.1f}ms")
print(f"Top Rally Lead: {res['rallyLeadRankings'][0]['displayName']} (Score: {res['rallyLeadRankings'][0]['compositeScore']:.1f})")
print(f"Top Garrison Lead: {res['garrisonLeadRankings'][0]['displayName']} (Score: {res['garrisonLeadRankings'][0]['compositeScore']:.1f})")
print(f"Top Flex Trio: {res['flexRankings'][0]['displayName']} (Score: {res['flexRankings'][0]['compositeScore']:.1f})")
POST /api/v1/optimize/beartrap-portfolio
Bear Trap Optimizer
Jointly optimizes 1 Lead Rally Trio (3 heroes) and up to 4 non-overlapping Joiner Captains for Bear Trap & Alliance Event PvE Boss encounters (PvE_Monster). Enforces strict zero hero overlap across all marches, sweeps PvE troop ratios, and returns the optimal portfolio, baseline greedy comparison (% lift), and top alternative portfolios.
import requests

payload = {
    "ownedHeroes": [
        { "name": "Amadeus", "starLevel": 5, "subTier": 5, "widgetLevel": 5, "skillLevel": 5 },
        { "name": "Jabel", "starLevel": 5, "subTier": 5, "widgetLevel": 5, "skillLevel": 5 },
        { "name": "Marlin", "starLevel": 5, "subTier": 5, "widgetLevel": 5, "skillLevel": 5 },
        { "name": "Chenko", "starLevel": 5, "subTier": 5, "widgetLevel": 0, "skillLevel": 5 },
        { "name": "Yeonwoo", "starLevel": 5, "subTier": 5, "widgetLevel": 0, "skillLevel": 5 }
    ],
    "troopTier": "T10",
    "trueGoldLevel": 5,
    "marchCapacity": 150000,
    "numberOfJoinerMarches": 4,
    "bossLevel": 5
}

res = requests.post("http://localhost:5000/api/v1/optimize/beartrap-portfolio", json=payload).json()
print(f"Optimal Damage: {res['optimalTotalDamage']:,.0f} (+{res['damageLiftPercent']:.2f}% vs Greedy)")
POST /api/v1/simulate/predict-matrix
Fast Screening (0ms)
Executes calibrated heuristic screening (Stage 1) to pre-evaluate and rank candidate lineups in under 5ms before triggering full Monte Carlo simulations. Incorporates class-weighted ratio scoring, squad extinction penalties (<8% squads), and generation gap deltas.
import requests

res = requests.post("http://localhost:5000/api/v1/simulate/predict-matrix", json=payload).json()
print(f"Screened {res['totalCombinationsScreened']} pairings in {res['executionTimeMs']:.2f}ms")
GET /api/v1/heroes
Metadata
Returns the complete database of Kingshot heroes across Generations 1 through 8, including base scaling curves, troop specializations, and skill op-codes.
import requests

heroes = requests.get("http://localhost:5000/api/v1/heroes").json()

print(f"Loaded {len(heroes)} Heroes:")
for h in heroes[:5]:
    print(f"  - [{h['generation']}] {h['name']} ({h['troopType']})")
GET /api/v1/heroes/shapley-ratings
Game Theory Attribution
Calculates cooperative game-theoretic Shapley value attribution for all 37 heroes. Evaluates each single hero's true marginal win rate lift (ΔW) across diverse 2-hero shells (Burst, Attrition, Control) to isolate individual hero power from team carry-bias.
import requests

url = "http://localhost:5000/api/v1/heroes/shapley-ratings"
ratings = requests.get(url).json()

print(f"Top 5 Heroes by Shapley Marginal Attribution:")
for r in ratings[:5]:
    print(f"  - {r['heroName']} ({r['troopClass']}): Lift={r['marginalWinRateLift']:+.2f}%, Normalized={r['normalizedShapleyPower']:.1f}/100")
GET /api/v1/encounters
PvE Encounters
Returns pre-calibrated PvE encounter presets (e.g. Level 22 Lion, Beast Bosses) with authentic in-game monster troop tiers, counts, and universal buff scalars.
import requests

encounters = requests.get("http://localhost:5000/api/v1/encounters").json()

for e in encounters:
    print(f"{e['encounterName']}: +{e['universalBuffPercent']}% Buffs | Inf: {e['infantryCount']} | Cav: {e['cavalryCount']} | Arc: {e['archerCount']}")
GET /api/v1/matrix/presets
Presets
Returns pre-configured seasonal lineup presets across Seasons 1 through 8 (including Season 8 Diego/Liz/Luna meta trios, cyclic positional permutations, and cross-generation benchmarks).
import requests

presets = requests.get("http://localhost:5000/api/v1/matrix/presets").json()
for p in presets:
    print(f"{p['id']}: {p['name']} ({p['attackerCount']} lineups)")
POST /api/v1/presets/validate
Validation
Validates JSON preset payloads for march presets (.ksatk / .ksdef) and full battle setups (.ksbtl). Reports schema errors, squad counts, and total troop volume.
import requests

url = "http://localhost:5000/api/v1/presets/validate"

with open("my_march.ksatk", "r") as f:
    json_text = f.read()

res = requests.post(url, json={"jsonContent": json_text}).json()

print(f"Is Valid: {res['isValid']} | Type: {res['detectedType']}")
print(f"Total Troops: {res['totalTroops']:,} across {res['squadCount']} squads")
if res["errors"]:
    print(f"Errors: {res['errors']}")
POST /api/v1/ocr/battle-report
Vision OCR Ingestion
Ingests 1 to 3 in-game Kingshot battle report screenshots (Overview, Hero Comparison, or Troop Power & Stat Bonuses) as multipart/form-data. The vision engine parses player identities, alliance tags, battle outcome, squad counts, TrueGold tiers, and all 12 core military troop stat bonuses for direct simulator population.
cURL
Python
C# (.NET)
curl -X POST "http://localhost:5000/api/v1/ocr/battle-report" \
  -F "files=@report_overview.jpg" \
  -F "files=@report_stats.jpg"
import requests

url = "http://localhost:5000/api/v1/ocr/battle-report"
files = [
    ("files", ("report_overview.jpg", open("report_overview.jpg", "rb"), "image/jpeg")),
    ("files", ("report_stats.jpg", open("report_stats.jpg", "rb"), "image/jpeg"))
]

resp = requests.post(url, files=files)
data = resp.json()

print(f"Outcome: {data['report']['battleOutcome']}")
print(f"Attacker: {data['report']['attacker']['playerName']} ({data['report']['attacker']['totalSquad']} troops)")
print(f"Defender: {data['report']['defender']['playerName']} ({data['report']['defender']['totalSquad']} troops)")
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Json;

using var client = new HttpClient { BaseAddress = new Uri("http://localhost:5000") };
using var form = new MultipartFormDataContent();

form.Add(new ByteArrayContent(File.ReadAllBytes("report.jpg")), "files", "report.jpg");

var response = await client.PostAsync("/api/v1/ocr/battle-report", form);
var result = await response.Content.ReadFromJsonAsync<dynamic>();

Console.WriteLine($"Success: {result.success}, Outcome: {result.report.battleOutcome}");
GET /api/v1/masters
Metadata
Returns all 10 Kingshot Masters (Cassia, Valora, Guinevere, Pan, Roman, Wilson, Aena, Isnor, Olander, Catherine) with their titles, max levels, and 4 skill slots (slot, name, maxLevel, bonusPerLevel, bonusUnit, effectScope). Master configurations can be supplied as PlayerMasterConfig[] via attackerMasters/defenderMasters on /simulate/battle & /simulate/rally, player.masters, or masters on /optimize/beartrap-portfolio.
import requests

resp = requests.get("http://localhost:5032/api/v1/masters")
masters = resp.json()
for m in masters:
    print(m["name"], "-", m["title"], len(m["skills"]), "skills")
ENUM BattleScenario (Battle Types & Locations)
Domain Model
Defines the combat engagement location and sets the exact in-game Casualty Distribution Profile (Losses vs Hospitalized Injured vs Lightly Injured). Passed in "scenario" field on simulation endpoints as either integer ID or enum string name.
Enum Name / Alias Value Category Description Casualty Split (Loss / Injured / Light)
PvP_SoloAttack
Aliases: PvP_CityAttack, PvP_QuickFight
0 Solo PvP Attacking an enemy lord's city. Attacker suffers direct permanent losses.
35% Dead / 10% Inj / 55% Light
PvP_RallyAttack 1 Rally PvP Multi-player coordinated rally march against an enemy settlement or garrison.
35% Dead / 10% Inj / 55% Light
PvP_SoloDefense
Alias: PvP_CityDefense
2 Solo City Defense Defending one's own city. No direct deaths (all route to infirmary up to capacity).
0% Dead / 35% Inj / 65% Light
PvP_ReinforcedDefense 3 Reinforced City Defending city fortified with friendly alliance reinforcement marches.
0% Dead / 35% Inj / 65% Light
PvP_KingsCastle 4 Throne War Battles for King's Castle central throne facility. Safe wounded mode.
0% Dead / 35% Inj / 65% Light
PvP_Outpost_Turret
Aliases: PvP_Outpost_L1 .. L4
5 Alliance Facilities Castle Turret and Outpost combat (neutral structure, 1.00x role multipliers).
0% Dead / 35% Inj / 65% Light
PvP_Fortress
Alias: PvP_Sanctuary
6 Alliance Facilities Alliance Fortress and Sanctuary territorial garrison conflicts.
0% Dead / 30% Inj / 70% Light
Swordland_Building
Aliases: Swordland_CityAttack, Swordland_CityDefense
7 Cross-Server Event Swordland / SVS cross-server event battlefield facilities.
0% Dead / 30% Inj / 70% Light
PvP_TileAttack
Alias: PvP_TileDefense
8 Field Skirmish Resource gathering tile combat on the world map.
0% Dead / 35% Inj / 65% Light
PvP_HQBannerAttack
Alias: PvP_HQBannerDefense
9 Territory Defense Alliance Headquarters and territory Banner attack/defense clashes.
0% Dead / 35% Inj / 65% Light
PvE_Monster
Alias: PvE_Monster_Enemy (101)
100 PvE Hunts Beast, Lion, and Boss hunts. 100% lightly injured (instant zero-loss recovery).
0% Dead / 0% Inj / 100% Light
ENUM TroopType (Troop Classes & Combat Dynamics)
Domain Model
Enumerates the 3 fundamental combat troop classes in Kingshot. Controls row formation placement, targeting behavior, counter damage multipliers, and special class mechanics.
Infantry (0) Frontline Tank

The frontline meat shield. Absorbs 100% of standard enemy attacks until completely depleted. High base Defense and Health stats.

  • โš”๏ธ Deals Counter To: Cavalry (+10% Damage)
  • ๐Ÿ›ก๏ธ Targeting Priority: Front Row (Takes all direct melee & ranged attacks)
  • โญ Primary Scaling Hero: Eric, Amadeus, Zoe
Cavalry (1) Flanking Striker

High-speed shock troops. Features unique 20% Backline Flank penetration directly targeting enemy Archers past the front line.

  • โš”๏ธ Deals Counter To: Infantry (+10% Damage)
  • ๐ŸŽฏ Targeting Split: 80% Enemy Frontline / 20% Direct onto Archers
  • โญ Primary Scaling Hero: Petra, Margot, Helga
Archers (2) Ranged High-DPS

Back-row glass cannons. Highest base Attack and Lethality. Triggers Archer Volley strikes for $+10\%$ expected value damage.

  • โš”๏ธ Deals Counter To: Cavalry (+10% Damage)
  • ๐Ÿน Special Feature: Archer Volley (+10% damage bonus EV)
  • โญ Primary Scaling Hero: Jaeger, Saul, Chenko
The Kingshot Counter Triangle: When attacking a countered unit type, the attacker gains a multiplicative $+10\%$ Counter Bonus: Infantry $\to$ Cavalry $\to$ Archers $\to$ Infantry.
ENUM SensitivityStatParameter (Sweep Parameter Targets)
Domain Model
Specifies which player stat or hero attribute is varied during a parameter sensitivity sweep (POST /api/v1/sensitivity/sweep).
Parameter Name Value Scope Description
AllSquadsLethality0GlobalMutates Lethality % simultaneously across Infantry, Cavalry, and Archers.
AllSquadsAttack1GlobalMutates Attack % across all troop squads.
AllSquadsDefense2GlobalMutates Defense % across all troop squads.
AllSquadsHealth3GlobalMutates Health (HP) % across all troop squads.
InfantryLethality4InfantryMutates only Infantry squad Lethality %.
InfantryAttack5InfantryMutates only Infantry squad Attack %.
InfantryDefense6InfantryMutates only Infantry squad Defense %.
InfantryHealth7InfantryMutates only Infantry squad Health %.
CavalryLethality8CavalryMutates only Cavalry squad Lethality %.
CavalryAttack9CavalryMutates only Cavalry squad Attack %.
CavalryDefense10CavalryMutates only Cavalry squad Defense %.
CavalryHealth11CavalryMutates only Cavalry squad Health %.
ArcherLethality12ArchersMutates only Archer squad Lethality %.
ArcherAttack13ArchersMutates only Archer squad Attack %.
ArcherDefense14ArchersMutates only Archer squad Defense %.
ArcherHealth15ArchersMutates only Archer squad Health %.
LeaderWidgetLevel16Hero WidgetSweeps primary hero widget level (1 through 10) evaluating staircase progression.
TroopMultiplier17Troop CountScales player total army size multiplier ($0.1\times$ to $5.0\times$).
ENUM SkillEvaluationMode (Simulation Execution Mode)
Domain Model
Controls whether hero skill triggers and random procs are evaluated via deterministic expected value math or discrete stochastic Monte Carlo dice rolls.
Mode Name Value Behavior & Mathematical Model Recommended Use Case
Deterministic 0 Expected-Value (EV) Math: Probabilities are mathematically folded into damage factors (e.g., $50\%$ chance for $+50\%$ damage = $1.25\times$ every tick). Produces identical, reproducible single-run trajectories. Quick Fight, instant single-run calibration against Absy EV benchmarks.
Stochastic 1 Probabilistic Dice Rolls: Evaluates discrete RNG rolls per attack/round for skill triggers, Margot dodges, and critical strikes. Simulates real in-game cascading variance and snowballing. Multi-iteration Monte Carlo simulations (250โ€“10,000 battles) for true win rates and casualty bands.
ENUM StatInputMode (Stat Ingestion & Aggregation Workflow)
Domain Model
Explicitly controls whether entered troop stats reflect final battle report totals or baseline account stats to prevent double-counting of hero base % and widgets.
Mode Name Value Behavior & Pipeline Use Case
InReportDirect 0 Direct Battle Report Stats (Default): Entered modifiers are used as-is for combat squads. Heroes contribute only active combat/expedition skill procs (no additive double-counting of hero star % or widgets). Battle report imports (.ksbtl, .ksatk), OCR uploads, manual report matching.
ComponentBuilder 1 Additive Component Builder: Starts from baseline account stats and additively incorporates Hero Star Base %, Widget %, Hero Gear, and granularComponents (pets, chiefGear, chiefCharms, warAcademy, researchTech, vip, citySkin, plus optional perTroopClass overrides for Infantry/Cavalry/Archers) via StatAggregator. Profile builder, theorycrafting, Matchup Matrix simulations.
POST /api/v1/simulate/matchup-matrix
Matchup Matrix & 2-Stage Pipeline
Simulates or screens an $N \times M$ matrix between attacker lineups and defender garrisons. Supports the Two-Stage Pipeline: Stage 1 evaluates large pools in memory (<5ms) using class-weighted ratio heuristics and extinction penalties, pruning candidates down to the Top $K$ ($8 \times 8$), followed by Stage 2 precision Monte Carlo simulation. Also supports Roster Filtering via allowedHeroNames (restricting candidates to owned heroes) and asymmetric userProfileOverride / heroOverrides (stars, subTier, widgetLevel, skillLevel), both also supported on POST /api/v1/simulate/matrix-v2.
import requests

url = "http://localhost:5000/api/v1/simulate/matchup-matrix"

payload = {
    "presetName": "Season4",
    "enableTwoStagePipeline": True,
    "maxCandidatesToSimulate": 8,
    "iterationsPerCell": 100,
    "attackers": [
        {
            "lineupId": "s4_meta",
            "displayName": "Alcar / Margot / Rosa",
            "heroNames": ["Alcar", "Margot", "Rosa"],
            "defaultRatio": { "infantryPercent": 50, "cavalryPercent": 20, "archerPercent": 30 }
        }
    ],
    "defenders": [
        {
            "lineupId": "s4_mirror",
            "displayName": "Alcar / Margot / Rosa",
            "heroNames": ["Alcar", "Margot", "Rosa"],
            "defaultRatio": { "infantryPercent": 50, "cavalryPercent": 20, "archerPercent": 30 }
        }
    ]
}

res = requests.post(url, json=payload).json()
print(f"Two-Stage Used: {res.get('twoStagePipelineUsed')}")
print(f"Screened {res.get('totalCandidatesScreened')} candidates in {res.get('stage1ScreenTimeMs')}ms")
POST /api/v1/simulate/predict-matrix
Stage 1 Heuristic Fast Screen
Instantly screens all candidate attacker lineups and defender garrisons in memory (<5ms) using calibrated empirical ratings, squad extinction thresholds (<8%), and counter weights. Returns candidate rankings and tags the top $K$ for simulation without running Monte Carlo.
GET /api/v1/matrix/presets
Presets
Retrieves all predefined meta presets (Season 1 & 2 Classic, Season 3, Season 4, Season 5, Season 6, Season 7, Season 8, and All Seasons Cross-Generation) with attacker and defender lineup counts.
POST /api/v1/simulate/gauntlet
Personal Lineup Gauntlet (US-017)
Runs a stat-isolated Personal Lineup Gauntlet evaluating a custom player trio (userCustomLineup with custom Atk/Def/HP/Let%, TroopTier, TrueGoldLevel, heroOverrides, and formation ratio, or hydrated via userProfileOverride) against a fixed 5.0โ˜… meta benchmark roster (benchmarkPreset, optionally filtered by allowedHeroNames) as Attacker ($1 \times N$), Defender ($N \times 1$), or Both ($2N$). Also computes Nash Equilibrium meta weights (nashEquilibriumWeight) and Best-in-Class hero champions (bestAttackingInfantry, bestAttackingCavalry, bestAttackingArcher, bestDefendingInfantry, bestDefendingCavalry, bestDefendingArcher).
POST /api/v1/admin/maintenance/purge-telemetry
Selective Telemetry, Calibration & Google OAuth (US-018 / US-019 / US-021)
Provides protected administrative endpoints for selective telemetry purging (POST /api/v1/admin/maintenance/purge-telemetry with beforeUtc, excludeEngineVersion, excludeEventTag: "DragonTyrant", and dryRunOnly), database health inspection (GET /api/v1/admin/maintenance/status), empirical benchmark recalibration (POST /api/v1/admin/maintenance/regenerate-benchmarks), and Monte Carlo vs. Predictive Variance convergence monitoring (GET /api/v1/admin/maintenance/convergence). Protected by Personal Google OAuth 2.0 session cookies (/auth/google/login → /auth/google/callback, validated against AdminAuth:AllowedEmails) or the X-Admin-Key HTTP header matching AdminAuth:FallbackPasscode.
POST /api/v1/war-room/counter-match
Live War Room Tactical Matchmaker (Stories 2.2.1 / 3.2.1)
Executes rapid batch counter-simulations (<300ms) evaluating the active alliance combat card roster against a target enemy profile or parsed battle report. Evaluates win probability, casualty trade ratios, and optimizes troop ratio distribution (e.g. 50/20/30 vs 60/15/25). Returns ranked Top 3 Counter-Leads, tactical rationale, recommended joiners, and a one-click in-game chat rally callout string. Skirmishes are automatically persisted to transient SQLite dossiers and archived to PostgreSQL when configured.
GET /api/v1/war-room/roster
Alliance Combat Cards Roster (Story 2.1.1)
Retrieves the active alliance combat cards roster (top 10โ€“15 rally captains and garrison anchors) pre-configured with heroes, widget tiers, troop classes, and baseline military stats. New cards or updates can be posted via POST /api/v1/war-room/roster.
DELETE /api/v1/war-room/roster/{id}
Remove Alliance Card
Permanently deletes a specified alliance combat card from the active roster database by ID.
POST /api/v1/war-room/roster/merge
Nest-Style Profile Merge
Merges two detected player profiles (handling OCR typos or name variations). Combines hero pools taking max star level (clamped strictly to ≤ 5.0★) and widget level, takes max military stats and capacities, unions joiner skills, deletes the source card, and registers persistent aliases on the target card so future reports automatically resolve to the unified card.
POST /api/v1/war-room/roster/auto-discover
Auto-Discover Alliance Leads
Ingests a parsed battle report to auto-discover or enrich friendly alliance members matching the specified alliance tag (e.g. APT). Adds newly discovered members or enriches existing cards with new heroes, higher widget levels, or improved troop tiers.
GET /api/v1/war-room/enemy-roster
Inferred Enemy Roster & Intelligence (Story 3.2.1)
Retrieves enemy commander profiles compiled and aggregated from battle report screenshots. Tracks encounter frequency, primary battle role (garrison anchor vs rally lead), identified heroes, true gold levels, and military stats. Supports optional query parameter ?eventId={eventId} to filter intelligence strictly to a specific tactical event scope (defaults to the currently active event).
PUT /api/v1/war-room/enemy-roster/{id}
Edit Enemy Profile (US-074)
Manually updates an inferred enemy profile (enemyName, case-sensitive allianceTag, kingdomId, roleFingerprint, troopTier, trueGoldLevel, and optional eventId) across all linked TransientEnemyDossiers rows for that enemy in the current event scope.
POST /api/v1/war-room/enemy-roster/{id}/move
Move Enemy to Event (US-074)
Reassigns an inferred enemy profile and all of its linked historical battle dossiers to a different configured War Room Event ({"targetEventId": "..."}).
GET /api/v1/war-room/events
Tactical Event Scopes
Retrieves tactical event scopes (e.g. KvK #142 Prep, Alliance Clash Nov 29) to group incoming battle intelligence and dossiers under dedicated operational sessions. Also supports POST /api/v1/war-room/events, PUT /api/v1/war-room/events/{id}/activate, and DELETE /api/v1/war-room/events/{id}.
POST /api/v1/war-room/roster/{id}/toggle-war-buffs
Wartime Pet Skill & Combat Buffs
Toggles the active wartime state of an alliance combat card between peacetime baseline stats and wartime elevated stats (with active Pet Skills and castle buffs).