Last active
February 15, 2019 15:59
-
-
Save trollboy/43630bc1c097d63131a4010cb1f01d8d to your computer and use it in GitHub Desktop.
PHP dice roller class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Simple game dice rolling | |
| * Emulates probability as closely as possible | |
| * Feel free to comment/contribute/bughunt | |
| * | |
| * @author Matt Wiseman <trollboy@gmail.com> | |
| */ | |
| class roll { | |
| /** | |
| * | |
| * Universal catcher for dice rolls | |
| * @param str name of the method called | |
| * @param array list of function arguments, although only 1 is supported | |
| * @return int result of dice roll | |
| * | |
| */ | |
| public static function __callStatic ($dice, $args){ | |
| //dice name | |
| $dice = strtolower($dice); | |
| //QTY | |
| $qty = intval($args[0]); | |
| //by default this is going to be 1, the lowest possible roll to make, however d100 is a special case | |
| $lowerlimit = 1; | |
| // total of dice rolled | |
| $result = 0; | |
| switch ($dice) { | |
| case 'd4': | |
| $upperlimit = 4; | |
| break; | |
| case 'd6': | |
| $upperlimit = 6; | |
| break; | |
| case 'd8': | |
| $upperlimit = 8; | |
| break; | |
| case 'd10': | |
| $upperlimit = 10; | |
| break; | |
| case 'd12': | |
| $upperlimit = 12; | |
| break; | |
| case 'd20': | |
| $upperlimit = 20; | |
| break; | |
| case 'd30': | |
| $upperlimit = 30; | |
| break; | |
| case 'd100': | |
| $lowerlimit = 0; | |
| $upperlimit = 9; | |
| break; | |
| //no idea wtf you're trying to roll, so here's a 0 so you at least get an int back | |
| default: | |
| return $result; | |
| break; | |
| } | |
| $i = 0; | |
| while($i < $qty){ | |
| if($dice == 'd100'){ | |
| $preroll = intval( mt_rand($lowerlimit,$upperlimit) . mt_rand($lowerlimit,$upperlimit) ); | |
| // on a roll of double 0, assume 100 | |
| if(!$preroll){ | |
| $result += 100; | |
| } else { | |
| $result += $preroll; | |
| } | |
| } else { | |
| $result += mt_rand($lowerlimit,$upperlimit); | |
| } | |
| $i++; | |
| } | |
| return $result; | |
| } | |
| } | |
| var_dump( | |
| '3d6', | |
| roll::d6(3) | |
| ); | |
| var_dump( | |
| '2d4', | |
| roll::d4(2) | |
| ); | |
| var_dump( | |
| '1d100', | |
| roll::d100(1) | |
| ); |
Author
Author
removed the __construct, included phpDoc comments, and fixed double 0 case error
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
dunno why I left the __construct in there.