Guest User

Untitled

a guest
Sep 22nd, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.32 KB | None | 0 0
  1. <?php
  2.  
  3. function usage() {
  4.     print("Usage: php dice.php <roll_string> [print_flag]\n");
  5. }
  6.  
  7. function roll($sides, $num, $print) {
  8.     $sum = 0;
  9.     if ($print) {
  10.         if ($num == 1) {
  11.             print("Rolling 1 $sides-sided die.\n");
  12.         }
  13.         else {
  14.             print("Rolling $num $sides-sided dice.\n");
  15.         }
  16.     }
  17.     for ($count = 0; $count < $num; $count++) {
  18.         $sum += mt_rand(1, $sides);
  19.     }  
  20.     if ($print) {
  21.         print("Result: $sum\n-------\n");
  22.     }
  23.     return $sum;
  24. }
  25.  
  26. function roll_string($string, $print) {
  27.     $clause = '((\d)+(d(\d+))?)';
  28.     $join = '(\s*[\+-]\s*)';
  29.     $first_clause = "^$join?$clause";
  30.     $match = "$first_clause($join$clause)*$";
  31.     if (!preg_match("/$match/", $string)) {
  32.         print("Malformed string.\n");
  33.         return FALSE;
  34.     }
  35.     $total = 0;
  36.     while (preg_match("/$first_clause/", $string, $matches)) {
  37.         if (count($matches) == 6) {
  38.             $clause_val = roll($matches[5], $matches[3], $print);
  39.         }
  40.         else {
  41.             $clause_val = $matches[3];
  42.         }
  43.         if (preg_match('/\s*-\s*/', $matches[1])) {
  44.             $clause_val *= -1;
  45.         }
  46.         $total += $clause_val;
  47.         $string = preg_replace("/$first_clause/", '', $string);
  48.     }
  49.     return $total;
  50. }
  51.  
  52. $print = 1;
  53. if (count($argv) == 3) {
  54.     $print = $argv[2];
  55. }
  56. elseif (count($argv) != 2) {
  57.     usage();
  58.     return;
  59. }
  60.  
  61. $total = roll_string($argv[1], $print);
  62. if ($total !== FALSE) {
  63.     print("Total: $total\n");
  64. }
Add Comment
Please, Sign In to add comment