Kingshot Simulator 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). Returns win rates, casualty distributions, 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,
    "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 simplex grid optimization (0%โ€“100% in 5% or 10% steps) to determine the mathematically optimal Attacker troop ratio (Infantry / Cavalry / Archers) to defeat a given Defender Garrison.
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
    },
    "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}")
GET /api/v1/heroes
Metadata
Returns the complete database of Kingshot heroes across Generations 1 through 7, 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/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']}")
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']}")
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. High lightly-injured ratio.
0% Dead / 30% Inj / 70% 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.