Er.......

Place for questions and answers for all newcomers and new coders. This is a free for all forum, no question is too stupid and to noob.
Post Reply
User avatar
Xaos
Posts: 940
Joined: Wed Jan 11, 2012 4:01 am

Er.......

Post by Xaos »

So I'm just trying to create a basic fight engine, a simple game where people input attributes of two gladiators and they duel it out. The only problem I've encountered is trying to get it to run until someone has died. IE I want the battle to continue until the last drop of blood has been shed ! But.......how? :D I tried a while loop, but you cannot re-call functions in PHP.

Code: Select all

<?php

$p1attack = $_POST['p1attack'];
$p2defense= $_POST['p2defense'];
$p2elusiveness=$_POST['p2elusiveness'];
$p1dexterity=$_POST['p1dexterity'];
$p1health=$_POST['p1health'];
$p1speed=$_POST['p1speed'];
$p2speed=$_POST['p2speed'];
$p2attack = $_POST['p2attack'];
$p1defense = $_POST['p1defense'];
$p1elusiveness = $_POST['p1elusiveness'];
$p2dexterity = $_POST['p2dexterity'];
$p2health=$_POST['p2health'];

while($p1health || $p2health > 0){
function fight($attack,$defense,$elusiveness,$dexterity,$health){
$hitchance = rand(1,$dexterity)-rand(1,$elusiveness);
if($hitchance >= rand(1,$elusiveness)){
echo "Hit! <br />";
$damage = ($attack * rand(1,$attack))-($defense * rand(1,$defense));
if($damage >= 0){
$health = $health - $damage;
echo "Damage dealt = $damage <br />"   ;
echo "Health = $health <br />"   ;
}else{
  echo "Attack paried!<br />"   ;
}
if($health <= 0){
echo "You're Dead! " ;
}
}else{
  echo "Miss!";
}
}
  $p1speedchance = (($p1speed + $p1elusiveness)/2) * rand(1,100);
  $p2speedchance = (($p2speed + $p2elusiveness)/2) * rand(1,100);

}if($p2health <= 0){
  echo "Player Two has died.";
}elseif($p2health <= 0){
  echo "Player One has died.";
}
if($p1speedchance > $p2speedchance){
echo "Player one goes for the attack! <br />";
fight($p1attack,$p2defense,$p2elusiveness,$p1dexterity,$p2health);
}else{
  echo "Player two goes for the attack! <br />";
  fight($p2attack,$p1defense,$p1elusiveness,$p2dexterity,$p1health);
}

?>
User avatar
MikeD
Posts: 294
Joined: Thu Sep 08, 2011 4:28 am

Re: Er.......

Post by MikeD »

If you have the function fight inside of the while loop, it will try to create that function everytime. Simple solution is to just move the function declaration outside of the loop. And call it inside of the loop.
User avatar
Xaos
Posts: 940
Joined: Wed Jan 11, 2012 4:01 am

Re: Er.......

Post by Xaos »

Gotcha, makes sense.
Post Reply

Return to “Beginner Help and Support”