PHP Game weapon accuracy

Posted by noko on Stack Overflow See other posts from Stack Overflow or by noko
Published on 2010-05-06T03:11:51Z Indexed on 2010/05/06 3:18 UTC
Read the original article Hit count: 205

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

© Stack Overflow or respective owner

Related posts about php

Related posts about pseudo-random-numbers