I am creating a PLayer 1 vs Player 2 simple system and the system limit only till 30 rounds if 30 rounds is done and both player are still alive then it is called a draw. If player 1 gets 0 or less than 0 before 30 rounds and player 2 is still alive then player 2 wins the games and etc…
Problem is why I am still having negative values whats wrong with my code? I already set an if statement in there. Any idea will be a big help for me and I am open for improvements since I am still a beginner programmer THANK YOU.
<?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';
}
?>
I don’t know if my code is right but this is based for my understanding any idea to improve this will be really a big help for me.
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: