We have a working game. Now we can focus on making it look good - that is juice.
Grab the assets for snake from the box alongside
Select the Main Node and add a Node2D as child
Attach a new script to the Background
To get a checkerboard pattern, we look at the grid coordinates (X, Y).
If you add x + y, the result alternates between Even and Odd.
If the result is odd we paint that square colour A (Light Green)
If the result is even we paint that square colour B (Dark Green)
Add variables for the two colours
Also add variables for the
grid size and screen dimensions
Determine how many columns and rows there are
Loop through every column and row
Find where you are on the grid
If the cell position is even
If the cell position is odd
So that the grid is painted
Each time the game starts
Right-Click on the Head node
Assign the head_right.png
The different head textures
Update the onready reference
So it points to the Sprite2D
Now update the process function
Based on the direction the snake
Add variables for all the different textures
These textures represent all the different
Possible directions of the tail and body
Create a new function to update the body
Go through every single piece of the body one by one.
Check who's in front of me (previous) and who is behind (next).
If I'm the first block, the 'front' is the Head.
If I'm the last block, I am the tail.
Draw an arrow from Me to the Front neighbour.
Draw another arrow from Me to the Back neighbour.
Do my neighbours share the same X alignment?
(i.e., are both X's zero?). If so, we are stacked vertically.
Do my neighbours share the same Y alignment? (i.e., are both Y's zero?).
If so, we are lined up horizontally.
If we aren't straight, we must be turning.
Add the two arrows together.
If I have no neighbour behind me, I am the tail.
Just point me toward the back of the snake piece in front of me.
Update the add_body_part function
To use Sprite2D instead of ColorRect
Give it a starting position
Call the update_body_sprites function
Using Vector Math can be abstract and confusing - let's refactor the code
Add a helper function which will
Tell us if our neighbour is
To the right or left of us
Now modify the update_body_sprites function to determine which body part to add:
Right-Click it and choose Change Type
Set the Texture to apple.png
In Offset disable Centered
Change the ready variable
Which references the apple
We should only spawn in free space
We mustn't spawn inside the snake
Adjust the move_food function
To loop through all the positions
Of the snake to check that we
Didn't choose one of them before
Choosing a final spawn position
This is the end of the tutorial.
You can expand it further by:
Increase the speed of the snake every ten apples eaten.
Add a win condition when there are no available spaces to spawn food
Add a game over screen with stats from the game
CONGRATULATIONS ON COMPLETING THE TUTORIAL!