开发者

PHP Game weapon accuracy

I'm trying to come up with a way for players to fire their weapons and only hit for a certain percentage.开发者_运维技巧 For example, one gun can only hit 70% of the time while another only hits 34% of the time.

So far all I could come up with is weighted arrays.

Attempt 1:

private function weighted_random(&$weight)
    {
        $weights = array(($weight/100), (100-$weight)/100);
        $r = mt_rand(1,1000);
        $offset = 0;
        foreach($weights as $k => $w)
        {
            $offset += $w*1000;
            if($r <= $offset)
                return $k;
        }
    }

Attempt 2:

private function weapon_fired(&$weight)
    {
        $hit = array();
        for($i = 0; $i < $weight; $i++)
            $hit[] = true;
        for($i = $weight; $i < 100; $i++)
            $hit[] = false;
        shuffle($hit);
        return $hit[mt_rand(0,100)];
    }

It doesn't seem that the players are hitting the correct percentages but I'm not really sure why.

Any ideas or suggestions? Is anything glaringly wrong with these?

Thanks


private function weapon_fired($weight)
    {
        return mt_rand(0, 99) < $weight;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