Pergunta

I'm new to PHP and am trying to write a PHP script, which should immitade throwing a dice over and over again, until every number was rolled at least once. I had a lot of attempts including many different ways of building the loop, but always get some kind of error. What ever method I used, I always gave each side of the dice a counter, which looks like this:

$rollCount1 = 0;
$rollCount2 = 0;
$rollCount3 = 0;
$rollCount4 = 0;
$rollCount5 = 0;
$rollCount6 = 0;

In case of using an array, it looked like this:

$diceSides = array (1,2,3,4,5,6);

This is how my "while"-loop looks like:

while ($rollCount1 > 0 && $rollCount2 > 0 && $rollCount3 > 0 && $rollCount4 > 0 && $rollCount5 > 0 && $rollCount6 > 0) {
    $roll = rand(1,6);
        if ($roll == 1) {
            echo "<div class=\"dice\">$roll</div>";
            $rollCount1 ++;
        }
        if ($roll == 2) {
            echo "<div class=\"dice\">$roll</div>";
            $rollCount2 ++;
        }
        if ($roll == 3) {
            echo "<div class=\"dice\">$roll</div>";
            $rollCount3 ++;
        }
        if ($roll == 4) {
            echo "<div class=\"dice\">$roll</div>";
            $rollCount4 ++;
        }
        if ($roll == 5) {
            echo "<div class=\"dice\">$roll</div>";
            $rollCount5 ++;
        }
        if ($roll == 6) {
            echo "<div class=\"dice\">$roll</div>";
            $rollCount6 ++;
        }
}

My attempt of the "for"-loop:

for ($rollCount1 = 0, $rollCount2 = 0, $rollCount3 = 0, $rollCount4 = 0, $rollCount5 = 0, $rollCount6 = 0; $rollCount1 > 0, $rollCount2 > 0, $rollCount3 > 0, $rollCount4 > 0, $rollCount5 > 0, $rollCount6 > 0; $rollCount1++, $rollCount2++, $rollCount3++, $rollCount4++, $rollCount5++, $rollCount6++, $roll = rand(1,6), echo ("$roll"))

When I tried a "array-version", I used

array_rand ($diceSides, $roll);

instead of

$roll = rand(1,6);

but none of them worked.

Foi útil?

Solução

Count the number of times you rolled a specific number in a separate array, and exit the loop when it doesn't contain any zeroes any more:

$results = array_fill(1, 6, 0);   // Prepare counter array
do {
    $roll = rand(1,6);            // Random number
    echo "Rolled a $roll...\n";
    $results[$roll]++;            // Count the results
} while(in_array(0, $results));   // Check whether there are still unthrowns

Sample here.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top