Skip to main content
2 of 5
added 97 characters in body
Philipp
  • 121.5k
  • 28
  • 261
  • 342

When you think about soldiers sitting in trenches firing at each other with a constant fire rate, you could model it by giving each soldier an x% chance to hit and eliminate one enemy soldier per shot, and repeat until one army is defeated.

Note: The function random() in this example returns pseudoradom floating-point values equally distributed between 0.0 and 1.0.

double kill_chance = 0.05; // 5% chance to kill an enemy per round
int troops_A = 57; // starting strenght of army A
int troops_B = 89; // starting strength of army B

// combat loop
while (troops_A > 0 && troops_B > 0) {
    int losses_A = 0;
    int losses_B = 0;
    // army A fires
    for (int i = 0; i < troops_A; i++) {
         if (random() < kill_chance) losses_B++;
    }
    // army B fires
    for (int i = 0; i < troops_B; i++) {
         if (random() < kill_chance) losses_A++;
    }
    // remove casualties
    troops_A -= losses_A;
    troops_B -= losses_B;
    // here would be a good place to report the combat progress to the player
}
// make sure no army ends up with a negative amount of soldiers
if (troops_A < 0) troops_A = 0;
if (troops_B < 0) troops_B = 0;

Note that this algorithm allows for a result where both armies lose. This would be equivalent to the last two soldiers shooting each other and then bleeding to death. Yeah, war is hell.

Philipp
  • 121.5k
  • 28
  • 261
  • 342