PHP游戏概率方法

时间:2023-03-08 20:38:57
<?php

 function createRandomKey($randArr, $rateKey){
$total = 0;
$chooseArr = array();
$pow = 0;     
//比如array( array('id' => 1, 'rate' => 40.99), array('id' => 2, 'rate' => 59.01));
/* foreach($randArr as $k => $v){      
$tmp = explode('.', strval($v[$rateKey]));
if($tmp[1] && strlen($tmp[1]) > $pow){
$pow = strlen($tmp[1]);
}
}*/
$r = pow(10, $pow);
foreach($randArr as $key => $value){
$total = $total + $value[$rateKey] * $r;
$chooseArr[$key] = $total;
};
$rand = rand(1, $total);
$bofore = 0;
foreach ($chooseArr as $k => $v){
$v = $v * $r;
if($rand > $bofore && $rand <= $v){
$chooseIndex = $k;
break;
}
$bofore = $v;
}
return $chooseIndex;
} $randArr = [
0 => ['point' => 15,'rate' => 0],
1 => ['point' => 5,'rate' => 0],
2 => ['point' => 10,'rate' => 0],
3 => ['point' => 11,'rate' => 0],
4 => ['point' => 13,'rate' => 10],
5 => ['point' => 20,'rate' => 80],
6 => ['point' => 50,'rate' => 0],
7 => ['point' => 80,'rate' => 0],
8 => ['point' => 10,'rate' => 0],
9 => ['point' => 60,'rate' => 10], ]; $a = createRandomKey($randArr,$rate = 'rate');
var_dump($a);
var_dump($randArr[$a]['point']);

  

PHP游戏概率方法