Move!

Background

The Game Loop

What makes games fun is that they’re interactive; users can move characters by pressing buttons on a keyboard or controller. In order to get user input, we need to wait for that input. After all, when playing a classic game like Super Mario Bros., Mario will just stand there until the player decides to move him!

Mario Being Still

Wait for it…

But how do we accomplish making games coninusously interactive? Enter the idea of the game loop!

The game loop is a special loop that runs the entire time that the game is being played. In Scratch, it’s a forever loop like the one below:

Scratch Forever Loop

A Scratch Foever Loop

If interested, other text-based languages like Python (below) can too make forever or while True loops as such:

while True:
    # Stuff to do over and over again

No need to worry about the syntax of Python above if unfamilar. The point is, regardless of the language, the logic inside of this game loop remains the same! Typically logic for things like counting points, user input, character movement, collision detection, and determining a winner go inside this loop. The reason for these things existing in the game loop is that we want to continuously do these tasks until the game ends.

Perhaps the simplest functionality that we want to put in a game loop is movement. So, lets make a simple game where we can move a sprite around the screen!

Recall that if I want to move a sprite to the right in scratch, I may use code like the following:

Scratch Move Right

Moving right in Scratch using steps

This makes the sprite move 10 steps in whatever direction it’s facing. Alternatively, it may be better to think of things more like a coordinate plan where x is the horizontal position and y is the vertical position. Then you could do something like this:

Scratch Move Right

Moving right in Scratch using coordinates

Now to do the same for other directions!

Your Mission

Using the Scratch distrubition code, let’s make a Scratch program where you can move the main cat sprite in any direction using the directional keys! Let’s also make sure that the cat isn’t able to leave the screen.

A screenshot of the distribution code is below:

Scratch Distro

Moves right unless at edge of screen (x = 190 is right edge)