Jump to content

While Loop Question


KillZoneZ
Go to solution Solved by Barand,

Recommended Posts

So, today i decided i would start learning PHP, i just learned how to do while loops and i wanted to get a bit out of the comfort zone of what the tutorials i've seen gave me.

 

So i decided to create a quick "interaction" where the player receives a random amount of damage from a monster, in this case a zombie, and then displays the damage received and the current health after the damage has been taken.

 

This is what i have:
   

<?php
        $LostHealth = rand(1,10);
        $Health = 100;
        if ($Health == 0) {
            echo "You are dead.";
        }
        else {
            echo "You turn around and there is a zombie coming in your direction";
            while ($Health > 0) {
                $Health = $Health - $LostHealth;
                echo "<p>A Zombie just hit you doing <strong>$LostHealth</strong> damage!</p>";
                echo "<p>You now have $Health HP</p>";
            }
        }
    ?>

However, the $LostHealth is always a fixed number everytime it loops.

 

Thanks for the help and time

Edited by KillZoneZ
Link to comment
Share on other sites

  • Solution

You need to set the random value inside the loop, not just once.

while ($Health > 0) {
                $LostHealth = rand(1,10);
                $Health = $Health - $LostHealth;
                echo "<p>A Zombie just hit you doing <strong>$LostHealth</strong> damage!</p>";
                echo "<p>You now have $Health HP</p>";
}
Edited by Barand
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.