he first Super Mario Bros. game was introduced in 1985 and became Nintendo’s greatest video game franchise and one of the most influential games of all time. Because the game involves making a character run, jump, and hop from platform to platform, this game style is called a platformer (or platform game).
In the Scratch game in this chapter, the cat will play the part of Mario or Luigi. The player can make the cat jump around a single level to collect apples while avoiding the crabs who will try to steal them. The game is timed: the player has just 45 seconds to collect as many apples as possible while trying to avoid the crabs!
Get ready to program a more complicated game than those in previous chapters.
Sketch Out the Design
Let’s sketch out on paper what the game should look like. The player controls a cat that jumps around while apples appear randomly. The crabs walk and jump around the platforms randomly, too.
Here’s what we’ll do in each part:
A. Create gravity, falling, and landing
B. Handle steep slopes and walls
C. Make the cat jump high and low
D. Add ceiling detection
E. Use a hitbox for the Cat sprite
F. Add a better walking animation
G. Create the level
H. Add crab enemies and apples
This platform game is the most ambitious one in the book, but anyone can code it if they follow the steps in this chapter. Let’s code each part one step at a time.
If you want to save time, you can start from the skeleton project file, named platformer-skeleton.sb3, in the resources ZIP file. Go to https://www.nostarch.com/scratch3playground/,and download the ZIP file to your computer by right-clicking the link and selecting Save link as or Save target as. Extract all the files from the ZIP file. The skeleton project file has all the sprites already loaded, so you’ll only need to drag the code blocks into each sprite.
Create Gravity, Falling, and Landing
In the first part, we’ll add gravity, falling, and landing code, similar to the Basketball game in Chapter 4. The important difference is that in the platform game, the cat lands when it touches a ground sprite rather than the bottom of the Stage. Coding is a bit trickier, because we want the ground to have hills and eventually platforms!
To start, click the text field at the top left of the Scratch editor and rename the project from Untitled to Platformer.
1. Create the Ground Sprite
Let’s use a simple shape for the ground in the first few scripts, just to explore how the code will work.
Hover over the Choose a Sprite button and click the Paint button to create a temporary ground sprite while you learn about platforming code. In the Paint Editor, use the Brush or Line tool to draw a shape for the ground. You can make the lines thicker by increasing the number in the line width text box at the top of the Paint Editor. Be sure to draw a gentle slope on the right and a steep slope on the left.
In the Sprite Pane, rename the sprite Ground. Also, rename the Sprite1 sprite Cat.
2. Add the Gravity and Landing Code
Now that we have a sprite for the ground, we need the cat to fall and land on it.
Select the Cat sprite. In the orange Variables category, click the Make a Variable button and create a For this sprite only variable named yvelocity. Then add the following code to the Cat sprite:
This code performs two actions in its forever loop: it makes the Cat sprite fall until it touches the Ground sprite 1 and then lifts up the Cat sprite if it is deep in the ground 2.
With these two code sections, the cat will fall down, hit the ground, and then rise if necessary, eventually settling on top of the Ground sprite.
The falling code at 1 subtracts 2 from the yvelocity variable and then moves the Cat sprite’s y position by yvelocity, making the cat fall faster and faster. If you programmed the Basketball game in Chapter 4, the falling code should be familiar.
But the repeatuntil block 2 will loop until the Cat sprite is no longer touching the Ground sprite. (If the cat is still in the air and falling, it will not be touching the ground, so the code in the loop is skipped.) Inside this loop, the yvelocity value is set to 0 so that the Cat sprite stops falling any farther. The changeyby1 block will lift up the Cat sprite a little. The repeatuntilnottouchingGround block continues lifting the sprite until it is no longer sunk into the Ground sprite. This is how the cat stays on top of the ground, no matter what the shape of the Ground sprite is.
3. Make the Cat Walk and Wrap Around the Stage
The cat also needs to walk left and right by use of the WASD keys, so add the following script to the Cat sprite:
This code is straightforward: pressing A points the cat to the left (-90) and moves the x position by -6 (to the left); pressing D makes the cat point to the right and moves the x position by 6 (to the right).
Next, add the following script to make the Cat sprite wrap around to the top if it falls to the bottom of the Stage:
This code is similar to the wrap-around code we wrote in the Asteroid Breaker game in Chapter 6. We’ll write wrap-around code for moving left and right later.
4. Remove the Ground Lift Delay
The big problem with the code right now is that the Cat sprite is lifted from inside the ground to on top of it very slowly. This code needs to run so fast that the player sees the sprite only on top of the ground, not in it.
The pink custom blocks can help us do this. Go to the My Blocks category and click the Make a Block button. Name the block handleground and then check the checkbox next to Run without screen refresh. With this box checked, Scratch will run the code in your custom pink block in Turbo Mode, even if the player didn’t enable Turbo Mode by shift-clicking the green flag. Otherwise, the ground-handling code would be too slow for this game.
The definehandleground block should now appear in the Code Area. Change the code for the Cat sprite to make it use the handleground block. The handleground block goes where the repeatuntilnottouchingGround blocks were, and that loop is moved under definehandleground.
This code works exactly as it did before, but now the handleground block has Run without screen refresh checked, so the loop code runs in Turbo Mode. Lifting the cat now happens instantly, so it looks like the cat never sinks into the ground.
Handle Steep Slopes and Walls
The Ground sprite has hills and slopes that the cat can walk on, and you can change the Ground sprite to pretty much any shape in the Paint Editor. This is a big improvement for the player compared to just walking on the bottom of the Stage, as in the Basketball game. But now the problem is that the Cat sprite can walk up the steep slope on the left as easily as it can walk up the gentle slope on the right. This isn’t very realistic. We want the steep slope to block the cat. To do this, we’ll make a small change to the walking code blocks.
At this point, the sprites are becoming overcrowded with lots of different scripts. So, right-click or long press the Code Area and select Clean up Blocks to reorganize the scripts into neat rows.
5. Add the Steep Slope Code
Now we need to edit the Cat sprite’s walking code and add some new code, too. Instead of simply changing the x position by a particular value, we’ll use a new custom block. Let’s call it walk and give this new custom block an input called steps. An input is somewhat like a variable, but you can only use it in the custom block’s define block.
Click the Make a Block button in the pink My Blocks category to make the walk block. Be sure to click the Add an input number or text button to make the steps input. When we want to call the new walk block, we’ll have to define that input with a number of steps to take. Make sure you check the Run without screen refresh checkbox.
This code also requires you to make a variable for the Cat sprite named groundlift (which should be For this sprite only). We’ll use this new variable to determine whether a slope is too steep for the cat to walk up. This code is a little complicated, but we’ll walk through it step-by-step. For now, make the Cat sprite’s code look like the following:
We want the cat to walk six units, as we did earlier, so we use -6 and 6 in the walking script when we call walk. In the definewalk block, the steps input block is used in the changexby blocks. This makes the code more compact, because we can use the same script for moving the cat to the left (with the walk-6 block) or to the right (with the walk6 block).
The code in the repeatuntil loop uses the groundlift variable to determine whether the slope is a walkable slope or a wall that should block the Cat sprite’s progress. The groundlift variable starts at 0 and changes by 1 each time the repeatuntil loop lifts the Cat sprite’s y position by 1. This loop continues looping until the sprite is no longer touching the ground or groundlift is equal to 8.
If groundlift is less than 8, then the slope isn’t that steep. The sprite can walk up the slope, so the definewalk script doesn’t have to do anything else.
But if groundlift=8, the repeatuntil loop stops looping. This code means “the sprite has been lifted up by 8, but it’s still touching the Ground sprite, so this must be a steep slope.” In that case, we need to undo the lift and the walking movement. The changeyby-8 and changexby-1*steps blocks undo the Cat sprite’s movement. Multiplying the walk input by -1 gives the opposite number of the input and variable.
This code is exactly like the code in the Maze Runner game in Chapter 3 that blocks the player from walking through walls.
Make the Cat Jump High and Low
With the walking code done, let’s add jumping. In the Basketball game, we changed the falling variable to a positive number. This meant that the player jumped the height of that variable’s value each time. But in many platform games, the player can do a short jump by pressing the jump button quickly or can jump higher by holding down the jump button. We want to use high and low jumping in this platform game, so we’ll have to come up with something a little more advanced than the Basketball game’s jumping code.
6. Add the Jumping Code
Let’s first create a For this sprite only variable named inair. This variable will be set to 0 whenever the Cat sprite is on the ground. But inair will start increasing when the Cat sprite is jumping or falling. The larger the inair value is, the longer the cat will have been off the ground and in the air.
Add this script to the Cat sprite:
The forever loop keeps checking whether the W key is being held down. If it is, this will give the Cat sprite a velocity of 14—that is, the Cat sprite will be moving up. But note that there are two conditions for the cat to continue moving up—the player must hold down W and the inair variable must be less than 8.
Let’s edit two of the existing Cat sprite scripts to add the inair variable that limits how high the cat can jump.
When the player first holds down the W key to make the cat jump, the yvelocity variable is set to 14. This makes the code in the forever loop in script 1 change the Cat sprite’s y position by the positive yvelocity, moving it upward. At the start of the jump, the inair variable is increasing but is still less than 8. So if the player continues to hold down the W key, yvelocity keeps getting set to 14 instead of decreasing because of the changeyvelocityby-2 block. This causes the jump to go upward longer than if the player had held down the W key for just one iteration through the loop. But eventually inair will become equal to or greater than 8, so it won’t matter if the W key is pressed. Remember that both conditions—keywpressedandinair<8—must be true for the code inside the ifthen block to run.
At this point, the yvelocity variable will decrease as expected, and the Cat sprite will eventually fall. In script 2, when the cat is on the ground, the inair variable is reset to 0.
Add Ceiling Detection
The cat can walk on the ground, and now walls will stop the cat from moving through them. But if the player bumps the Cat sprite’s head against a platform from below, the Cat sprite will float through it! To solve this problem, we need to make some adjustments to the lifting code to add ceiling detection.
7. Add a Low Platform to the Ground Sprite
Add a short, low platform to the Ground sprite’s costume, as shown in the following figure. Make sure it is high enough for the cat to walk under but low enough that the cat can jump up and touch it.
This platform should be low enough that the cat could hit its head on it. If it can’t, then redraw the platform a bit lower.
8. Add the Ceiling Detection Code
The problem with the code is in the custom handleground block. This code always assumes the Cat sprite is dropping from above and, if the Cat sprite is touching the Ground sprite, it should be lifted above it. The Ground sprite represents any solid part that the cat can’t move through, including ceilings. We need to change the code so that if the Cat sprite is jumping up when it touches the Ground sprite, the cat stops rising because it bumps its head. We know the Cat sprite is moving upward when its yvelocity is greater than 0. So, let’s edit the custom handleground block to add a new Boolean input named movingup.
A Boolean is a true or false value. We use a Boolean input because we need to know whether yvelocity is greater than 0 when the handleground block is first called. This true or false value is stored in the movingup input just like a variable would store it. If we put yvelocity>0 in the ifthen block instead of movingup, then the cat would end up rising above the ceiling instead of bumping against it.
Right-click or long press the definehandleground block and select Edit from the menu.
Click the Add an input boolean button. Name this new input field movingup and then click OK.
This will add a new movingup block that you can drag off the definehandleground block just like you do with blocks from the Block Palette. This movingup block will be used in a new ifthenelse block. Modify the definehandleground block’s code to match this.
If the cat is moving up, the changeyby-1 block makes the cat look like it’s bumping its head. Otherwise, the script behaves as it did previously, raising the cat so it sits above the ground.
Next, we have to edit the handleground call in this script. We’ll add a Boolean condition to determine whether the sprite is moving up, which is yvelocity>0.
The handlegroundyvelocity>0 block sets the movingup input to true if yvelocity is greater than 0 (that is, if the sprite is jumping and moving up). If yvelocity is not greater than 0, then the sprite either is falling down or is still, causing the movingup input to be set to false.
This is how the definehandleground block decides whether it should run changeyby-1 (so the Cat sprite can’t go up through the ceiling) or run changeyby1 (so the Cat sprite is lifted up out of the ground). Either way, if the Cat sprite is touching the Ground sprite (which it is if the code inside the repeatuntilnottouchingGround block is running), the yvelocity variable should be set to 0 so that the Cat sprite stops falling or jumping.
Use a Hitbox for the Cat Sprite
There’s another problem with the game. Because the code relies on the Cat sprite’s touching the Ground sprite, any part of the Cat sprite can be “standing” on the ground, even its whiskers or cheek! In this figure, the cat isn’t falling because its cheek has “landed” on the platform, which isn’t very realistic.
Fortunately, we can fix this problem by using the hitbox concept we used in the Basketball game.
9. Add a Hitbox Costume to the Cat Sprite
Click the Cat sprite’s Costumes tab. Then hover over the Choose a Costume button and click the Paint button that appears. Draw a black rectangle that covers most (but not all) of the area of the other two costumes. The following figure shows a slightly transparent first costume in the same image so you can see how much area the black rectangle covers:
Name this costume hitbox. Whenever the Platformer program’s code checks whether the Cat sprite is touching the Ground sprite, we’ll switch the costume to the black rectangle hitbox costume before the check and then back to the regular costume after the check. By doing so, the hitbox will determine whether the cat is touching the ground.
These costume switches will be handled with the pink custom blocks that have the option Run without screen refresh checked, so the hitbox costume will never be drawn on the screen.
10. Add the Hitbox Code
We’ll add switchcostumeto blocks to the start and end of both pink custom blocks. Modify the Cat sprite’s code to look like this:
These blocks from the purple Looks category will change the costume to the hitbox. Because the hitbox is a simple rectangle that doesn’t have protruding parts that could “catch” on platforms, like the cat’s head and whiskers could, the game will behave in a more natural way.
Add a Better Walking Animation
The Cat sprite that a Scratch project starts with has two costumes named costume1 and costume2.
You can make a simple walking animation by switching back and forth between these two costumes. However, a Scratcher named griffpatch (whose profile is at https://scratch.mit.edu/users/griffpatch/) has created a series of walking costumes for the Scratch cat.
In addition, griffpatch has made costumes for standing, jumping, and falling.
Using these costumes will make the Platformer game look more polished than using the two simple costumes that the Cat sprite comes with. We just need to add some animation code that switches between these costumes at the right time. Fortunately, griffpatch has created several cool Scratch programs using the costumes in the book resources download at https://nostarch.com/scratch3playground/.
11. Add the New Costumes to the Cat Sprite
To add the new costumes, you must upload the costume files into your Scratch project. You’ll find the eight walking images and the standing, jumping, and falling images in the resources ZIP file. The filenames for these images are Walk1.svg, Walk2.svg, and so on, up to Walk8.svg, as well as Stand.svg, Jump.svg, and Fall.svg.
Then, in the Scratch editor, click the Cat sprite’s Costumes tab. Hover over the Choose a Costume button in the lower left, click the Upload Costume button, and select Stand.svg to upload the file. This creates a new sprite with Stand.svg as its costume.
Delete the original costume1 and costume2 costumes, but keep the hitbox costume. Put the costumes in the following order (it’s important that you match this order exactly):
Each costume has not only a name (like Walk1, Jump, or Fall) but also a number. The costume number is based on the costume’s order in the Costumes tab. For example, the costume at the top is named Stand, but it is also known as costume 1. The costume beneath it is named Jump, but it is also known as costume 2. The code we add in the next step will refer to costumes by their names and numbers.
12. Create the Set Correct Costume Block
With all these different costumes, it will be a bit tricky to determine which frame we need to show and when. We’ll use the idea of animation frames: several frames shown together quickly make a moving image, just like a flip book.
To keep track of the frames, create two For this sprite only variables named frame and framespercostume. Then add two set blocks for these initial variables to the Cat sprite’s whengreenflagclicked script.
Now the setup is done.
As the player moves the Cat sprite left or right, we want the frame variable to increase. The framespercostume variable keeps track of how fast or slow the animation runs.
Let’s edit the code in the definewalk custom block to increase the frame variable by an amount calculated from framespercostume.
When the cat is standing still (that is, not moving left or right), the frame variable should be reset to 0. Modify the Cat sprite’s existing whengreenflagclicked script to add a third ifthen block that resets the frame variable.
Now let’s write some code to determine which costume to show. We’ll use this code in a few places in the scripts we’ve written, so let’s make a custom block.
In the pink My Blocks category, click the Make a Block button and name this block setcorrectcostume. Check the option Run without screen refresh and then click OK. Add the following blocks to the Cat sprite, starting with the new definesetcorrectcostume block.
If the Cat sprite is on the ground (or has just started jumping or falling so that inair is less than 3), then we want to display either the standing costume or one of the walking costumes. Remember that the whengreenflagclicked script keeps setting frame to 0 if the player isn’t pressing the A key or D key. So when frame is 0, the switchcostumetoStand block displays the Stand costume. Otherwise, we must calculate which of the eight walking costumes to show. This calculation refers to costumes by their numbers, which are based on their order in the Costumes tab.
Which walking costume is shown is decided by the switchcostumetofloorof4+framemod8 blocks. Wow, that looks complicated! Let’s break it down to better understand each part.
The mod block does a modulo mathematical operation, which is the remainder part of division. For example, 7 / 3 = 2 remainder 1, so 7 mod 3 = 1 (the remainder part). We’ll use mod to calculate which costume number to display.
The frame variable keeps increasing, even though we have only eight walking costumes. When frame is set to a number from 0 to 7, we want it to display costumes 4 to 11. This is why our code has the 4+frame blocks. But when frame increases to 8, we want to go back to costume 4, not costume 12.
The mod block helps us do this wrap-around with the costume numbers. We can control the costume that is displayed by using a math trick: because 8 mod 8 = 0, a frame value of 8 will show the first walking costume! We have to add 4 to this number, because the first walking costume is actually costume 4. (Remember, costume 1, costume 2, and costume 3 are the standing, jumping, and falling costumes, respectively.) This sum is then used with the floor block. Floor is a programming term that means “round down.” Sometimes frame will be set to a number like 4.25 or 4.5, so 4+frame would be 8.25 or 8.5, but we just want to round down to show costume 8.
Whew! That’s the most math you’ve seen in this book so far, but when it’s broken down, it becomes easier to understand.
The code in the else part of the ifthenelse block handles what happens if inair is greater than or equal to 3. We check yvelocity to see whether the cat is falling (that is, if yvelocity is less than or equal to 0) or jumping (that is, if yvelocity is greater than 0) and switch to the correct costume. Finally, the definesetcorrectcostume code finishes.
Replace the switchcostumetocostume1 blocks in the definehandleground and definewalk blocks with the new set correctcostume blocks. Also, add the changeframeby1/framespercostume blocks so that the frame variable increases over time, as shown here:
Create the Level
The new walking animation makes the Platformer game look more appealing. Now let’s change the plain white background into a real level. What’s great about the code we’ve written for the Cat sprite to walk, jump, and fall is that it will work with a Ground sprite of any shape or color. So if we change the Ground sprite’s costume (say, for different levels), we don’t have to reprogram the Cat sprite!
13. Download and Add the Stage Backdrop
Click the Ground sprite’s Costumes tab. Hover over the Choose a Costume button, click the Upload Costume button that appears, and select PlatformerBackdrop.png, which is in the resources ZIP file. After this costume has uploaded, you can delete the previous costume.
It’s not enough to add the file PlatformerBackdrop.png as a costume for the Ground sprite. You must also upload it as a Stage backdrop. Hover over the Choose a Sprite button, click the Upload Backdrop button that appears, and select PlatformerBackdrop.png to upload it. We need to upload the file to both places because we’ll be erasing all the “background parts” from the Ground sprite in the next step. We only need the Ground sprite to mark which parts the Cat sprite can walk on. The backdrop will be the image that is displayed on the Stage.
14. Create a Hitbox Costume for the Ground Sprite
The Platformer game code is based on the Cat sprite’s touching the Ground sprite. The Ground sprite’s costume is a hitbox, so if the Ground sprite’s costume is a full rectangle that takes up the entire Stage, it will be treated as though the entire Stage is solid ground. We need to remove the parts of the Ground sprite’s costume that are part of the background and not platforms.
The easiest way to do this is to click the Select tool in the Paint Editor. Drag a Select rectangle over the part of the costume you want to delete. After selecting an area, press delete to remove that piece.
Use the Eraser tool to erase areas that aren’t rectangular. If you make a mistake, click the Undo button at the top of the Paint Editor to undo the deletion.
Keep removing the background parts of the costume until only the platform parts remain.
If you’re having trouble creating this costume, you can use the premade PlatformerBackdropHitbox.png image in the resources ZIP file. The background parts of the image are already deleted, so you just need to click the Upload Costume button on the Costumes tab to add it.
15. Add the Ground Sprite’s Code
The Stage backdrop is used to set the appearance of the platforms and background. The Ground sprite is used to identify which parts are solid ground that the Cat sprite can walk on. Add the following code to the Ground sprite’s Code Area:
The Ground sprite’s costume needs to line up perfectly over the Stage’s backdrop so that you can’t tell it’s there. Because the Stage backdrop and the Ground sprite’s costume came from the same image file, you can do this by moving the Ground sprite to the coordinates (0, 0). Otherwise, the Ground sprite’s costume won’t line up perfectly over the backdrop.
The drawing of the Ground sprite’s costume doesn’t matter as much as the shape of the costume. As long as the Ground sprite is lying perfectly on top of the backdrop, we can set the ghost effect to 100, and the Ground costume and backdrop will line up. The backdrop shows what the level looks like, while the Ground sprite acts as its hitbox.
16. Add More Wrap-Around Code to the Cat Sprite
Notice that the level has a couple of floating platforms and a hill with a pit in the middle. When the cat falls down the pit, it wraps around the Stage and reappears at the top. Let’s add wrap-around code for the left and right edges of the Stage as well. Add the following script to the Cat sprite:
When the cat walks to the left edge of the Stage, its xposition will be less than -230. In that case, we make it wrap around to the right edge by setting xposition to 230.
Also, if the cat is moving from the left side of the Stage, its yposition will be less than 5. This will put it inside the ground when moved to the right edge of the Stage, so an ifthen block checks for this condition and sets yposition to 5.
The other ifthen block wraps the Cat to the left edge of the Stage if it’s on the right edge (that is, its xposition is greater than 230).
Add Crab Enemies and Apples
The entire Platformer game setup is complete! The player can make the Cat sprite walk, jump, fall, and stand on platforms. The Cat sprite has some cool animations, and the backdrop looks like a real video game.
Now all we have to do is make a game using all the pieces we have. We’ll add an apple that appears randomly around the Stage and add a few enemies that try to touch the Cat sprite and steal the apples.
17. Add the Apple Sprite and Code
Click the Choose a Sprite button and select the Apple sprite from the Sprite Library window that appears; then click OK.
As in previous games, we’ll use a variable to track the game’s score. Click the orange Variables category and then click the Make a Variable button to create a For all sprites variable named ApplesCollected. This variable will keep track of the player’s score.
In the Apple sprite’s Code Area, add the following code:
At the start of the game, when the player clicks the green flag, the score in ApplesCollected is set to 0. Also, because the Apple sprite is a bit too big, we set its size to 50 percent.
During the game, the Apple sprite needs to appear in random places on the Stage. We make the Apple sprite invisible using setghosteffectto100. It then moves to a random place on the Stage.
But not just any random place on the Stage will do. We need to make sure the Apple sprite is not inside the Ground sprite, because it would be impossible for the player to get it. To prevent the Apple sprite from moving to somewhere inside the Ground sprite, the loop keeps trying new random places until the Apple sprite is no longer touching the Ground sprite. The movement of the apple won’t be visible to the player, because the ghost effect is still set to 100. When the Apple sprite finds a place that is not touching the Ground sprite, it becomes visible again with setghosteffectto0.
Then the Apple sprite waits until the Cat sprite touches it. When that happens, the score in ApplesCollected increases by 1, and the Apple sprite loops to find a new random place on the Stage.
18. Create the Crab Sprite
The game wouldn’t be very challenging if all the player had to do was jump around and collect apples. Let’s add some enemies that the player must avoid.
Right-click or long press the Cat sprite and select Duplicate. The enemies will use the same code as the Cat sprite so that they can jump and fall on the platforms. (We’ll remove the code that assigns the keyboard keys to control the sprite and replace it with code that moves the crabs around randomly.) Rename this duplicated sprite Crab. Then, on the Costumes tab, click the Choose Costume button and select the crab-a costume. Then open the Costume Library again and select the crab-b costume.
The Crab sprite will still have all the Cat sprite costumes (Stand, Fall, Walk1, and so on). Delete these Cat sprite costumes, including the hitbox costume. Create a new hitbox costume that is the right size for the crab. Here’s what the hitbox costume should look like (the crab-a costume has been placed over it so you can see the relative size, but the costume is just the black rectangle):
19. Create the Enemy Artificial Intelligence
In games, artificial intelligence (AI) refers to the code that controls the enemies’ movements and how the enemies react to the player. In the platform game, the AI for the crabs is actually pretty unintelligent: the crabs will just move around randomly.
In the orange Variables category, click the Make a Variable button and create a For this sprite only variable named movement. The movement variable will store a number representing the Crab sprite’s movements.
Jump up straight
Jump to the left
Jump to the right
The Crab sprite’s movements will be randomly decided and will frequently change. Add the following code to the Crab sprite:
At first, the movement variable is set to a random number between 1 and 6 that decides which movement the crab will make.
The rest of the Crab sprite’s code defines these movements. Find any code from the Cat sprite code that uses the whenkeypressed blocks and replace those blocks with ones that check the movement variable. (If you ran the program right now, the keyboard keys would control the CatandCrab sprites, because they have the same code!)
Modify the Crab sprite script that checks whether the player is pressing the A key or the D key to match the following code:
As with the Cat sprite, this code lets the Crab sprite walk left and right. Change the values in the walk blocks to -4 and 4 to make the crab move slower than the player.
Then change the script that handles the player pressing the W key to jump to match the following code:
This code lets the Crab sprite jump up, left, and right.
Now let’s animate the crab’s movements. The Crab sprite has only two costumes, crab-a and crab-b. We’ll switch between these two costumes to make it look like the crab is walking. We can simplify the setcorrectcostume block for the Crab sprite a bit.
Modify the setcorrectcostume code to look like the following:
Notice that the numbers in the floorof1+framemod2 blocks have also changed. The first costume is costume 1, and the Crab has only two costumes, so the numbers in these blocks have been changed to 1 and 2.
Finally, we need to create a new script so that the crabs can steal apples from the player. Add this code to the Crab sprite:
The Crab sprites subtract 1 from ApplesCollected and say “Got one!” when they touch the player. If the player has 0 apples, the Crab sprites will say “Apples!” but will not subtract 1 from ApplesCollected.
The game will be a bit more exciting with two crabs, so right-click or long press the Crab sprite in the Sprite List and select Duplicate from the menu.
20. Add the Time’s Up Sprite
We’re almost done! The last thing we need to add to the game is a timer. Now the player will be under pressure to grab apples as quickly as possible instead of playing it safe. Hover over the Choose a Sprite button, click the Paint button, and draw the text Time’s Up in the Paint Editor. Mine looks like this:
Rename the sprite Time'sUp. Then create a For all sprites variable named Timer and add the following code:
This code gives the player 45 seconds to collect as many apples as possible while trying to avoid the crabs who will steal one. When the Timer variable reaches 0, the Time'sUp sprite will appear, and the game will end.
Now the Platformer game is ready for final testing!
You did it! You’re a Scratch master! The advanced Platformer game is the most elaborate and complex project in this book. You combined and used lots of different concepts to make this game, so it might help to read through this chapter a few more times.
In this chapter, you built a game that
Uses a ground sprite that the player stands on
Uses pink custom blocks with the Run without screen refresh option enabled
Lets the player walk up and down slopes
Has ceiling detection so the player bumps their head on low platforms
Has detailed animations for walking, jumping, and falling
Implements AI for enemies so they move around on their own
That wraps it up for this book, but don’t let that stop you from continuing your programming adventure. You can always look through other Scratchers’ programs to get more ideas. Find a game you like and try to create it from scratch. (All my puns are intended.)
The great thing about Scratch is that it provides you with unlimited possibilities for the types of games you can make. You can create clones of popular classic games like Pac-Man or Flappy Bird. Or you can make unique games using your own designs. Good luck!