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. <?php
  2. function doDice($text){ //the main dice function
  3. 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
  4. return rolldice($things[2], $things[3], $things[1]);
  5. }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.
  6. return rolldice($things[3], $things[4], $things[1], $things[2]);
  7. } //end motive check
  8. } //end main function
  9.  
  10. function rolldice($dice, $sides, $originalText = null, $motive = null)
  11. { //the core of the roll dice function
  12. $total = 0; //the total value
  13. for ($i=1; $i <= $dice; $i++) //loop for the amount of dice
  14. {
  15. $dv = rand(1, $sides); //get a random number from 1 to the number of sides on the dice
  16. $total = $total + $dv; //add to the total.
  17. } //end our loop
  18. $string = ($motive != null) ? "$originalTextRolling $dice dice with $sides sides &lt;$motive&gt;...Total value: $total" : "$originalTextRolling $dice dice with $sides sides...Total Value: $total";
  19. //Above: set the string depending on if a motive is specified or not
  20. return $string; //return the string from above with the original text from the post or other item
  21. } //end the core function
  22. ?>


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. $message = doDice("Here is the original message and i'm rolling a dice with motive.. [dice=My Motive Here]1d10[/dice]");
  2. print $message;


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,379
Rating:
There are currently no comments for this tutorial, login or register to leave one.