<?php if (!defined('PmWiki')) exit();

# Dice Roller 
# 2011 sebastianseval@gmail.com
# Created 29-Jun-2011 

$RecipeInfo['SimpleDiceRoller']['Version'] = '2011-06-29';
Markup("dice", "directives", '/\\(:dice\\s(.*?)\\s(\d+)d(\d+):\\)/ei', "Roll('$2','$3','$1')");

function Roll($dices,$sides,$id)
{
    global $TimeFmt;

    //finds things like 3d12 changes it
    //to "Roll {3d12 = roll1, roll2, roll3} total"
    $output = "<div class='dice'>";
    if($sides > 200)
    {
        return XL('limit is 200 dice');
    }

    $total = 0;
    $hits = array ();
    $throwings = array ();
    $throwing_exist = false;    
    $ret_string = XL('Roll ').'{'.$dices.'d'.$sides.' = ';

    $pagename = ResolvePageName($pagename);
    $dicefile = FmtPageName('$WorkDir/.dice/$FullName.dice', $pagename);

    # generate a new rolling dice
    for($i = 0; $i < $dices; $i++)
    {
        $roll = rand(1, $sides);
        $hits[] = $roll;
        $total += $roll;
    }

    # proceed only if the file exists
    if (file_exists($dicefile)) {

        # determine the name of this page's dice file
        $throwings = file ($dicefile);

        # Loop through our array
        foreach ($throwings as $throwing_line) {

            $throwing_data = explode ('.', $throwing_line);
            if ($throwing_data[0] == $id) {
                $throwing_exist = true;
                $hits = explode (',', $throwing_data[1]);
                $total = array_sum ($hits);
            }
        }
    }

    # add new line to the .dice file
    if ( !file_exists($dicefile) || $throwing_exist == false) {    
        # create .dice file
        if ( ($fp = @fopen ($dicefile, 'a') ) ) {
            $throwing_line = $id.'.'.implode (',', $hits)."\n";
            fputs($fp, $throwing_line);
            fclose($fp);
        }         
    }
    
    // ...
    $ret_string .= implode (',', $hits); 
    $ret_string .= '} '.$total;
    $ret_string .= '<!-- '.XL('roll generated at ').strftime($TimeFmt).' -->';

    $output .= $ret_string;
    $output .= '</div>';

    return $output;
  
}