RPG Creator Battles Revisited

I can't help it. Every once in a while the RPG Creator pops up in my head and I need to work on it a little. Sooner or later I get distracted by something else, but most of the times I actually make a few steps towards completion. This time I revisited the battle script and turned it into a class.

There is actually not much new to show here. I already talked about the basic functionality in another article on this blog. The biggest addition is the validation logic for the two opponents. The validation just makes sure the opponents have all values needed for battle calculation.

/**
 * Validates a battle's opponent.
 *
 * @param array $array
 *   A battle opponent representated by an array
 *   consisting of four values: attack, defense,
 *   armor & damage.
 * @return boolean
 */
private static validateOpponent($array) {
  $valid = TRUE;
  if (!isset($array['attack']) || !is_numeric($array['attack'])) {
    $valid = FALSE;
  }
  else if (!isset($array['defense']) || !is_numeric($array['defense'])) {
    $valid = FALSE;
  }
  else if (!isset($array['armor']) || !is_numeric($array['armor'])) {
    $valid = FALSE;
  }
  else if (!isset($array['damage']) || !is_numeric($array['damage'])) {
    $valid = FALSE;
  }
  else if (isset($array['health']) && !is_numeric($array['health'])) {
    $valid = FALSE;
  }
  return $valid;
}

To calculate a battle outcome, create two opponents and run the class'es solve function. You will receive an array with all calculated round in return.

$attacker = array(
  'attack' => 100,
  'defense' => 50,
  'armor' => 10,
  'damage' => 25,
  'health' => 100,
);

$defender = array(
  'attack' => 80,
  'defense' => 40,
  'armor' => 20,
  'damage' => 15,
  'health' => 100,
);

$results = RpgBattle::solve($attacker, $defender);

The full source code can be found on Github.