To start with, let's look at the solution to last weeks homework. How do we change the direction of the character on screen, and test when he leaves the left side of the screen?
This week, we learn more about variables, constants, and different data types (strings and numbers).
Finally this week, we get interactive, meaning we change the game so a human can interact with what's happening on screen using the keyboard.
Today's episode, on YouTube
In last weeks episode the character moved to the right of the screen and died when it reached the right wall. We did that by increasing the value of playerLeft, then comparing it (>=) to 600.
To make the character run in the opposite direction we need to reduce playerLeft. Next, we need to change that comparison. We don't need to check for 600 any more, we need to check for zero, as that means we've hit the left edge of the window.
When writing code you often find yourself checking a variable against a limit, or changing a variable by a set amount over and over, just like we already have.
Up to now when we've done that we've used the number directly in the code (such as comparing our position with the wall - 600). You may have noticed we've needed to copy that value to several places in the code. What would happen if we wanted to move that wall? We'd need to find every 600 (and the occasional 300) and change each and every one of them.
This week, let's figure out a cleaner way to define constants, so we can make our lives easier in the future. It may seem like more work for today, but trust me: in the long run, we're saving time.
Well, in episode 001 we made a picture. In episode 002 we added movement and made it a movie. This week, we're changing that movie into something interactive. That is, afterall, the main difference between a game and a movie - you interact with a game, you can only watch a movie.
Let's make a start by listening for the keyboard event keydown.
Events work a little bit like the setTimeout() function we saw before. As with setTimeout(), events require a callback function, which you implement, to do work sometime later. The difference however, is that an event handler is called at some unknown time in the future, as a result of the browser firing an event in response to some action.
Things that typically are detected by events are:
This week, to deal with the user pressing a button on the keyboard, we will use the function window.addEventListener(), in conjunction with the keydown event.
This weeks code only checks that the user pressed something, but we don't know what. For homework, look at the data passed in the keydown event, to identify which key was actually pressed.
Adapt the code we've already written so you can control the direction that the character runs. Use "Z" for left and "X" for right. Or if you're fealing really brave, maybe you can figure out how to use the arrow keys instead - however, "Z" and "X" are easier!