If you're seeing this message, it means we're having trouble loading external resources for Khan Academy.

If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

Let's start by making our character, the hopping beaver. We'll use object-oriented design, discussed in this tutorial, to describe our Beaver character.

When creating a game character, we should think about what properties and behaviors it should have. For example, our beaver should keep track of her x and y position and how many sticks she has collected. She also needs two behaviors: hop, which makes her jump a little bit up, and fall, which makes her fall a bit down.

Here's what that could look like, as an object:

That program doesn't do a very good job at checking the different behaviors, though - it's not animated, so we can only see her in one state of being. Let's add a draw function, so that we can tell the beaver to do different things depending on user interaction. For this game, we want the beaver to hop whenever the user is pressing the space key. That can be implemented pretty simply:

draw = function() {
    background(255, 255, 255);
    if (keyIsPressed && keyCode === 0) {
        beaver.hop();
    } else {
        beaver.fall();
    }
    beaver.draw();
};

That's pretty effective code, but if we ran it, we'd have to continuously press our space bar to keep the beaver from hopping off the face of the canvas forever, never to return. We should constrain the y values to some reasonable value, to keep the beaver in screen. That's common in games, to keep characters inside the "game world." We could do that by using constrain in the draw function, passing it an appropriate min and max:

 this.y = constrain(this.y, 0, height-50);

Now, here's our program, with a keyboard-controlled hopping and falling beaver. Play around with it a bit!