How to Code a Snake Game on Scratch

3,312

27

6

Introduction: How to Code a Snake Game on Scratch

About: Hi! I'm a young DIYer, and I like to dabble in a lot of subjects, from cardboard to baking. While the main focus of this account will be cardboard, I'll try to post the occasional baking and art tutorial. Just…

Want to learn how to code without all that language mumbo-jumbo? Scratch is the answer for you--it's a free website that lets you code without having to learn a whole new language. I discovered Scratch only a few weeks ago, but I'm glad to report that it's very easy to pick up, even for total beginners like me. In this tutorial, I teach you how to make a simple snake game in scratch, with sound effects and scoring.

If you want to test my version of the finished product before you start building, go to https://scratch.mit.edu/projects/454858553/.

Supplies

  • A computer/any device with internet access

Step 1: Exploring Scratch

Disclaimer: This isn't going to be a full out crash course on how Scratch works. If you're interested in learning more, I'd recommend going to Scratch's Ideas page.

To create a new project on Scratch, go to https://scratch.mit.edu/. Sign in if you already have an account, or click Join Scratch at the top right to create a new account. Once you're logged in, click the Create tab at the top of the page, next to the Scratch logo. This will take you to a brand new project page.

Automatically, the project page is on the Code tab, where we'll be dragging code blocks to actually make our snake game. On the tab to the right, the Costumes tab, is where we will be drawing our game characters (the apple and snake). The next tab over is the Sounds tab, where we'll be adding sound effects to our game.

When you're on the Code tab, there are three main sections that we'll have to worry about. The most left side with all the code blocks is divided into sections based on functionality, and I'll be calling these sections "drawers." The section right next to the drawers is what I call the "code space." This is where we'll be dragging and connecting the code blocks together. The area most right of the screen is divided in half--the top half is your viewing area, where you'll see your code output. The bottom half is your sprite pane, where all the sprites you've created are displayed. We'll be talking about sprites more in the next step.

The green flag above the viewing area, when clicked, runs your program. The red stop sign next to it stops your program.

Tip: Remember to repeatedly save your code by clicking the "Save Now" button on the top right of the screen that appears when you've added new code to the code space.

Step 2: Creating Our First Sprite

In Scratch, game characters are called "sprites". Our first sprite will be the snake.

To begin, delete the Cat sprite by clicking the trash symbol on the top right of the sprite box. Go into the Backdrops tab and click the Choose a Sprite button on the bottoms left corner. Click the paintbrush icon. Once you click the icon, you should see the Backdrops text on the tab switch to say Costumes.

Click the Circle tool from the toolbar on the left of the drawing board and use it to make a circle on the drawing board. Change the fill to green, or whatever color you want. Change the outline to none, which is just a red line slashing through a blank box. Change the name of the costume from "costume1" to "snake". Changing the name of the sprite from "Sprite1" to "snake" will also make things easier for you later on in this build.

Switch back to the code tab so that we can start programming our snake to move at our command!

Step 3: Making the Snake Move

To make our snake move, drag the "when flag is clicked" block from the Events drawer onto your code space. Go into the Motion drawer and select a "move 10 steps" block. When you click on the green flag above the output screen, you should see your snake sprite move. The next step is to make our snake move depending on which arrow key we press.

Step 4: Using the Arrow Keys to Move the Snake

Go to the Variables drawer and click the "Make a Variable" button. When a box pops up asking for a new variable name, type in "direction", and then hit OK. Drag a "When space key is pressed" block from the Events Drawer onto your code space. Change "space" key to "up arrow". Take a "set direction to 0" block from the Variables drawer and type "up" in the place of "0". Connect the block to the "When up arrow key is pressed" block.

Do the same for the other arrow keys (i.e. "When down arrow key is pressed", "set direction to down", etc.).

Delete the "move 10 steps" block from the code space. Replace it with a "forever" block from the Control drawer. Add an "if then" block inside the "forever" block. From the Operators drawer, drag a "___ = 50" block into the if block. Change "50" to "up" and drag your Direction variable into the blank space before the = sign.

