How to Make a Basic While Loop in Your HTML5 Game

By Andy Harris

for loops are useful when you know how often a loop will continue in your HTML5 game, but sometimes you need more flexibility. The while loop is based on a simple idea. It contains a condition. When the condition is true, the loop continues; if the condition is evaluated as false, the loop exits.

The program asks for a password and keeps asking until the user enters the correct password.

image0.jpg

 function getPassword(){
  //from while.html
  var correct = "HTML5";
  var guess = ";
  while (guess != correct){
  guess = prompt("Password?");
  } // end while
  alert("You may proceed");
 } // end getPassword

A while loop for passwords is not hard to build:

  1. Store the correct password in a variable.

    Variable names are important because they can make your code easier to follow. This uses the names correct and guess to differentiate the two types of passwords. Beginners often call one of these variables password, but that can be confusing because there are actually two passwords (the correct password and the guessed password) in play here.

  2. Initialize the guess to an empty value.

    The key variable for this loop will be guess. It starts as an empty string. It’s critical to initialize the key variable before the loop begins.

  3. Set up the while statement.

    The while statement has extremely simple syntax: the keyword while followed by a condition, followed by a block of code.

  4. Build the condition.

    The condition is the heart of a while loop. The condition must be constructed so the loop happens at least once (ensure this by comparing the condition to the variable initialization). When the condition is true, the loop continues. When the condition is evaluated to false, the loop exits. This condition compares guess to correct. If guess is not equal to correct, the code continues.

  5. Write the code block.

    Use braces and indentation to indicate the block of code that will be repeated in the loop. The only code in this particular loop asks the user for a password.

  6. Add code to change the key variable inside the loop.

    Somewhere inside the loop, you need code that changes the value of the key variable. In this example, the prompt statement changes the password. As long as the user eventually gets the right password, the loop ends.