Turn-Based Combat
Turn-based combat (Pokémon, Final Fantasy, Slay the Spire, XCOM) is a great programming exercise because the whole game is rules and state: stats, a damage formula, turn order, a few actions, an enemy that decides what to do, and a clear win or loss. No physics, no frame timing, and every decision can be printed and checked.
The damage formula
Start with the formula, because it decides how the whole game feels. A common shape: attack minus part of the defense, never below a minimum, with a little randomness and a chance for a critical hit.
using System;
Console.WriteLine("ATK vs DEF -> damage (no randomness)");
foreach (int atk in new[] { 8, 12, 20 })
{
Console.Write(quot;ATK {atk,2}: ");
foreach (int def in new[] { 0, 6, 12, 30 })
Console.Write(quot;DEF {def,2} = {BaseDamage(atk, def),2} ");
Console.WriteLine();
}
static int BaseDamage(int attack, int defense) => Math.Max(1, attack - defense / 2);ATK vs DEF -> damage (no randomness)
ATK 8: DEF 0 = 8 DEF 6 = 5 DEF 12 = 2 DEF 30 = 1
ATK 12: DEF 0 = 12 DEF 6 = 9 DEF 12 = 6 DEF 30 = 1
ATK 20: DEF 0 = 20 DEF 6 = 17 DEF 12 = 14 DEF 30 = 5
Design choices hide in that one line:
defense / 2means defense matters, but never makes you invulnerable on its own.Math.Max(1, …)guarantees every hit does something. Without it, a well-armored enemy can make a fight impossible to win, which feels like a bug.- Small numbers are easier to balance and easier for players to read. Big-number games scale the same formula.
Spreadsheet the formula before coding the game. Tables like the one above show at a glance whether a stat matters too much or too little.
A complete battle
The battle below has a hero and a goblin shaman. Each round, the faster fighter acts first. The hero's choices come from a script (in a real game, a menu); the enemy uses a simple rule-based AI. Randomness uses a seeded generator, so the fight is identical every time you run it. Change the seed to see a different fight.
using System;
using System.Collections.Generic;
var rng = new Random(11);
var hero = new Fighter("Hero", hp: 40, atk: 12, def: 6, speed: 7, potions: 1);
var shaman = new Fighter("Shaman", hp: 34, atk: 10, def: 4, speed: 9, potions: 2);
var heroPlan = new Queue<string>(new[] { "attack", "defend", "attack", "heal", "attack", "attack", "attack", "attack", "attack", "attack" });
for (int round = 1; hero.Alive && shaman.Alive; round++)
{
Console.WriteLine(quot;-- Round {round}: {hero} | {shaman}");
var order = shaman.Speed > hero.Speed ? new[] { shaman, hero } : new[] { hero, shaman };
foreach (var actor in order)
{
if (!hero.Alive || !shaman.Alive) break;
var target = actor == hero ? shaman : hero;
string action = actor == hero ? (heroPlan.Count > 0 ? heroPlan.Dequeue() : "attack") : EnemyChoice(shaman);
Console.WriteLine(" " + actor.Act(action, target, rng));
}
}
Console.WriteLine(hero.Alive ? "Victory!" : "Defeat...");
static string EnemyChoice(Fighter self) =>
self.Hp < self.MaxHp * 0.4 && self.Potions > 0 ? "heal" : "attack";
class Fighter
{
public string Name; public int Hp, MaxHp, Atk, Def, Speed, Potions;
bool defending;
public bool Alive => Hp > 0;
public Fighter(string name, int hp, int atk, int def, int speed, int potions)
{ Name = name; Hp = MaxHp = hp; Atk = atk; Def = def; Speed = speed; Potions = potions; }
public string Act(string action, Fighter target, Random rng)
{
defending = false; // a defend lasts until your next turn
switch (action)
{
case "defend":
defending = true;
return quot;{Name} raises a guard.";
case "heal" when Potions > 0:
Potions--;
int healed = Math.Min(15, MaxHp - Hp);
Hp += healed;
return quot;{Name} drinks a potion (+{healed} HP).";
case "heal":
return quot;{Name} has no potions left!";
default:
if (rng.Next(100) < 10) return quot;{Name} attacks... and misses!";
int damage = Math.Max(1, Atk - target.Def / 2) + rng.Next(-2, 3); // -2..+2 variance
bool crit = rng.Next(100) < 15;
if (crit) damage *= 2;
if (target.defending) damage /= 2;
target.Hp = Math.Max(0, target.Hp - damage);
return quot;{Name} hits {target.Name} for {damage}{(crit ? " (CRITICAL)" : "")}{(target.defending ? " (guarded)" : "")}." +
(target.Alive ? "" : quot; {target.Name} falls!");
}
}
public override string ToString() => quot;{Name} {Hp}/{MaxHp}" + (Potions > 0 ? quot; ({Potions} potion{(Potions == 1 ? "" : "s")})" : "");
}-- Round 1: Hero 40/40 (1 potion) | Shaman 34/34 (2 potions)
Shaman hits Hero for 5.
Hero hits Shaman for 8.
-- Round 2: Hero 35/40 (1 potion) | Shaman 26/34 (2 potions)
Shaman hits Hero for 9.
Hero raises a guard.
-- Round 3: Hero 26/40 (1 potion) | Shaman 26/34 (2 potions)
Shaman hits Hero for 6 (CRITICAL) (guarded).
Hero hits Shaman for 8.
-- Round 4: Hero 20/40 (1 potion) | Shaman 18/34 (2 potions)
Shaman hits Hero for 7.
Hero drinks a potion (+15 HP).
-- Round 5: Hero 28/40 | Shaman 18/34 (2 potions)
Shaman hits Hero for 7.
Hero hits Shaman for 12.
-- Round 6: Hero 21/40 | Shaman 6/34 (2 potions)
Shaman drinks a potion (+15 HP).
Hero hits Shaman for 11.
-- Round 7: Hero 21/40 | Shaman 10/34 (1 potion)
Shaman drinks a potion (+15 HP).
Hero hits Shaman for 10.
-- Round 8: Hero 21/40 | Shaman 15/34
Shaman hits Hero for 6.
Hero hits Shaman for 10.
-- Round 9: Hero 15/40 | Shaman 5/34
Shaman hits Hero for 9.
Hero hits Shaman for 12. Shaman falls!
Victory!
How it's structured
| Concern | Where | Why it's separate |
|---|---|---|
| Stats and state | Fighter fields |
one place to read and save |
| Rules | Act |
every action resolves the same way for the hero and the enemy |
| Decisions | the hero's plan, EnemyChoice |
swapping a menu for the script, or a smarter AI for the rule, changes nothing else |
| Randomness | one seeded rng passed in |
the whole fight replays exactly from the seed |
| Flow | the round loop | turn order and the end condition in one place |
The enemy AI is two lines and already feels intentional: it heals when hurt and has potions. Good game AI is about readable behavior more than clever behavior; Game AI takes this much further.
Balancing by simulation
Because the battle is pure logic, you can simulate thousands of fights and measure the win rate. Designers do exactly this to tune numbers before a playtest:
using System;
int wins = 0, totalRounds = 0;
const int fights = 1000;
for (int seed = 0; seed < fights; seed++)
{
var rng = new Random(seed);
int heroHp = 40, enemyHp = 34, rounds = 0;
while (heroHp > 0 && enemyHp > 0)
{
rounds++;
heroHp -= Math.Max(1, 10 - 6 / 2) + rng.Next(-2, 3); // shaman is faster: hits first
if (heroHp <= 0) break;
enemyHp -= Math.Max(1, 12 - 4 / 2) + rng.Next(-2, 3);
}
if (heroHp > 0) wins++;
totalRounds += rounds;
}
Console.WriteLine(quot;hero win rate: {100.0 * wins / fights:F1}% over {fights} fights");
Console.WriteLine(quot;average length: {(double)totalRounds / fights:F2} rounds");hero win rate: 99.9% over 1000 fights
average length: 3.93 rounds
This stripped-down model (attacks only, no misses, crits or potions) says the hero wins almost every time, in about four rounds. That tells a designer something useful: without its potions the shaman is far too weak, and the full battle above is only tense because of the healing. Raise the shaman's attack in the model (the 10 in the first damage line) and rerun it until the win rate is where you want it, then playtest the real fight.
Make it yours
- Add a "fire" spell that ignores defense but costs mana.
- Give the shaman a pattern: every third turn it charges up, then hits twice as hard (telegraphing the big attack gives the player a chance to defend).
- Support more than two fighters: sort all of them by speed each round.
Test yourself
Why does the damage formula use Math.Max(1, …)?
- To make crits possible
- So every hit does at least 1 damage and high defense can't make a fight unwinnable
- To round the result
- To prevent overflow
Why is the random generator seeded and passed into Act?
- Seeds make hits stronger
- The whole fight can be replayed exactly, which helps debugging, testing and balancing
- C# requires it
- To make the enemy smarter
What is the advantage of simulating many fights in code?
- It replaces playtesting entirely
- You can measure win rates and fight length quickly while tuning numbers
- It makes the game faster
- It generates art