Боевой цикл, этап 2 плана: таблица баланса боя, случайность ±5%, прогноз риска, полный итог боя

Числа боя (ревью 27.10.2026, п. 2.5):
- BattleRules (модуль Боя, без Unity) — все числа в одном месте, с версией
- таблица BattleConfig (Assets/Resources/BattleConfig.asset) — меняется в Inspector, App/GameModules переводит её в BattleRules
- сила воинов по-прежнему из GameData.Troops

Случайность (план 27.10.2026):
- каждой стороне от −5% до +5% (шаг 0,1%), из номера боя BattleRequest.Seed (SplitMix64)
- тот же номер с теми же войсками — всегда тот же итог; поход получает battleSeed при выступлении и хранит его

Прогноз:
- IBattleSystem.Forecast: «преимущество / исход неясен / высокий риск поражения», диапазоны силы и потерь
- окно атаки показывает прогноз риска вместо точного итога; окно итога боя — силы и удачу сторон

Итог боя (ревью, п. 2.3):
- для обеих сторон по типам: до боя, выжившие, погибшие, раненые (пока нули — доля не утверждена)
- номер боя, версия правил, удача сторон

Тесты: случайность воспроизводима и в пределах ±5%; прогноз не противоречит 300 боям с разными номерами;
итог сходится по типам у обеих сторон; правила из таблицы; тот же поход — тот же бой.
Все 37 тестов ModuleTests прогнаны вне Unity — проходят.

