由于舍入错误,百分比并不总是有效。例如,当总赌注为1000时,下注1的几率为0%。
我建议画一个范围[0,totalamount]内的随机数。
// 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");
这使利率保持100%的比例。