0
class Gunner {

    public $health;
    public $attack;

    function __construct($health, $attack) {
        $this->health = $health;
        $this->attack = $attack;
    }
}

$player = array();
$player[] = new Gunner(100, 20);
$player[] = new Gunner(100, 20);
$player[] = new Gunner(100, 20);

$enemy = array();
$enemy[] = new Gunner(100, 20);
$enemy[] = new Gunner(100, 20);

只要两个数组都具有“实体”/对象,我就希望有一些循环运行。我怎么做?我想和每一个实体战斗,就像 $player[0] 会战斗(又名 rand(1,20))然后从对立面的生命值中移除直到它为 0。当它的值为 0 或更少时,我会移除数组中的实体(对象)。

我不确定 while 循环或从数组中删除的样子。

while ((count($attacker) > 0) && (count($defender) > 0))
{
    $attacker_attack = rand(1, 25);

    $defender[0]->health -= $attacker_attack;

    if (!$defender[0]->IsAlive()) {
        unset($defender[0]);
        array_values($defender);
    }

    $defender_attack = rand(1, 20);

    $attacker[0]->health -= $defender_attack;

    if (!$attacker[0]->IsAlive()) {
        unset($attacker[0]);
        array_values($attacker);
    }
}
4

1 回答 1

2

你的意思是这样的(演示)?

class Gunner
{
    public $health;
    public $attack;

    public function __construct($health, $attack)
    {
        $this->health = $health;
        $this->attack = $attack;
    }
}

$attacker = array
(
    new Gunner(100, 20),
    new Gunner(100, 20),
    new Gunner(100, 20),
);

$defender = array
(
    new Gunner(100, 30),
    new Gunner(100, 30),
);

while ((count($attacker) > 0) && (count($defender) > 0)) // fight till death!
{
    $defender[0]->health -= $attacker[0]->attack;

    if ($defender[0]->health <= 0) // defender dead?
    {
        unset($defender[0]); $defender = array_values($defender);
    }

    if (count($defender) > 0) // are any def alive for counter-attack?
    {
        $attacker[0]->health -= $defender[0]->attack;

        if ($attacker[0]->health <= 0) // attacker dead?
        {
            unset($attacker[0]); $attacker = array_values($attacker);
        }
    }
}

print_r($attacker);
print_r($defender);

PS:我更新了代码以反映您的最后评论,有点不清楚应该如何进行回合。

于 2012-05-13T10:25:34.743 回答