Need a unique gift idea?
A Pastebin account makes a great Christmas gift
SHARE
TWEET

Untitled

a guest Sep 22nd, 2018 59 Never
Upgrade to PRO!
ENDING IN00days00hours00mins00secs
 
  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. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top