Grab a "change y by 10" block from the Motion drawer and connect it to the inside of the "if direction = up" block. If you play your program right now, when you press the up arrow, your snake will move up on the screen. If you like the snake's speed as it is, keep the change as 10, but if you want it a little slower, change "10" to "5". If you want it a little faster, change "10" to "15". I'm just going to keep it at 5 for now.

Do the same for the other directions, changing the y or x values as appropriate (left and right mean a change in x while down means a negative change in y). By the time you're done, you'll be able to control your snake with the arrow keys.

Step 5: Snake Origins

When you continue to test your snake's movement, you may notice that the snake doesn't automatically reset to the middle of the screen when you restart the game. We'll have to enter code for this ourselves.

Drag "go to x: y: " block from the Motion drawer. A quick shortcut to find the middle of the screen's coordinates is to simply drag the snake sprite to the middle of the screen. The block will automatically reset itself to the current coordinates, although it will only do so if it hasn't been placed in the code space yet.

Now when you start your code, you'll see that the snake starts off at the center of the screen. However, you'll also see that the snake will just go in whatever direction it was going to before. To fix this, we'll have to tell the snake to point itself forward, which in this case is 90 degrees. Drag a "point in direction 90" block from the Motion block, and connect it below the "go to x: y: " block.

When you play your code again, you'll see that the snake automatically moves to the right. In keeping with the original version of snake, we want the snake to wait until an arrow key is pressed before moving. Go to the Control drawer and drag a "wait until " block to the bottom of the "point in direction 90" block. From the Sensing drawer, drag a "key space pressed" block to fill in the blank space in the "wait until " block. Click the drop down menu next to "space" and select "any". Now the block should read: "wait until key any pressed".

Test your code to make sure that it works.

Step 6: Apple Sprites

For this step, we'll be going back into the Costumes tab. There are two ways you can make the apple: #1--Draw it yourself or #2--Get an image from the Scratch image library.

For option #1, make another sprite by pressing the button on the bottom left and clicking the paintbrush icon. Use the paintbrush and fill bucket tool to draw your apple masterpiece, and use the select tool to resize it if you need to.

For option #2, make another sprite by pressing the button on the bottom left and clicking the search icon. When you get brought to the "Choose a Sprite" page, type "apple" in the search bar. Click on the Apple option that shows up. Use the select tool to resize the apple to your liking. Make sure to select both the apple and the stem, as they are treated as two separate objects in the drawing board.

Note: The size of the apple on the drawing board is irrelevant to the apple's actual size on the output screen. To get a sense of what the apple will actually look like once you start the code, look on the output screen as you resize it.

Step 7: Eating Apples for Points

Switch back to the Code tab. You'll notice that we have a blank code space, because all the code we wrote in the previous steps is for the Snake sprite. We'll have to write new code for the Apple sprite to make the snake earn points as it eats apples.

From the Events drawer, drag a "when flag is clicked" block into the code space. Choose the "go to x: y: " block from the Motion drawer and connect it the "when flag is clicked" block. Drag two "pick random 1 to 10" blocks from the Operators drawer and place them in the empty spaces between x and y.

To figure out where the apple should be placed, drag the apple sprite to the very left of the output screen. Take note of the x-value and input it in the place of "1" for the "pick random" block. Do the same for the very right, top, and bottom of the output screen, keeping in mind that the top and bottom extreme values are for the y-value.

Drag a "forever" block from the Control drawer. Place an "if then" block inside the forever block. From the Sensing drawer, choose a "touching mouse pointer" block and place it inside the blank for the if then block. Change "mouse pointer" to "snake" in the drop down menu.

Go to the Variables drawer and make a new variable called "score". Drag a "change direction by 1" block, and switch "direction" to "score". This will allow your program to keep score as the player collects apples. Once the player eats an apple, we want the apple to go to a different spot randomly on the screen. Duplicate the "go to x: y: " block we made before and connect it beneath the "change score by 1" block.

