0

我正在创建一个玩家 1 与玩家 2 的简单系统,如果完成了 30 轮并且两个玩家都还活着,则系统仅限制到 30 轮,则称为平局。如果玩家 1 在 30 轮之前得到 0 或小于 0 并且玩家 2 还活着,那么玩家 2 赢得比赛等等......

问题是为什么我仍然有负值我的代码有什么问题?我已经在那里设置了一个 if 语句。任何想法都会对我有很大帮助,因为我仍然是初学者,所以我愿意改进,谢谢。

<?php 

        //Player 1
        $p1Health = 100;
        $p1Attack = 5;
        $p1Speed = 3;

        //Player 2
        $p2Health = 70;
        $p2Attack = 8;
        $p2Speed = 5;

        //Greater speed attack first
        $speed1=0;
        $speed2=0;

        echo '<td>'.$p1Health.'</td><td>'.$p1Attack.'</td><td>'.$p1Speed.'</td>';

        echo '<td>'.$p2Health.'</td><td>'.$p2Attack.'</td><td>'.$p2Speed.'</td>';

        //Compare speed
        if($p1Speed<$p2Speed){
            $speed1=1; //start first
            $speed2=0;
        }
        else {
            $speed1=0; //start first
            $speed2=1;
        }

        $rounds = 30; //maximum rounds
        $count = 0;

        while($count<=30){

            if($p1Health<=0 || $p2Health<=0){ //if any of the players health is equal or below zero loop stop and declare winner

                break;

            }
            else if($speed1==1){

                $p2Health = $p2Health - $p1Attack;

                echo 'Player 2 damaged by '.$p1Attack.' points.Health points left: '.$p2Health.'<br>'; 

                //turn to other player to attack
                $speed1=0;
                $speed2=1;

            }
            else if($speed2==1){

                $p1Health = $p1Health - $p2Attack;

                echo 'Player 1 damaged by '.$p2Attack.' points.Health points left: '.$p1Health.'<br>';

                //turn to other player to attack
                $speed1=1;
                $speed2=0;

            }

            $count++;
        }

        if($p1Health>0 && $p2Health<=0){

            echo 'Player 1 wins the battle';

        }
        else if($p2Health>0 && $p1Health<=0){

            echo 'Player 2 wins the battle';

        }
        else if($p1Health>0 && $p2Health>0){

            echo 'Battle draw';

        }

    ?>

我不知道我的代码是否正确,但这是基于我的理解,任何改进它的想法都会对我有很大帮助。

4

2 回答 2

3

Player 1 starts with 100 health. After each attack from player 2, that goes down by 8. After the 12th attack, player 1 will have 4 health. On the 13th attack, that value is reduced by another 8, yielding −4.

You'll see this phenomenon any time one player's attack strength doesn't evenly divide the other's health.

If you don't want the value to go below zero, even after an attack, then check for that and fix it:

$p1Health = $p1Health - $p2Attack;
if ($p1Health < 0)
  $p1Health = 0;
于 2012-09-11T16:47:36.477 回答
0

这是因为在循环的第 20 次执行中,这些值仍然可能为负数。循环仍将再次执行到第 21 次迭代,您的 if 条件将中断。

您可以考虑在 while 条件下使用健康值,例如:

while ($count < $rounds && p1Health > 0 && p2Health > 0) {

然后消除循环中检查健康值的第一个条件。

于 2012-09-11T16:51:39.853 回答