Guy codes a Snake game from scratch in under 4 and a half minutes. Posted by 3 years ago. Guy codes a Snake game from scratch in under 4. The snake is a list of these points (yes, a list of lists!) as it contains more than one point. It starts as a single pixel at the top left of the screen, denoted by 0,0. After which, more points will get appended to the list. The food is a single pixel positioned randomly somewhere else (not in the same row or column). Scratch is a free programming language and online community where you can create your own interactive stories, games, and animations.
Snake Game
Every time the snake catches a fruit, its size increases. I could have forked another Snake repository, but since I didn’t know Javascript (and I would need to use it on the next steps), I thought that developing the Snake game from scratch would be a good idea to learn more about it. Scratch Class Handbook. After being an instructor for the Saturday Morning Scratch Classes at the Museum of Art and Digital Entertainment in Oakland, CA, Al Sweigart has compiled a handbook of tips for teachers and parents interested in using Scratch to lead an after school coding club. Scratch Class Handbook PDF (version 3, updated 2020/10/07).
Learn It
- In this project you are going to create the well known snake game.
- The game play is as follow:
- The snake moves continuously on the game board
- The player uses the arrow keys to direct the direction of the snake's movement
- A mouse is placed on the board at a random location
- If the snake eats a mouse, two things happen: the player scores one and the snake grows longer
- When the snake has grown to certain length, there is danger that the snake may move cross its own body. If this happens, the game is over
We are going to code the above steps one at a time in Scratch
Code It - The snake moves continuously on the game board
- Create a new Scratch project.Delete the cat sptite by right clicking on it then delete.
- Next, we add a snake sprite. The sprite has two costumes, a head and a body. Right click on each image below to download to your homedrive. You can make your own later.
- Follow the steps below to create the snake sprite with two costumes.
- Now, lets add
some scripts
to make the snake movecontinuously
.Continuous movement
means using a loop. The scripts for this are very simple for now.
Code It - The player uses the arrow keys to direct the direction of the snake's movement
- Next we need to enable to player to control which way the snake moves.
- This is accomplished by using the four arrows.
- Each time an arrow key is pressed, an event is
triggered
, then the snake will point the way the player wants it to move. - During the game play, the event of arrow key pressing needs to be
continuously
monitored. Again, we will use aforever loop
- You need to add code for other three arrow keys inside the loop.
- Test your code to make sure you can control which way the snake moves.If you are stuck, check that your code looks like this.
Code It - create variables to keep score and the speed of the snake movement
- The snake movement is bit too fast. The computer is working as hard as it can to run your loop on move the snake 20 steps each loop.
- Lets create a variable called
speed
so that we can slow down the movement a bit but later we can also change the variable to make the game harder. - The speed is going to store the waiting time between each loop.
- We need to give it a value (number of seconds) at the start of the game. I used 0.2 seconds. You can use 0.1 second to make it move a bit faster.
- Test your code and make sure everything is still working.
- Create another variable called
score
to be used later and set it to 0 after green flag is clicked.
Code It - A mouse is placed on the board at a random location
- To get on making our game, we are going to use the mouse sprite from the Scratch site. Once you finish making this game, you can always go back to change the sprite to what you like.
- Lets add code so the new sprite, mouse can be placed on
a random location within the board
. The layout and dimension of the game board in Scratch is like this:- The maximum on Y axis is 240, the minimum on X axis is -240.
- The maximum on Y axis is 180, the minimum on Y axis is -180.
- We want the whole image of the mouse to be placed inside the border, so we need to pick a location that is somewhere between -230 and 230 on X axis and between -165 and 165 on Y axis.
- To pick a random location, we need to use the random block from Scratch's Operators block.
- Make sure you have click on the mouse sprite and then go to its script window. The mouse need to go to a random location at the start of the game (when the geen flag is clicked).
- Test your code to make sure it works.
Code It - The snake eats the mouse and score increase by 1
- The eating happens when the snake 'touch' the mouse.
- Once eaten, the mouse needs to move to a new random location and the score increases by 1.
- This eating, moving to a new location and increasing score need to be monitored
continuously
during the game play. All those three actions should be inside aforever loop
. - make sure you are working on the mouse sprite script window.
- Test again and make sure it all works.
Code It - The snake eats the mouse and it grows by one size
- This is probably the most difficult script to understand. So lets go over it slowly. Watch the following finished game carefully you will find the added body parts of the snake follow the head in both movement and directions.
- In scratch, you can create a clone or many clones to do exactly what we want.
- Lets create some clones to follow the head.
- Those clones should have the costume of the body, NOT the head. So after being created as a clone, they should switch costume to the body. So add the following code block to your snake sprite.
- Test your code now you will find:
- there are too many clones being created
- if the costume being switched to body, the head no longer showed up.
- To correct the costume problem, we just need to switch the costume to head at the start of the game.
- To correct the too many clones problem, we need to delete some clones at regular intervals. But how many clones to keep? Well, each time the player scores, there should be a clone added to the snake.
- The clone has been created every 0.2 seconds (the speed) continuously. To maintain the same number of clones as the score, the time we need to wait before delete extra clones is:
- Test your code, it should now keep tracking of score and the snake should grow after eating a mouse.
Code It - Game Over
- The game is over when the snake's body has crossed with itself.
- When this happens, we need to broadcast a game over message, so other sprites can act accordingly.
- It is much easier if you have a body costume that has a different colour from the head. Add the following code and pick the body colour.
- Since the body is a clone, we need to add some code to the clone on the snake sprite script window.
- What heppens to the snake when the game is over? We can hide it and stop its scripts. BUT if you hide it, make sure you also add show at the start of the game.
- Do the same for the mouse's script when the mouse receives GameOver message.
Code It - Improve the game by letting the snake to teleport
- The game is working. But it can be improved. When the snake hits the four borders, it simply stucks there.
- If we can add some code so that the snake comes from the opposite side when it hits the border (teleport), it will make the game play smoother and more enjoyable.
- To let the snake teleport, we need to
continuously detect
when it hits the border:- the X axis maximum when the snake is moving right
- the X axis minimum when the snake is moving left
- the Y axis maximum when the snake is moving up
- the Y axis minimum when the snake is moving down
- Can you add other three conditions when the snake is moving left, up and down?
Badge It
Silver
- Follow the instructions given above, producing a working game without the ability to teleport the snake.
Gold
- Finish the teleport code so that the snake can teleport from all 4 sides.
- Create a 'Game over' sprite.
- Add script for it, so when the game is over, it shows up and hides at the start of a new game.
Platinum
- A start new game screen so that players can:
- click a button to start a new game
- As the snake grows longer, it moves faster
This page is part of the Snake in MIT Scratch Tutorial.
The snake is composed of a number of sprites that each occupy one space on the grid.
As the snake moves and grows the pieces must be re-arranged to reflect the snake’s current state.
When designing a complex object like the snake there are two important areas to consider:
- Data Structures: All the variables that describe the object.
- Operations: The actions that the object can make.
The data structure describes the current state of the snake and the operations allow the snake to alter its state.
Data Structure of the Snake
The snake is described by the following data:
- Body Parts List: Contains the location of every piece of the snake.
- Head: The head is the body part at the front of the snake.
- Tail: The tail is the body part at the end of the snake.
- Direction: This is the direction that the snake is currently traveling.
The following diagram shows the data that describes the snake:
The data that is used to describe the state of the snake.
The body parts list contains the coordinates of every square that the snake occupies on screen.
The first element in the list is the head and the last element in the list is the tail.
In the example above the body parts list would contain the following data:
Scratch Game Code
{ (8,4), (7,4), (7,3), (7,2), (6,2), (5,2) }
![Scratch Scratch](https://www.reptileforums.co.uk/forums/attachments/snake-classifieds/24121d1286300619-female-ball-python-male-python-dscf0132.jpg)
Finally the direction variable stores the direction that the snake is currently traveling.
The possible directions are: Up, Right, Down or Left.
Operations on the Snake Data Structure
The following operations are used to manipulate the snake’s body during gameplay.
- Move Snake: Advances the snake one square in the direction it is facing.
- Grow Snake: Increases the length of the snake by adding an extra body part in the direction the snake is facing.
- Create Snake: Builds the snake at the start of a game.
- Change Direction: Sets the direction that the snake is currently traveling.
These operations are performed on the data structure as follows.
Move Snake
The process of moving the snake can be thought of as chopping off the tail of the snake and moving it to where the head should go next.
It wouldn’t be nice to do this to a real snake but it’s an effective way of moving the snake with the data structure described previously.
The method is as follows:
- Calculate the next position the snake’s head will move to.
- Remove the tail from the snake.
- Add a new body part at the next position
- Update the head and tail values.
The following animation shows the process: Freeslots com review.
Moving the snake can be visualized as chopping off its tail and moving it to the next position the head should go.
Grow Snake
The snake increases in length when it eats an apple. The process is similar to how the move operation is carried out:
- Calculate the next position the snake’s head will move to.
- Add a new body part at the next position
- Update the head and tail values.
The following animation shows the snake growing:
When the snake eats an apple the growth occurs at its front end. The tail pauses for a moment while the head grows.
The process is the same except the tail is not deleted at the start so the total number of body parts grows by one.
Create Snake
Creating a snake can be thought of as placing an empty snake (a snake with zero body parts) at a location and then repeating the grow snake operation until the snake is the desired length:
- Using the desired starting position decide upon the next position a body part should be placed.
- Use the Grow Snake operation to add a body part at the next position.
- If the snake’s body has reached the desired length then stop. Otherwise go back and repeat step 2.
The snake is created by repeatedly using the grow operation.
Reusing the grow snake operation when creating a snake is helpful because when it becomes time to implement the operation in Scratch the code for making the snake longer only has to be written once.
Change Direction
The snake’s direction value can be Up, Down, Left or Right. These are the movement directions allowed by the grid of squares. Casino games guide.
The snake is allowed to turn at right angles to its current direction:
The direction that the snake can turn changes according to the direction it is facing.
When its direction is Up or Down it is only allowed to turn Left or Right and when the direction is Left or Right it is only allowed to turn Up or Down.
Scratch Implementation of the Snake Data Structure
The data structure must be re-created using the tools available in Scratch.
![Snake Snake](https://cdn.gardenista.com/wp-content/uploads/2015/04/fields/ewr.jpg)
This diagram shows the data that describes the snake:
The data that is used to describe the state of the snake.
This data structure is implemented in Scratch as follows:
Body Parts List
The body parts list contains the coordinates of every piece of the snake’s body. Coordinates have 2 components – an X and Y value that represents a horizontal and vertical position.
In the Snake project the list of coordinates is created using 2 lists called snake parts X and snake parts Y. These lists contain all of the X and Y values that make up the body parts list.
The Body Parts List for the snake in the picture above would be as follows:
(8,4), (7,4), (7,3), (7,2), (6,2), (5,2)
This would be represented in Scratch with the two lists:
snake parts X: 8, 7, 7, 7, 6, 5
snake parts Y: 4, 4, 3, 2, 2, 2
The abstract body parts list that had two values for each body part has been replaced with 2 lists that each hold one value of each coordinate.
The lists appear in the Scratch data panel as follows:
The body parts lists have been made available to all sprites.
They have been defined globally – that is to say they are available in all sprite scripts.
The head is the first value in the lists and the tail is the last value in the lists. In scratch they are accessed within list blocks as follows:
The head and tail values are accessed in list blocks using the first and last index values.
Snake Part
Each part of the snake’s body is represented on screen by a clone of the Snake Part sprite.
Cloning allows multiple copies of a sprite to exist in the game. More information on cloning can be found in the Scratch Documentation.
At the start of the game the original Snake Part sprite is hidden.
When pieces of the snake are created a clone of the sprite is made and that is what appears on screen.
When the game ends all the clones are deleted.
The sprite uses the when backdrop switches block to know when the game has started or ended.
The Title backdrop is used at the start of the game and the GameOver backdrop is used at the end of the game.
At the start and end of each game the original snake sprite is hidden and all existing clones are deleted.
The sprite’s script contains the Move To Grid Pos function that allows it to position itself using the logical grid defined in Section 03 – Dividing the Playing Area into a Grid.
Function used to translate grid coordinates into Scratch screen positions.
Snake In Scratch
The snake is composed of multiple Snake Part sprites. Each of these sprites moves itself to the proper X and Y grid position according to what is stored in the snake parts X and snake parts Y lists.
In order that each clone of the Snake Part sprite represents a single piece of the snake a unique identifier is assigned to each clone. This unique value links the cloned sprite to the snake parts data it is to represent.
The identifier is defined in the Snake Part sprite script as snake part ID. Its value is an index of the snake parts X and snake parts Y lists – a number that corresponds to the location of a body part.
The snake part ID is defined in the Snake Part sprite. It is used to uniquely identify clones of the sprite and associate them with the body part they are to represent on screen.
Each clone of the Snake Part sprite has its own snake part ID that holds the location of the coordinates from snake parts X and snake parts Y that are used to position the clone on screen.
Creating a new body part for the snake has the following steps: Club world casino login.
- Add the position of the new part to snake parts X and snake parts Y.
- Create a clone of the Snake Part sprite.
- Assign the clone a snake part ID that points to the newly created position in snake parts X and snake parts Y.
The first step adds the position of the new body part to the body parts X and body parts Y lists.
The Snake Part sprite is cloned and its snake part ID is set to the index of the new body part’s position in the snake part lists.
The new position is added to the end of the list so the Snake Part sprite clone sets its value to the length of the body parts list as that will be the index of the last item in the list:
Scratch Games Tutorials
When a Snake Part sprite is cloned it sets its ID to the index of the last value added to the Snake Parts X/Y position lists.
Moving the Snake
In the abstract definition the process of moving the snake was described as chopping off the snake’s tail and moving it to the front as the new head.
The process of moving the snake works as follows in the Scratch project:
- Calculate the position that the head will occupy after the move is complete and store this in two variables called Snake Next X and Snake Next Y.
- Add the new X and Y Next Position values at the front of the snake parts X and snake parts Y lists.
- Delete the last item in the snake parts X and snake parts Y lists.
- Broadcast the Snake Changed message.
A new head is added and the old tail is deleted.
The Move Snake function appears in the Game Controller sprite as follows:
The move snake functions adds a new head to the snake and deletes the old tail.
After moving the snake the system broadcasts a Snake Changed message. The Snake Part sprites that compose the snake’s body will move to the snake’s new position when they receive this message.
Note: The next position is calculated as part of the input handling code described in Section 6.
Growing the Snake
Growing the snake works by adding a new head position to the snake parts lists and creating a clone of the Snake Part sprite to represent it on screen.
The process has the following steps:
- Add the Snake Next X and Snake Next Y position values at the head of the body parts lists.
- Make a new clone of the Snake Part sprite.
- Broadcast the Snake Changed message.
The position of the new head is added to the snake parts lists and a clone of the Snake Part sprite is created.
When the Snake Part clone is created it will assign its snake part ID to the new length of the list so that the new body part has a corresponding Snake Part clone.
The operation appears in the Game Controller script as follows:
The grow snake operation adds a new item to the body parts lists and then makes a clone of the Snake Part list to represent it.
Create Snake
The Create Snake operation makes use of the Grow Snake operation to create the snake’s body parts.
A starting location is decided and the grow operation is repeated until the snake is the desired length. The process has the following steps:
- Empty all of the body parts from the snake parts lists.
- Set Snake Next X and Snake Next Y to the location the tail should occupy.
- Repeat 3 times:
- Use grow snake to add a new body part.
- Move the Snake Next X to one space to the right.
The Create Snake operation appears in the Scratch project as follows:
Updating the Snake Parts
When the snake’s state changes by moving or growing the snake parts must move on screen to reflect those changes.
The game controller lets all the clones know that the snake has changed by using a broadcast block to send a message saying ‘Snake Changed’.
When the snake is changed the current tail becomes the new head.
The move and grow operations set the position of the head in the first item in the snake parts lists.
When the snake is changed the following script is executed:
When the Snake Updated message is received the clone uses its ID to look up the location it should move to from the body parts lists.
In order for a snake part clone to determine that it is the tail it checks its snake part ID against the length of the snake parts list. If the ID is equal to the length of the snake parts list then this snake part must be the final element and therefore the tail.
The snake part that is the tail sets its snake part ID to 1 so that it becomes the new head and uses the Move To Grid Pos block to move itself to the correct position on screen.
All of the other snake parts that weren’t the tail increase their snake part ID by one so eventually they will reach the end and become the tail.
Conclusion
The snake’s body is represented by a list of coordinates with its head being the first value in the list and its tail being the last.
Operations for creating, growing and moving the snake have been specified and their Scratch implementation has been described.
Next Section: Moving the Snake at Regular Intervals