Now our program allows us to control the snake using the arrow keys, and we can gain points by eating apples.

Step 8: Fair Game

If you've tested your code recently, you'll notice that the score doesn't reset itself to 0 when you restart the game. We need to add extra code if we want the score to reset every time the flag is clicked.

Grab a "set direction to 0" block from the Variables drawer and change "direction" to "score". Place the block above the first "go to x: y: " block, right below the "when flag is clicked" block.

Step 9: Snake Grows Longer

This step is all about getting the snake to grow in size (length) as it eats more and more apples.

Go back to the snake sprite's code tab if you aren't already on it. Drag a "create clone of myself" block from the Control drawer. Connect it below the last "if then" block of code you have in the forever loop. When you run the code as it is right now, it makes the snake grow as it moves, even if it doesn't eat an apple. You might also notice that the snake will randomly break itself off and stop regenerating.

To fix this, go to the Variables drawer and make a new variable called "length". Drag a "when I start as clone" block from the Control drawer and place it on the code space. Connect a "wait 1 seconds" block from the Control drawer to the "when I start as clone" block. Replace "1" with the length variable. Finish this chunk of code off with a "delete this clone" block from the Control drawer.

Switch to the apple sprite's code tab. From the Variables drawer, drag a "change direction by 1" block and attach it below the "change score by 1" block we've already made in the code space. Change "direction" to "length" and "1" to "0.1". Drag a "set direction to 0" block and connect it below the "set score to 0" block we've already placed in the code space. Switch "direction" to "length".

Test your code. You should see the snake grow longer as it eats apples.

Step 10: Don't Touch the Edge!

By now, we've already built a fully-functional snake game. All we have to do now is add obstacles to the game, which in this case is game over if the snake touches the edge.

Go to the snake sprite's code tab. From the Events drawer, drag a "when flag is clicked" block onto the code space. Go to the Control drawer and choose a "forever" block from it. Connect the "forever" block below the "when flag is clicked" block. Place a "if then" block inside the "forever" block. Drag a "touching mouse pointer" block from the Sensing drawer and put it in the blank space in the "if then" block statement. Change "mouse pointer" to "edge".

Go to the Events drawer and drag a "broadcast message1" block into the "if then" block. Click the arrow next to "message1" and click "new message" in the drop down menu. In the text box that appears, type in "game over" and hit "ok". From the Control drawer, drag the "stop all" block below the "broadcast game over" block.

With all the code we've just written, our snake will now die if it hits the edge. Go ahead and try it for yourself.

Step 11: Game Over

As is traditional with all video games, we need to code in a clear game over sign for the player to see when the snake has died.

Go back to the Costumes tab and make a new sprite by clicking the paintbrush icon. Use the rectangle tool to make a background for the game over sign. Click the square with a red line through it to get no outline and change the fill's color to blue, or any other color you want. Use the text tool to write "Game Over" in big white letters across the background. Personally, I like how the font Pixel makes the game seem more retro, but any font is fine. Use the mouse select tool to resize the font to your liking. Rename the costume and sprite "game over".

Go to the game over sprite's code tab. Drag a "when flag is clicked" block from the Events drawer. Go to the Looks drawer and choose a "hide" block from it. Go back to the Events drawer and drag a "when I receive game over" block onto the code space. From the Looks drawer, get a "show" block and connect it to the "when I receive game over" block.

Test your code. The game over sign should appear when the snake hits the edge, but stay hidden while the game is still on.

Step 12: Player Stats

Go to the Variables drawer and make two new variables named "show score" and "high score". Drag two "hide variable direction" blocks and connect them below the "hide" block. For one block, change "direction" to "show score". For the other, change "direction" to "high score". Drag a "set direction to 0" block and connect it below the "show" block. Switch "direction" to "show score", and instead of "1", drag the variable "score" into the block's blank space.

Drag a "show variable direction" block and place it beneath the "set show score to score" block. Change "direction" to "show score".

