PHP D20 Dice

Here is a simple PHP D20 Dice rolling script that I wrote to simulate the one in Open RPG.  It takes the following string: 1d20*13+14 and outputs something similar to: [5d8] => [3,2,5,4,3] = 17
<?php
 
// PHP 5
class dice {
 
 // format 1d20*13+14 
 function roll($input)
 {
 
  $math = array("+", "-", "*", "/");
 
  // split the string into individual characters
  $characters = str_split($input);
 
  // loop through array and halt when it finds a character in
  // math array
  foreach($characters as $char)
  {
   if(!in_array($char, $math))
   {
    $die .= $char;
   } else {
    break;
   } 
  }
 
  $parts = explode("d", $die);
  $num = $parts[0]; // number of dice to roll
  $sides = $parts[1]; // number of sides on the dice
 
  // to figure out equation
  // final $char should be one of the math symbols
  $extra = explode($char, $input);
 
  // roll x number of die
  for($i=1; $i <= $num; $i++)
  {
   // add to array
   $rolls[$i] = rand(1, $sides);
  }
 
  // creates string of numbers
  foreach($rolls as $roll)
  {
   $numbers .= $roll . ',';
  }
 
  // removes trailing , from string of numbers to form [ numbers ]
  $numbers = substr($numbers, 0, -1);
 
  // sum array - get total of all dice rolled
  $total = array_sum($rolls);
 
  // solves error with calc_string method...
  // if it doesn't contain something like *2 (2d*2) which is 2 characters in length
  // don't bother with attempting to calculate the string otherwise,
  // build the string to be calculated
  if(strlen($extra[1] >= 2))
  {
 
   // build equation string
   $eq = $total . ' ' . $char . '' . $extra[1];
 
   // compute final total
   $final = $this->calc_string($eq);
 
  }else{
   $final = $total;
  }
 
  echo '[' . $input . '] => ['.$numbers.'] = ' . $final . '<br>';
 }
 
 function calc_string( $mathString )
 {
  $cf_DoCalc = create_function("", "return (" . $mathString . ");" );
 
  return $cf_DoCalc();
 }
 
};
 
if(isset($_POST['submit']))
{
 $times = $_POST['times'];
 $dice = new dice();
 for($i=1; $i <= $times; $i++)
 {
  $dice->roll($_POST['roll']);
 }
}
 
 
?>
 
<html>
<head>
<title>Roll Dice</title>
</head>
 
<body>
<form method="post" action="<?php echo $PHP_SELF; ?>">
Roll: <input type="text" name="roll"><br>
Number of Times to Roll: <input type="text" name="times"><br>
<input type="submit" value="roll" name="submit">
</form>

No comments :