Showing posts with label loops. Show all posts
Showing posts with label loops. Show all posts

Monday, May 20, 2013

J.S. Project: Dragon Slayer



We'll be combining while loops with some other control statements (like if / else statements) to create a dragon slaying minigame.

01 / 04 : Let's first start off by declaring the variables which we'll be using. We're going to need a variable to check if we're still slaying, a variable to check if we hit the dragon, a variable to keep track of how much damage we've dealt the dragon this round, and a variable to keep track of total damage. We'll also be relying on random numbers to see if we hit the dragon, and if so, how much damage we did. JavaScript generates random numbers like this:
    var randomNumber = Math.random();
This creates a random number between 0 and 1. By multiplying the number and rounding it down, we can make it a random whole number. For example:
    Math.floor(Math.random() * 5 + 1);
will generate a random number between 1 and 5 inclusive. Now let's declare and set the following variables:
    1. slaying equal to true
    2. youHit to a random number that's either 0 (which JavaScript reads as 'false') or 1 {which JavaScript reads as 'true')
    3. damageThisRound to a random number between 1 and 5 (inclusive)
    4. totalDamage to 0
    HINT - by multiplying the random number (which is between 0 and 1) by 5, we make it a random number between 0 and 5 (for example, 3.1841). Math.floor() rounds this number down to a whole number, and adding 1 and the end changes the range from between 0 and 4 to between 1 and 5 (up to and including 5).

var slaying = true;
var youHit = Math.random();
var damageThisRound = Math.floor(Math.random() * 5 + 1);
var totalDamage = 0;

02 / 04 : Wonderful. Now let's add in our while loop. We want to run this whole game as long as we're trying to kill the dragon--that is, while slaying is true. When checking variables like slaying that are set to true, we don't need to write something like this:
    while(slaying === true)
Instead, we can just write:
    while(slaying)
Now let's create a while loop that only executes when slaying is true. For this exercise, set slaying to false in the body of the loop (we want to make sure the loop can exit... no infinite loops for us!) 

var slaying = true;
while(slaying) {
    slaying = false;
}

03 / 04 : Now time to add a couple of branches to our program so it can handle different outcomes. You know what this means... if and else! Inside the while loop, create an if / else statement that checks the value of youHit. If it's 1 (true), it should log a congratulatory message to the console, telling the user (s)he hit the dragon. If it's 0 (false), it should log a message to the console saying that the dragon defeated you. Either way, slaying should be set to false, since either you beat the dragon (and the slaying's over) or the dragon beat you!

while(slaying) {
    if (youHit) {
        console.log("You hit!");
    } else {
        console.log("You missed!");
    }
    slaying = false;
}

04 / 04 : We're gonna add the second 'if' statement. In the first branch of our if statement (right after the console.log() where we congratulate the player for hitting the dragon), let's set totalDamage equal to totalDamage + damageThisRound. The shortcut for this is: the += operator. When you type
    totalDamage += damageThisRound 
you're telling JavaScript to add totalDamage and damageThisRound together, then assign the new value to totalDamage. Inside the first if statement, create a second if statement that checks to see if totalDamage is greater than or equal to 4. If so, it should log to the console that the player slew the dragon and set slaying equal to false (since the dragon's dead, the slaying is over). If totalDamage isn't greater than or equal to 4, youHit should be assigned a new random 1 or 0. (This is as easy as setting youHit to the same expression you used when you first declared it.)


while(slaying) {
    if (youHit) {
        console.log("You hit!");
        totalDamage += damageThisRound;
            if ( totalDamage >= 4) {
                console.log("You win!");
                slaying = false; 
            } else { 
                youHit = Math.floor(Math.random()*2);
            }
    } else {
        console.log("You missed!");
        slaying = false;
    }
}


You did it! You've written your own dragon slaying game!

Thursday, April 18, 2013

Javascript: Combining Objects with Arrays, Loops, and Functions


a slice of coconut cake @ souen

Objects are just another type--like a string or number, but a bit more complex. So just as we can make arrays of strings and numbers, we can also makes arrays of objects:

// here, we have a person constructor:
function Person (name, age) {
    this.name = name;
    this.age = age;
};

// now we can make an array of people:
var family = new Array();
family[0] = new Person("jenny", 18);
family[1] = new Person("alex", 13);
family[2] = new Person("mom", 51);
family[3] = new Person("dad", 49);

Arrays filled with objects will work just like arrays filled with numbers and strings. In the same we we can loop through an array of numbers to print them out or to calculate a sum, we can loop through an array of objects and access properties or methods:

// loop through our new array and print out the name of each family member:
for (i = 0; i < family.length; i++ )
{console.log(family[i].name)
};

We can also use objects as parameters for functions as well. That way, we can take advantage of the methods and properties that a certain object type provides. In addition to our Person constructor, we have also introduced a new function, ageDifference. This function takes two Person objects as parameters and returns the difference in age between the two people:

// create var ageDifference
var ageDifference = function(person1, person2) {
    return person1.age - person2.age;
};

// create multiple example people
var jenny = new Person("Jenny", 18);
var alex = new Person("Alex", 13);

// create new variable diff
var diff = ageDifference(jenny, alex);