Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- function usage() {
- print("Usage: php dice.php <roll_string> [print_flag]\n");
- }
- function roll($sides, $num, $print) {
- $sum = 0;
- if ($print) {
- if ($num == 1) {
- print("Rolling 1 $sides-sided die.\n");
- }
- else {
- print("Rolling $num $sides-sided dice.\n");
- }
- }
- for ($count = 0; $count < $num; $count++) {
- $sum += mt_rand(1, $sides);
- }
- if ($print) {
- print("Result: $sum\n-------\n");
- }
- return $sum;
- }
- function roll_string($string, $print) {
- $clause = '((\d)+(d(\d+))?)';
- $join = '(\s*[\+-]\s*)';
- $first_clause = "^$join?$clause";
- $match = "$first_clause($join$clause)*$";
- if (!preg_match("/$match/", $string)) {
- print("Malformed string.\n");
- return FALSE;
- }
- $total = 0;
- while (preg_match("/$first_clause/", $string, $matches)) {
- if (count($matches) == 6) {
- $clause_val = roll($matches[5], $matches[3], $print);
- }
- else {
- $clause_val = $matches[3];
- }
- if (preg_match('/\s*-\s*/', $matches[1])) {
- $clause_val *= -1;
- }
- $total += $clause_val;
- $string = preg_replace("/$first_clause/", '', $string);
- }
- return $total;
- }
- $print = 1;
- if (count($argv) == 3) {
- $print = $argv[2];
- }
- elseif (count($argv) != 2) {
- usage();
- return;
- }
- $total = roll_string($argv[1], $print);
- if ($total !== FALSE) {
- print("Total: $total\n");
- }
Add Comment
Please, Sign In to add comment