在+ array + objects时模拟攻击

时间:2012-05-13 10:09:45

标签: php

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);

只要两个数组都有“实体”/对象,我想要有一些while循环。我怎么做? 我想对每一个实体进行战斗,比如$ player [0]会战斗(也就是做兰特(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);
    }
}

1 个答案:

答案 0 :(得分:2)

你的意思是这样的(demo)?

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:我更新了代码以反映您的上一条评论,有点不清楚应该如何播放。