Открыто для команды (Battle.md): показывать ли шанс победы в процентах; порядок бонусов и случайности.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alexander
2026-10-28 19:03:14 +01:00
co-authored by Claude Opus 5.5
parent ebb03489d0
commit eeb90b8cb6
16 changed files with 513 additions and 67 deletions
+132 -5
View File
@@ -212,7 +212,7 @@ public class ModuleTests
[Test]
public void Battle_MoreSoldiersWins_TieGoesToDefender()
{
var battle = new BattleSystem();
var battle = new BattleSystem(BattleRules.NoRandom);
Assert.IsTrue(battle.Resolve(new BattleRequest { Attackers = 30, Defenders = 20 }).Victory);
Assert.IsFalse(battle.Resolve(new BattleRequest { Attackers = 20, Defenders = 20 }).Victory);
Assert.AreEqual(20, battle.Resolve(new BattleRequest { Attackers = 30, Defenders = 20 }).Survivors);
@@ -221,7 +221,7 @@ public class ModuleTests
[Test]
public void Battle_Counters_ArchersBeatInfantry_InfantryBeatsCavalry()
{
var battle = new BattleSystem();
var battle = new BattleSystem(BattleRules.NoRandom);
// Одинаковая "сырая" сила: 25 лучников x5 = 125 против ~31 пехоты x4 = 124
var archersVsInfantry = battle.Resolve(new BattleRequest
{ AttackerUnits = new[] { 0, 25, 0, 0 }, DefenderUnits = new[] { 32, 0, 0, 0 } });
@@ -235,7 +235,7 @@ public class ModuleTests
[Test]
public void Battle_WallsHelpDefenders_SiegeBreaksWalls()
{
var battle = new BattleSystem();
var battle = new BattleSystem(BattleRules.NoRandom);
var field = battle.Resolve(new BattleRequest { AttackerUnits = new[] { 22, 0, 0, 0 }, DefenderUnits = new[] { 20, 0, 0, 0 } });
var walls = battle.Resolve(new BattleRequest { AttackerUnits = new[] { 22, 0, 0, 0 }, DefenderUnits = new[] { 20, 0, 0, 0 }, DefenderFortified = true });
Assert.IsTrue(field.Victory);
@@ -249,7 +249,7 @@ public class ModuleTests
[Test]
public void Battle_LossesPerType_NeverExceedUnits_AndSumUp()
{
var battle = new BattleSystem();
var battle = new BattleSystem(BattleRules.NoRandom);
var rnd = new Random(7);
for (int run = 0; run < 500; run++)
{
@@ -276,7 +276,7 @@ public class ModuleTests
[Test]
public void Battle_EdgeCases_OutcomeAndArithmetic()
{
var b = new BattleSystem();
var b = new BattleSystem(BattleRules.NoRandom);
var cases = new[]
{
new BattleRequest { AttackerUnits = new[] { 1, 0, 0, 0 }, DefenderUnits = new[] { 1, 0, 0, 0 } }, // 1 x 1
@@ -324,6 +324,133 @@ public class ModuleTests
Assert.IsFalse(b.Resolve(cases[8]).Victory, "обе силы обнулились -- ничья, защитнику");
}
// ---------------- Боевой цикл (этап 2 плана от 27.10.2026) ----------------
static readonly BattleRequest SampleBattle = new BattleRequest
{ AttackerUnits = new[] { 12, 8, 6, 4 }, DefenderUnits = new[] { 8, 6, 4, 2 }, DefenderFortified = true };
[Test]
public void Battle_Luck_IsReproducible_AndWithinFivePercent()
{
var b = new BattleSystem();
bool plus = false, minus = false, differs = false;
BattleOutcome first = default;
for (long seed = 1; seed <= 2000; seed++)
{
var r = SampleBattle; r.Seed = seed;
BattleOutcome o = b.Resolve(r);
BattleOutcome again = b.Resolve(r);
Assert.AreEqual(o.AttackerPower, again.AttackerPower, "тот же номер боя -- тот же итог");
Assert.AreEqual(o.Survivors, again.Survivors);
Assert.AreEqual(seed, o.BattleId);
Assert.That(o.AttackerLuckPermille, Is.InRange(-50, 50));
Assert.That(o.DefenderLuckPermille, Is.InRange(-50, 50));
plus |= o.AttackerLuckPermille > 0;
minus |= o.AttackerLuckPermille < 0;
if (seed == 1) first = o; else differs |= o.AttackerPower != first.AttackerPower;
}
Assert.IsTrue(plus && minus && differs, "случайность бывает в обе стороны и меняется от боя к бою");
var noLuck = new BattleSystem(BattleRules.NoRandom);
var req = SampleBattle; req.Seed = 777;
Assert.AreEqual(0, noLuck.Resolve(req).AttackerLuckPermille, "RandomPercent = 0 -- без случайности");
}
[Test]
public void Battle_Forecast_ShowsRisk_AndNeverContradictsRealBattle()
{
var b = new BattleSystem();
var strong = new BattleRequest { AttackerUnits = new[] { 40, 0, 0, 0 }, DefenderUnits = new[] { 10, 0, 0, 0 } };
var weak = new BattleRequest { AttackerUnits = new[] { 5, 0, 0, 0 }, DefenderUnits = new[] { 50, 0, 0, 0 } };
var even = new BattleRequest { AttackerUnits = new[] { 20, 0, 0, 0 }, DefenderUnits = new[] { 20, 0, 0, 0 } };
Assert.AreEqual(BattleChance.Advantage, b.Forecast(strong).Chance);
Assert.AreEqual(BattleChance.HighRisk, b.Forecast(weak).Chance);
Assert.AreEqual(BattleChance.Uncertain, b.Forecast(even).Chance);
bool evenWon = false, evenLost = false;
foreach (var req in new[] { strong, weak, even, SampleBattle })
{
BattleForecast f = b.Forecast(req);
for (long seed = 1; seed <= 300; seed++)
{
var r = req; r.Seed = seed;
BattleOutcome o = b.Resolve(r);
if (f.Chance == BattleChance.Advantage) Assert.IsTrue(o.Victory, "преимущество -- победа при любой удаче");
if (f.Chance == BattleChance.HighRisk) Assert.IsFalse(o.Victory, "высокий риск -- поражение при любой удаче");
Assert.That(o.AttackerPower, Is.InRange(f.AttackerPowerMin, f.AttackerPowerMax));
Assert.That(o.DefenderPower, Is.InRange(f.DefenderPowerMin, f.DefenderPowerMax));
Assert.That(o.AttackerLosses, Is.InRange(f.AttackerLossesMin, f.AttackerLossesMax), "потери в пределах прогноза");
if (req.AttackerUnits == even.AttackerUnits) { evenWon |= o.Victory; evenLost |= !o.Victory; }
}
}
Assert.IsTrue(evenWon && evenLost, "равный бой решает удача: бывает и победа, и поражение");
}
[Test]
public void Battle_Outcome_IsSymmetric_AndAddsUpPerType()
{
var b = new BattleSystem();
var rnd = new Random(11);
for (int run = 0; run < 300; run++)
{
var att = new int[4]; var def = new int[4];
for (int i = 0; i < 4; i++) { att[i] = rnd.Next(0, 25); def[i] = rnd.Next(0, 25); }
BattleOutcome o = b.Resolve(new BattleRequest
{ AttackerUnits = att, DefenderUnits = def, DefenderFortified = rnd.Next(2) == 0, Seed = run });
int attOut = 0, defOut = 0;
for (int i = 0; i < 4; i++)
{
Assert.AreEqual(att[i], o.AttackerUnitsBefore[i]);
Assert.AreEqual(def[i], o.DefenderUnitsBefore[i]);
Assert.AreEqual(att[i], o.AttackerSurvivorUnits[i] + o.AttackerDeadUnits[i] + o.AttackerWoundedUnits[i], "атакующий: до = выжившие + погибшие + раненые");
Assert.AreEqual(def[i], o.DefenderSurvivorUnits[i] + o.DefenderDeadUnits[i] + o.DefenderWoundedUnits[i], "защитник: то же");
Assert.AreEqual(0, o.AttackerWoundedUnits[i] + o.DefenderWoundedUnits[i], "раненых пока нет: доля не утверждена");
Assert.GreaterOrEqual(o.AttackerSurvivorUnits[i], 0);
Assert.GreaterOrEqual(o.DefenderSurvivorUnits[i], 0);
Assert.AreEqual(o.DefenderDeadUnits[i] + o.DefenderWoundedUnits[i], o.DefenderLossUnits[i]);
attOut += o.AttackerDeadUnits[i] + o.AttackerWoundedUnits[i];
defOut += o.DefenderLossUnits[i];
}
Assert.AreEqual(o.AttackerLosses, attOut);
Assert.AreEqual(o.DefenderLosses, defOut);
Assert.AreEqual(BattleRules.Default.Version, o.RulesVersion);
}
}
[Test]
public void Battle_Rules_ComeFromConfig()
{
var req = new BattleRequest { AttackerUnits = new[] { 22, 0, 0, 0 }, DefenderUnits = new[] { 20, 0, 0, 0 }, DefenderFortified = true };
Assert.IsFalse(new BattleSystem(BattleRules.NoRandom).Resolve(req).Victory, "стены +20% держат");
var noWalls = BattleRules.NoRandom;
noWalls.WallsPercent = 0;
noWalls.Version = 2;
BattleOutcome o = new BattleSystem(noWalls).Resolve(req);
Assert.IsTrue(o.Victory, "без стен те же войска побеждают");
Assert.AreEqual(2, o.RulesVersion, "итог помнит версию правил");
}
[Test]
public void World_MarchBattle_IsReproducible()
{
MarchData Run()
{
var world = new WorldSimulation(WorldMapLayout.CreateDefault(), new BattleSystem());
MarchData m = world.StartMarch("p", WorldMapLayout.PlayerCityId, WorldMapLayout.BossCastleId, 30, 1000, out _);
m.units = new[] { 12, 8, 6, 4 };
world.Advance(m.arriveMs, new List<WorldEvent>());
return m;
}
MarchData a = Run(), b = Run();
Assert.AreNotEqual(0, a.battleSeed);
Assert.AreEqual(a.battleSeed, b.battleSeed, "тот же поход -- тот же номер боя");
Assert.AreEqual(a.attackerPower, b.attackerPower);
Assert.AreEqual(a.attackerLuck, b.attackerLuck);
Assert.AreEqual(a.survivors, b.survivors);
}
[Test]
public void World_GarrisonComposition_SumsToGarrison_AndIsStable()
{