PHP Roll Dice


This short tutorial will show you how to create a dice roller in PHP with BBCode for things such as a forum or a CMS.

This was originally requested by zerocool in the RMB forum topid ID 480
PHP Code
  1.  
  2. <?php
  3. function doDice($text){ //the main dice function
  4. if(preg_match("/^(.*?)\[dice\]\s*(\d+)\s*d\s*(\d+)\s*\[\/dice\]/i", $text, $things)) { //if it matches only the [dice]1d10[/dice] then do without the motive
  5. return rolldice($things[2], $things[3], $things[1]);
  6. }elseif(preg_match("/^(.*?)\[dice=(.*?)\]\s*(\d+)\s*d\s*(\d+)\s*\[\/dice\]/i", $text, $things)){ //or if it does have [dice=My Motive]1d10[/dice] supply the motive.
  7. return rolldice($things[3], $things[4], $things[1], $things[2]);
  8. } //end motive check
  9. } //end main function
  10.  
  11. function rolldice($dice, $sides, $originalText = null, $motive = null)
  12. { //the core of the roll dice function
  13. $total = 0; //the total value
  14. for ($i=1; $i <= $dice; $i++) //loop for the amount of dice
  15. {
  16. $dv = rand(1, $sides); //get a random number from 1 to the number of sides on the dice
  17. $total = $total + $dv; //add to the total.
  18. } //end our loop
  19. $string = ($motive != null) ? "$originalTextRolling $dice dice with $sides sides &lt;$motive&gt;...Total value: $total" : "$originalTextRolling $dice dice with $sides sides...Total Value: $total";
  20. //Above: set the string depending on if a motive is specified or not
  21. return $string; //return the string from above with the original text from the post or other item
  22. } //end the core function
  23. ?>
  24.  


You must start with the doDice function on your post in order for it to run correctly.
So you would have something like the following:
PHP Code
  1.  
  2. $message = doDice("Here is the original message and i'm rolling a dice with motive.. [dice=My Motive Here]1d10[/dice]");
  3. print $message;
  4.  


This will output:

Here is the original message and I'm rolling a dice with motive..
Rolling 1 dice with 10 sides <My Motive Here>
Total value: X


X would be the total value returned by the core's $total variable which is calculated per-die.

Hope you learned something from this.
ShadowMage's Avatar
Author:
Views:
11,310
Rating:
There are currently no comments for this tutorial, login or register to leave one.