Forgot Password / Register
Site Statistics
Total Members: 520
Total Tutorials: 242
Newsest User: 8884244477
Todays Unique Hits: 451
0 Users 1 Guests Online

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
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php 
function doDice($text){ //the main dice function
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
  
return rolldice($things[2], $things[3], $things[1]); 
}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.
  
return rolldice($things[3], $things[4], $things[1], $things[2]); 
//end motive check
//end main function
 
function rolldice($dice$sides$originalText null$motive null
//the core of the roll dice function 
   
$total 0//the total value
   
for ($i=1$i <= $dice$i++) //loop for the amount of dice 
   

      
$dv rand(1$sides); //get a random number from 1 to the number of sides on the dice
      
$total $total $dv//add to the total.
   
//end our loop
$string = ($motive != null) ? "$originalTextRolling $dice dice with $sides sides &lt;$motive&gt;...Total value: $total"$originalTextRolling $dice dice with $sides sides...Total Value: $total";
//Above: set the string depending on if a motive is specified or not
return $string//return the string from above with the original text from the post or other item
//end the core function
?>


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:
Code

$message = doDice("Here is the original message and i'm rolling a dice with motive.. [dice=My Motive Here]1d10[/dice]");
print $message;


This will output:
Code

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
Author:
Views:
10526
Rating:
There are currently no comments for this tutorial.