Which Unit Attacks First? Building a Polytopia Battle Planner in TypeScript
A Swordsman and an Archer can kill the same Warrior in either order. Send the Swordsman first and it loses 5 HP. Send the Archer first and both units walk away untouched. That's the turn I use to explain the Polytopia b
A Swordsman and an Archer can kill the same Warrior in either order. Send the Swordsman first and it loses 5 HP. Send the Archer first and both units walk away untouched.
That's the turn I use to explain the Polytopia battle planner. In this turn-based strategy game, you choose when each unit attacks. The damage is deterministic. To recommend an order, I need a simulator that agrees with the player's combat log and a definition of βbetterβ that can tell two successful kills apart.
What counts as damage?
Give the defending Warrior 10/10 HP, defence 2 and a forest bonus of 1.5Γ. The Swordsman (attack 3) and Archer (attack 2) are both healthy. The Warrior can hit the Swordsman back. The Archer is firing from outside its reach.
| Attack order | First exchange | Finishing hit | Friendly HP lost |
|---|---|---|---|
| Swordsman, Archer | Swordsman deals 7 and takes 5. Warrior has 3 HP left. | Archer removes 3 HP. | 5 |
| Archer, Swordsman | Archer deals 4 and takes 0. Warrior has 6 HP left. | Swordsman removes 6 HP. | 0 |
The first row turns on a half point. The Swordsman's attack force is 3. The Warrior's defence force is also 3 (2 Γ 1.5). Each gets half the combined force. The Swordsman's hit rounds from 6.75 to 7. The counter uses the Warrior's pre-hit force, so it rounds from 4.5 to 5. Only the next exchange sees a Warrior at 3 HP.
Here's the arithmetic for an ordinary direct hit on a living target. The HP fractions below are already clamped to [0, 1], and this excerpt assumes positive total force. The caller supplies retaliation eligibility from unit abilities, status and the player's range setting. The planner has no map coordinates.
const roundDamage = (value: number) => Math.round(value + 1e-10);
const attackForce = attack * attackerHpFraction;
const defenceForce = defence * defenderHpFraction * defenceMultiplier;
const totalForce = attackForce + defenceForce;
const hit = roundDamage((attackForce / totalForce) * attack * 4.5);
const damage = Math.min(defenderHp, hit);
const retaliation = damage < defenderHp && canRetaliate
? Math.min(attackerHp, roundDamage((defenceForce / totalForce) * defence * 4.5))
: 0;
The tiny offset protects half-up rounding when floating-point arithmetic lands just below a half. The HP cap matters separately. In the first row the Archer's finishing shot rounds to 6, but only 3 HP remain. Recording 6 would give the plan credit for damage it never dealt. Both orders remove exactly 10 HP. The formula walkthrough works through the force calculation, and the standalone formula and tests are small enough to run separately.
One of my favourite regression cases is a 7/10 HP Warrior attacking a full-health, poisoned Warrior on a standard bonus tile. Poison selects its own multiplier for each bonus category. Open, standard and walled go from 1, 1.5 and 4 to 0.5, 0.7 and 2 respectively. Here both forces equal 1.4, so the hit rounds from 4.5 to 5. Halving the standard bonus would give 0.75 and predict 4 damage. That one-point difference is what the test asserts. The other terrain cases are in Defence bonuses and poison.
Rounding also has a version boundary. For ordinary splash damage on a secondary target, the planner's default ruleset (v116, mapped to game build 2.18.1) rounds the full hit, halves it, then takes the floor. The legacy v115 rule halves the raw hit before rounding. A raw hit of 7 gives 3 splash damage under the former and 4 under the latter.
Give βbetterβ an ordering
For the two orders above, βdid the target die?β gives a tie. A weighted score could break it, but choosing a weight for kills would also set an exchange rate between enemy kills and friendly HP. For the recommended plan I want a simpler rule. If one order kills more defenders, that settles the comparison. Only a tie gets to the next question.
Here's a shortened rendering of the recommended comparator. A negative result ranks a ahead of b. JavaScript's || moves on when the difference is zero.
function compareRecommended(a: SimulationResult, b: SimulationResult): number {
return b.defendersKilled - a.defendersKilled
|| b.attackersAlive - a.attackersAlive
|| b.starTrade - a.starTrade
|| b.defenderStarsLost - a.defenderStarsLost
|| a.attackerStarsLost - b.attackerStarsLost
|| a.totalHpLost - b.totalHpLost
|| a.attackersUsed - b.attackersUsed
|| a.defenderHpRemaining - b.defenderHpRemaining
|| b.survivingAttackerHp - a.survivingAttackerHp;
}
Stars are the game's currency. The planner values dead units in stars and subtracts friendly losses from enemy losses to get the trade. Friendly survivors include units that never had to act. In the forest fight, both orders tie through all the star fields. Friendly HP lost is the first difference, so the Archer goes first. When every field ties, the search favours the lexicographically earlier sequence of original attacker indices. That keeps the player's own order when it scores just as well.
Put a budget on the search
The search chooses attacker order. Each action picks the first living defender in the supplied list, and area attacks can also affect designated secondary targets. Once all defenders fall, unused units stay back. A separate pass can drop a unit that contributed neither damage nor status if removing it preserves kills and damage and scores at least as well. There's no independent choice of every target and every subset of attackers.
Six distinct attackers have 720 possible orders. Eight have 40,320. Identical combat profiles reduce the estimate, and support units are excluded. The UI runs small searches synchronously. Above 20,000 estimated orders, it makes the player's simulation available and sends the recommendation job to a Web Worker.
The request carries the attackers, defenders, recommended objective, ruleset and time budget. The replies carry an opening estimate, occasional progress counts and a final result.
type OptimizerWorkerResponse =
| { type: "start"; total: number; timeLimitMs: number }
| { type: "progress"; evaluated: number }
| { type: "done"; best: SimulationResult;
permutationsEvaluated: number; complete: boolean };
Before exploring orders, the solver simulates the input order and a greedy order, keeping the better of the two. It already has a playable answer when the timed search starts exploring alternatives. The worker gets a 20-second budget and checks elapsed time every 4,096 terminal evaluations. A run can overshoot the budget or finish before its first progress message. If the first few attacks kill everything, many orders share the same ending, so the final count can be well below the starting estimate even on a completed search.
Show the five HP
If the player enters Swordsman first, the result can explain the recommendation with βsave 5 HP.β Enter Archer first and a second battle log would just make the player hunt for a difference. The UI compares the same nine outcome fields as the recommended comparator and suppresses the extra card on a tie. When outcomes differ, it can show positive changes in HP, survivors, attackers used, kills or star value. The attack-order guide gives the player more positions to try.
There's one piece of that UI I'd change. The worker returns complete: false when it stops at the time checkpoint, but the result handler keeps only best. Its βalready optimalβ message can therefore appear after a partial search. For the two-unit fight, both orders are cheap to check. For a timed-out search, the claim I can actually defend is βNo better order found within the budget.β The solver already knows the difference. The result screen needs that last boolean too.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.