Page 1 of 1

Er.......

Posted: Sat Jun 15, 2013 7:19 pm
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);
}

?>

Re: Er.......

Posted: Sat Jun 15, 2013 10:38 pm
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.

Re: Er.......

Posted: Sat Jun 15, 2013 10:43 pm
by Xaos
Gotcha, makes sense.