Dax
Dax

Reputation: 827

Calculating a winner, depending on win chance of each player

My Goal: Each player has an option to place a bet, and for each player the winning chance of their bet would be calculated and displayed on the web page. So as an example if player 1 bets 5000 credits and the total pot is 15000 credits, player 1 has a 33% chance to win. After this calculation I would like to pick a winner from all the players that placed a bet.

Example game:

How should I approach the way of picking a random winner from all the players? I was thinking of generating one random number and comparing it to the win chance somehow. Any tips?

Upvotes: 3

Views: 1266

Answers (1)

Attersson
Attersson

Reputation: 4866

Percentage does not always work due to rounding errors. For instance betting 1 when the total pot is 1000 yields 0% chance.

I recommend drawing a random number in range [0,tototalAmount)

// player 1 bets 1500, player 2 bets 2300, player 3 bets 4000
    let bets = [1500,2300,4000];
    bets.forEach((e,i)=>bets[i]=(i==0)?e:e+bets[i-1]);
    //now bets is [1500,3800,7800]
    console.log(bets);

    let maxDraw = bets[bets.length-1];   

    //Draw
    let drawnNumber = Math.floor( Math.random() * (maxDraw) );
    
    // drawnNumber is in range 0~7799
    //so if the drawn number is in ranges:
    // 0~1499      : player 1 wins. odds are 1500/7800
    // 1500~3799   : player 2 wins 2300/7800
    // 3800 7799   : player 3 wins 4000/7800
    
    console.log("drawn number =",drawnNumber);

    // remember the above are checked in order.
    let winner = 0;
    bets.forEach((e,i)=>{
        if(!winner && drawnNumber<=bets[i])
            winner = i+1;
    });
    console.log("player",winner,"wins");

This keeps rates 100% proportional.

Upvotes: 2

Related Questions