Sunday, June 8, 2014

Getting Loopy.

The biggest problems with loops is that if you write them wrong, they never stop, crashing the browser. I've done this a lot lately. As in almost every exercise. The syntax of the do/while and for loops is confusing. I've had some exercises where I can't figure out what to write, and I feel like sometimes I haven't been taught how to write the code properly, even though other people understand how to do it. Hopefully it gets hammered into my head while I write the Dragon Slayer game that's up next in my lessons.
var slaying = true;
var youHit = Math.floor(Math.random() * 2);
var damageThisRound = Math.floor(Math.random()*5 + 1);
var totalDamage = 0;
while(slaying){
    slaying = false;
    if(youHit) {
        console.log("Congratulations, you hit the dragon!");
        totalDamage += damageThisRound;
        
        if(totalDamage >= 4) {
            console.log("You slew the dragon!");
            slaying = false;
        } else {
            youHit = Math.floor(Math.random() * 2);
        }
    }else {
        console.log("You have died.");
        slaying = false;
    }

}
This one was a fun exercise. It uses a random number generator (Math.random) that is rounded to the nearest whole number (Math.floor) to determine total damage to a dragon. If you miss once, you lose, since dragons are super powerful. Take a look at it here with a browser's console.
There's no real interactive elements yet, but I think that's something that's more complicated, so they haven't touched on how to really do it yet. I'll keep learning more JavaScript and being able to do cooler and cooler things.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home