Drag an "if then" block from the Control drawer. From the Operators drawer, drag a " > 50" block. Replace the blank space left of the ">" sign with the score variable. Replace the "50" to the right of the ">" sign with the variable high score. Choose a "set direction to 0" block from the Variables drawer and change "direction" to "high score". Replace "0" with the variable score, and place the block inside the "if then" block. Drag a "show variable direction" block and change "direction" to "high score". Place this block outside the "if then" block.

The code we've just written has enabled our game to keep track of a player's high score and compare it with other players' scores.

Step 13: Clean the Clutter

This step is mostly about cleaning up our game's output screen.

Some variables, like direction and length, do not need to be seen changing by the player. These variables are better as being behind-the-scenes, otherwise they might be distracting. To take them off the output screen, uncheck the checkboxes next to the variable names. Click and drag the variables on the output screen to reorganize where the shown variables show up on the output screen.

You can put the variables wherever you want, but personally, I put the score variable on the top left of the output screen. For the show score and high score variables, I right clicked on them and picked the option of "large readout". I also dragged them to the near middle of the screen, below the game over text. In the Costumes tab, I added text on the game over sign to clarify what the large readouts represent: score and high score.

We're almost finished with the game over sign. All we have to do now is hide the score variable once it's game over. We want the score variable to still be visible when the game is in play, but hidden when it's game over. To do this, drag a "hide variable direction" block from the Variables drawer and switch "direction" to "score". Attach this block below the "show variable high score" block. Drag a "show variable direction" block below the "hide variable high score" block. Switch "direction" to "score".

Step 14: Sound Effects

This is one of my favorite parts of the whole process, as sound effects really seem to bring the game to life for me.

Go to the Sounds tab while on the snake sprite's code tab. Click the button on the bottom left of the page to search Scratch's sound library. Search up the sound "bonk" in the library, and click on the sound box that appears. Go back to the code tab.

From the Sound drawer, drag a "play sound Bonk until done" block below the "broadcast game over" block. This will produce the Bonk sound effect when the snake sprite hits the edge.

Go to the apple sprite's sound tab. In Scratch's sound library, search up the sound effect "bite". Click on the option that shows up and go to the apple sprite's code tab. Drag a "play sound Bite until done" block from the Sound drawer and place it below the second "go to x: y: " block in the if then loop.

Step 15: Level Up

Just to be clear, this step is completely optional. The game we've built so far is a great stand-alone already, but if you want to make the game a little more interesting, continue reading.

To make our game more interesting, we want to increase the snake's speed when it reaches a certain score milestone. This milestone is up to you, but I put mine at 10 points.

Go to the snake sprite's code tab. From the Control tab, choose an "if then else" block and place it around the block of code we wrote in Step 4 (it's the if direction = up/down/left/right blocks). Make sure the "create clone of myself" block is outside the "if then else" loop, at the very bottom of the forever loop. For the blank in the "if then" statement, drag a "< 50" block from the Operators drawer. Replace "50" with "10", or whatever other score milestone you have set. Fill the blank to the left of "<" sign with the score variable. For the empty space below the "else" statement, duplicate the "if direction = up/down/right/left" blocks and place it inside the else loop. Change all the 5s and -5s with 10s and -10s.

This bit of code will make the game speed up once the player reaches 10 points, making it a little bit more interesting for the player.

Block Code Contest

Runner Up in the
Block Code Contest

2 People Made This Project!

Recommendations

  • Home Decor Challenge

    Home Decor Challenge
  • Explore Science Challenge

    Explore Science Challenge
  • Arduino Contest

    Arduino Contest

6 Comments

0
Shail2512
Shail2512

Reply 4 weeks ago

Can you please teach me

0
SratchUser666
SratchUser666

Tip 5 weeks ago

Maybe use an actual say block that makes the sound of an actual snake.

0
StumpChunkman
StumpChunkman

5 months ago

This is really cool. Thank you so much for sharing.