Lesson 11: Conditional Statements
1. Once our monkey image has animated out of the gameWindow, it would be nice to reset it back to the bottom and have it continue animating. You can use a conditional statement to do this.
The if statement here allows us to add some logic. Specifically, if the condition that is in the parenthesis is true (y is less than -100), it will run the command that is after the condition (set the value of y to 350). If the condition is false (y is not less than -100), the command following the condition will not run.
The animation should now repeat over and over.
2. Reset the monkey's horizontal position to a random value every time the monkey's vertical position is reset to the bottom.
Notice now that you are running a block of code when y is less than -100. Using curly braces after the condition allows multiple lines of code to run when the condition is true.
3. Also notice that you are now repeating some lines of code. You are setting the position of monkey_01 in init and again in gameloop, when y is less than -100. To avoid code redundancy, make a function for placing the monkey in gameWindow.
4. Now you can simplify the init function by replacing the redundant code with a function call to placeMonkey().
5. You can also simplify gameloop() by replacing the redundant code with a call to placeMonkey(). Note that you are now using an if/else statement. If y is less than -100, placeMonkey() will be called to reset monkey_01 to a new starting position. However, if y is not less than -100, monkey_01 will be moved up 10 pixels to the new y value.
If/else statements can be read as: If a condition is true do something, otherwise do something else.
6. You may find the code easier to read if you use curly braces for code blocks when using an if/else statement.
Now monkey_01 should repeatedly animate through gameWindow starting from a new location each time.
7. Just as with HTML and CSS, indentation is very important in JavaScript. Proper indentation makes your code more readable for yourself and for others.
Just follow some basic rules:
- Use tabs, not spaces, to indent.
- Indent everything with a block of code from the open curly brace ({) to the close curly brack (}).