dimanche 6 janvier 2019

PHP Three Random Winner Based on Chance

I created a roll system that will choose a 3 random winner based chance.

My code is this

function chance($input=array())
{
    echo 'The Max Value can be: '.(array_sum($input)*10).'<br>';
    $number=rand(0,array_sum($input)*10);
    echo 'Checking for: '.$number.'<br>';
    $starter=0;
    foreach($input as $key => $val)
    {
        $starter+=$val*10;
        echo 'Current value being tested against is: '.$starter.' which is '.$key.'<br>';
        if($number<=$starter)
        {
            $ret=$key;
            break;
        }

    }

    return 'Winner is '.$ret.'';
}

$array=array('black' => 15.30, 'brown' => 20.20, 'kitty' => 15.30, 'lala' => 15.20, 'popi' => 14.00, 'usher' => 20.00);

for($i=0;$i<3;$i++)
{
    echo chance($array).'<br><br>';
}

it will create an output like this one

The Max Value can be: 1000
Checking for: 797
Current value being tested against is: 153 which is black
Current value being tested against is: 355 which is brown
Current value being tested against is: 508 which is kitty
Current value being tested against is: 660 which is lala
Current value being tested against is: 800 which is popi
Winner is popi

The Max Value can be: 1000
Checking for: 219
Current value being tested against is: 153 which is black
Current value being tested against is: 355 which is brown
Winner is brown

The Max Value can be: 1000
Checking for: 709
Current value being tested against is: 153 which is black
Current value being tested against is: 355 which is brown
Current value being tested against is: 508 which is kitty
Current value being tested against is: 660 which is lala
Current value being tested against is: 800 which is popi
Winner is popi

The code works perfect, But there is some error in winners. POPI win twice in that case. What I want is to get 3 random winner without repeat the previous winner.

for example, if user POPI already win in first roll, she cannot win again in the next roll. So the user cannot win twice in a roll.

Aucun commentaire:

Enregistrer un commentaire