我正在创建一个玩家 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';
}
?>
我不知道我的代码是否正确,但这是基于我的理解,任何改进它的想法都会对我有很大帮助。