Hardware Reference
In-Depth Information
Example 3: A Simple Game
Using Scratch for simple animation is one thing, but the software also allows users to read
inputs from the keyboard to introduce interactivity. By combining some simple animation
controls to the previously described program, you can create a simple game—and, at the
same time, introduce the concepts of sprite collision, if statements and input.
For this example, start a new Scratch project—remembering to save the previous example, if
you haven't already done so—and begin by dragging a move 10 steps block to the Scripts
area. This time, rather than telling the code blocks to execute when the flag icon is clicked, go
to the Control block palette and drag a when space key pressed block above the move
block.
As the name suggests, the when space key pressed block looks for input from the
user—in this instance, the spacebar being pressed—and uses that as the trigger for execut-
ing a list of blocks. The block works at any time—if you press the spacebar now, the sprite
will obey its instructions and move 10 steps to the right.
he when space key pressed block also differs from the when [flag icon] clicked
block in another important way: it can be customised. Click the down-arrow button next to
the word space to see a list of all the keys the block can watch, and then select right
arrow from the list to change the block into a when right arrow key pressed block.
A game in which the player can move in only one direction isn't much fun, so drag a new
when space key pressed block into the Scripts area. This can't link to the existing block
list—you can only have a single trigger block—so start a new list somewhere further down.
As before, use the down-arrow button next to the word space to customise the block, turn-
ing it into a when left arrow key pressed block. Finally, switch the block palette back
to Motion mode and connect a move 10 steps block beneath the new when left arrow
key pressed block before changing it to read move -10 steps .
If you press the left and right arrow keys now, you'll see that the cat moves according to your
input (see Figure 11-7): pressing the left arrow moves the cat 10 steps to the left (although,
as far as Scratch is concerned, it's moving minus 10 steps to the right), and pressing the right
arrow moves the cat 10 steps to the right.
Now that the sprite can be moved by the player, it's time to give the sprite something to do.
As this is just a very simple game, the goal should also be simple: to collect some food. Click
the Choose New Sprite From File button, found in the middle of the three buttons above the
Sprite palette at the bottom-right of the Scratch window.
Search WWH ::




Custom Search