Mini-Lab: If-Else Statements


Introduction

The goal of today's Mini-Lab is to improve your puzzle with a counter that keeps track of the number of moves that have been made. If the player makes too many moves without completing the puzzle, they lose.

Make sure that you have finished the previous Mini-Lab before you get started on this one.


Exercises:

  1. Adding a Counter: The first step is to add a new variable to your JavaScript program to keep track of number of moves that the player has left. Like the currentBlank variable you created earlier, this variable should be created inside your <script> section but outside any of your existing JavaScript functions. (Variables created inside a function only exist while that function is executing, and can only be accessed in that function. Variables that are created outside of any function exist indefinitely, and can be accessed from any JavaScript functions in the page.)
  2. Initializing the Counter: Your new counter variable should be given an initial value of 20 (this is called initializing the variable). You can initialize it in the same line where you first declare it with the var keyword, or in a separate line immediately after, or, if you have an initializeGlobalVars function, you can initialize it there. You do not want to set it to 20 in the swapWithBlank function, though, or it will be reset to 20 every time the user clicks on a picture.
  3. Updating the Counter: The next step is to modify your swapWithBlank function so that it updates your counter variable every time it is called, and informs the player when too many moves have been made:
    function swapWithBlank(imageToSwap) 
    {
       
    // DON'T REMOVE YOUR PREVIOUS CODE! // ADD NEW CODE TO: // 1. Decrease the counter variable by 1. // 2. Pop up an alert box if the counter variable is less than or equal to 0.
    }
    There are three ways to decrement a variable. If you have a variable called myVar, you could do any of the following:
        myVar = myVar - 1;
        myVar -= 1;
        myVar --;
    
    You choose! Then test your page to make sure that it works as expected.
  4. Extras (If You Have Time):    (otherwise go straight to step 4)
  5. Finishing Up: Before publishing your page to the web server, add comments to your JavaScript containing the following information (Don't remove your old comments, just add these after them.):