I'm trying to create a random die roller, and I've got the computed section worked out, but I can't get the results to display multiples.

For example: The user enters the number of sides on the die (such as 6 for a normal cube die), then the number of rolls. The computed section iterates a for loop with the number of rolls as the endpoint. Each roll is randomized using the number of sides field.

I tried a foreach loop with the following:

foreach ($node_field as $value) {
  $display = $node_field_item['value'];
}

But I get an error that I've used an invalid argument in the foreach statement.

Is there an easy way to display multiple results?

Here is my computed code:

for ($n = 0; $n <= ($node->field_rolls[0]['value'] - 1); $n++) {
  $node_field[$n]['value'] = rand(1, $node->field_sides[0]['value']);
}

Any help is appreciated!

Comments

Steel Rat’s picture

Ok, I've scrapped what I was trying to do previously, and went with a code snippet for rolling dice someone else posted.

I had it working very briefly, but then the results all started returning 0.

Here's my computed code:

$expression = $node->field_sides[0]['value'];
$node_field[0]['value'] = print_r(roll_dice($expression), true);

function roll_dice($roll) {
        $rolls = explode(",", $roll);
        for ($i = 0; $i < count($rolls); $i++) {
                preg_match('/^\s*(\d+)\s*d\s*(\d+)\s*/i', $rolls[$i], $match);
                $n = 0;
                for ($j = 0; $j < $match[1]; $j++) {
                        $n += rand(1, $match[2]);
                }
                $rolls[$i] = $n;
        }
        return $rolls;
}

And the display code is the default.

The expression field_sides field expects a format of xdy where x = the number of rolls and y = the number of sides on the die.

Any ideas?

Steel Rat’s picture

For some reason the $rolls[$i] value was always returning zero. I changed it to just $rolls and it works fine now. It just means the user can't enter multiple rolls, which I can deal with until I figure out something better.

Steel Rat’s picture

One thing I need to be able to do here as well is break out each die roll and have it displayed. Right now all I get is a total.

Steel Rat’s picture

Well, I figured out how to get the individual rolls, but then the result display is messed up when using a view. I don't suppose there's a way to make a hidden field to store the individual die rolls which I can then display as needed.

Justin Freeman’s picture

Assigned: Unassigned » Justin Freeman
Status: Active » Closed (fixed)
Steel Rat’s picture

Thanks,