Code Snake Game in Java
Summary
TLDRThis video tutorial guides viewers through the process of coding the classic game Snake using Java. The presenter starts by showing the final game, where the snake grows by eating red food and the player controls its movement with arrow keys. The game is developed using Java's built-in Graphics Library and runs in a 600x600 pixel window. The tutorial covers creating a custom JPanel for drawing, implementing game logic with a Timer for the game loop, handling key events for snake movement, detecting food collision to grow the snake, and updating the snake's body segments. It concludes with adding game over conditions for collision with walls or the snake's body and displaying the score. The presenter also mentions their ongoing series on game development in Java and invites viewers to subscribe for updates.
Takeaways
- 🎮 The tutorial demonstrates how to code the classic game Snake using Java with a built-in Graphics Library.
- 🔑 To start the game, players can use the arrow keys to control the snake's movement.
- 🍎 The snake grows by one segment each time it touches the red food item on the screen.
- 🏁 The objective is to grow the snake's body without colliding into the walls or its own body.
- 📐 The game area is a 600x600 pixel window divided into a grid of 25x25 pixel tiles.
- 📝 The game utilizes a custom JPanel class called `SnakeGame` to handle the drawing and logic of the game.
- 🔄 A game loop with a timer is implemented to continuously update and redraw the game at set intervals.
- ⏰ The game loop runs every 100 milliseconds, causing the snake to move and the game to refresh.
- ➡️ The snake's direction is controlled by setting velocity variables for the X and Y coordinates.
- 🚫 The snake cannot move in opposite directions to prevent it from moving backward into its own body.
- 🍂 The snake's body is represented as an ArrayList of `Tile` objects, with each segment drawn as a rectangle on the screen.
- 💥 The game ends if the snake collides with the walls or its own body, and a 'Game Over' message is displayed along with the score.
Q & A
What is the final result of the tutorial?
-The final result of the tutorial is a playable game of Snake in Java. The snake moves when arrow keys are pressed, grows by one segment when it touches food, and the game ends if the snake collides with the walls or its own body.
What programming language is used to create the Snake game?
-The programming language used to create the Snake game in the tutorial is Java.
How is the game window created in the tutorial?
-The game window is created using Java's Swing library by instantiating a JFrame object, setting its title to 'Snake', making it visible, and defining its size and location.
What is the purpose of the 'tile' class in the game?
-The 'tile' class is used to keep track of the X and Y positions for each segment of the snake's body and the food in the game.
How is the snake's movement controlled in the game?
-The snake's movement is controlled by detecting key presses using the KeyListener interface and updating the snake's X and Y coordinates based on the arrow keys pressed.
How does the snake grow in the game?
-The snake grows by adding a new segment to the snake's body ArrayList when the snake's head collides with the food.
What is the game loop responsible for in the game?
-The game loop is responsible for constantly redrawing the game panel with updated positions of the snake and food, creating the illusion of movement.
How is the food placed randomly on the screen?
-The food is placed randomly on the screen by using a Random object to generate random X and Y coordinates within the bounds of the game board.
What is the tile size used in the game?
-The tile size used in the game is 25x25 pixels, which determines the movement and grid size of the game board.
How is the game over condition checked?
-The game over condition is checked by detecting if the snake's head collides with its own body or with the walls of the game board.
What happens when the snake collides with the food?
-When the snake collides with the food, the snake eats the food, its body grows by one segment, and new food appears at a random location on the screen.
How is the score displayed and incremented in the game?
-The score is displayed at the top left of the game window and is incremented by one each time the snake eats the food, which corresponds to the length of the snake's body.
Outlines
🚀 Introduction to Coding Snake Game in Java
The video begins with an introduction to the tutorial on coding the classic game Snake using Java. The presenter shows the final game where the snake grows upon eating food and the game ends if the snake hits walls or itself. The tutorial will utilize Java's built-in Graphics Library and is part of a new series on game development in Java. The presenter also mentions other game tutorials available and invites viewers to subscribe for updates.
📐 Setting Up the Game Window and Panel
The presenter guides viewers through setting up the game window using Java's Swing library. A JFrame is created and configured with a size of 600x600 pixels, centered on the screen, not resizable, and set to exit the program when closed. A new class named 'SnakeGame' is created to extend JPanel, allowing for game drawing. The game's width and height are set, and the background is colored black. The main application file is updated to include an instance of SnakeGame and to pack the frame for proper sizing.
🎨 Drawing the Snake and Grid
The presenter explains how to draw the snake head as a green rectangle on the game panel. The position of the snake is calculated based on tile size, and grid lines are drawn to represent the game area. The snake's starting position is set, and the program is run to display the snake head and grid on the screen.
🍎 Drawing the Food and Randomizing Its Position
The food in the game is represented as a red tile, initially placed at a fixed position. To add an element of randomness, the presenter creates a 'Random' object and a function to place the food at a random location on the screen. The food's new position is determined by random numbers within the game area boundaries.
🔁 Creating the Game Loop and Moving the Snake
The game loop is set up using a Timer that calls the 'actionPerformed' method every 100 milliseconds, causing the game to repaint and update. The snake's movement is controlled by specifying a velocity and updating the snake's position within the game loop. The snake's movement is restricted to prevent it from moving backwards.
⌨️ Implementing Keyboard Controls for Snake Movement
The SnakeGame class is modified to implement the KeyListener interface, allowing the snake to respond to arrow key presses. The key press events are used to set the velocity of the snake, enabling it to move up, down, left, or right. The snake's response to key presses is tested in the program.
🐍 Adding the Snake's Body and Collision Detection
An ArrayList is used to store the segments of the snake's body. A function to detect collision between the snake's head and the food is defined, and when a collision occurs, a new segment is added to the snake's body. The snake body is drawn on the screen, and the move function is updated to ensure that the snake's body parts move in conjunction with the head.
🏁 Game Over Conditions and Score Tracking
The presenter adds game over conditions to stop the game when the snake collides with its own body or the game walls. A variable 'gameOver' is introduced and set to false by default. The game loop is stopped when the game over condition is met. Additionally, a score is displayed on the screen, which increments each time the snake eats the food. The score is represented by the length of the snake's body.
🎉 Final Touches to the Snake Game
The presenter removes the grid lines and adds borders to the food and snake rectangles for a cleaner look. The snake game is now fully functional with the snake growing after eating food, moving with keyboard input, and ending the game when it hits a wall or itself. The video concludes with an invitation for viewers to like, comment, and subscribe for more content.
Mindmap
Keywords
💡Snake Game
💡Java
💡Graphics Library
💡JFrame
💡JPanel
💡Game Loop
💡Tile
💡KeyListener
💡Collision Detection
💡Random Placement
💡GameOver Condition
Highlights
Coding the game Snake in Java using the built-in Graphics Library.
Starting the game with any arrow key initiates snake movement.
Snake grows by one segment upon touching red food.
The objective is to grow the snake without colliding into walls or its own body.
Creating a window for the game using Java's Swing library.
Defining a tile size of 25x25 pixels for game board partitioning.
Creating a SnakeGame class that inherits from JPanel for drawing the game.
Implementing a game loop with a timer set to 100 milliseconds for frame redrawing.
Using arrow keys for controlling the snake's direction with key event listening.
Preventing the snake from moving backward to avoid collisions with its own body.
Storing the snake's body segments in an ArrayList for easy manipulation.
Detecting food collision to increase the snake's size.
Implementing game over conditions for colliding with walls or the snake's body.
Displaying the game score based on the number of food segments eaten.
Drawing grid lines for visual clarity and then removing them for a cleaner look.
Adding borders to the game tiles for better distinction between segments.
Completing a fully functional game of Snake with visual and interactive elements.
Transcripts
hey there hope you're having a wonderful
day in this video we're going to be
coding the game Snake using Java so what
you see here is the final result of this
tutorial and to start the game you just
need to tap on any Arrow key
and you can see we have the snake moving
and whenever it touches the food which
is in red
it will grow its body by one segment so
the goal of the game is to
grow the snake's body without colliding
into the walls and if you Collide into
the walls or if the snake collides into
its own body the game is over
okay
so we're going to be coding this game in
Java using the built-in Graphics Library
so before we begin I just want to
quickly mention that I am working on a
new coding tutorial Series where I teach
you how to make games in Java So
currently I'm working on Tic-tac-toe and
snake and there will be more tutorials
in the future
I also have tutorials in HTML CSS and
JavaScript for Doodle Jump breakout
Flappy Birds Space Invaders Wordle
Sudoku 2048 Candy Crush and snake as
well so if you're interested and you
want to stay up to date on new tutorials
make sure you subscribe to this Channel
and you can also find this list on
kenneopecoding.com
all right let's begin so for this
tutorial I'm going to be using visual
studio code if you want to learn how to
set up visual studio code with Java I
have a video on that and I'll link it in
the description below
all right so let's create a project so
Ctrl shift p Java create project and no
build tools I'm going to create this on
my desktop
and let's call it snake
all right now I have my project folder
inside the source folder we have this
app.java file so let's open that
and the first thing I'm going to do is
delete this line
alright so now let's create a window for
our game so what I need to do is import
Java x dot swing
okay
and then in our main function let's
define a few variables so int board with
is going to be 600 pixels
and into Board height and we'll set that
to board width so Board height will also
be 600 pixels
all right let's create a window so
jframe
frame is new jframe and let's give it a
title so we'll just call it snake
let's make the frame visible so frame
dot set visible
we'll set this to true
frame dot set size we're going to set it
to board width
Board height
so this is going to be a window that is
600 pixels by 600 pixels
let's do frame dot set location relative
to null so this is going to open up the
window at the center of our screen
frame that's sizable
we're going to set this to false
and then frame dot set default closing
operation we're going to set this to
jframe dot exit on close
so this is going to make it so that the
program will terminate when the user
clicks on the x button on the window
all right let's run our program
and you can see we have a window
so now that we have our window what we
need now is a jpanel so that we can draw
our game so instead of creating a jpanel
here I'm going to create a new class
that will inherit the jpanel
so over here in our source folder I'm
going to create a new file and I'm going
to call it snake game
dot Java
so now we have our snake game file
and let's add some import statements so
import
java.awt dot asterisk
import
java.awt.event dot asterisk
import
java.util Dot arraylist
so this is going to be used for storing
the segments of the snake's body
import
java.util dot random
so this is going to be used for getting
random X and Y values to place our food
on the screen
finally import Java x dot swing dot
asterisk
okay so those are all the import
statements that we need
so in our class I'm going to extends the
jpanel
so basically we are inheriting here and
for those of you who don't know what
that means we are creating a new class
called snake game that will take on the
properties of Jade panel so basically
it's a version of jpanel with more
things that we can add
all right so now for our snake game
Let's create some variables for the
width and height
let's also create a Constructor
snake game
and this is going to take in two
parameters so board width
and Board height
so here I'm going to do this dot board
with
is equal to board width
and this dot Board height is equal to
Board height
so the reason why we need the this
keyword is to distinguish the two
boardwifts so we have one as a parameter
and another as a field or a member of
the snake game class so to distinguish
the two we say this dot board width
meaning the board width that belongs to
this class
so now we're going to take the board
width and Board height
and set preferred size to new dimension
this dot board with
this dot Board height
let's set the background of the panel to
color dot black
and then we're going to go back to our
app.java file
and we're going to create an instance of
the snake game
snake game is equal to a new snake
game
and we need to pass in the two
parameters so board width and Board
height
and then we're going to take the frame
and add the snake game
so if I run the program
you can see we have our snake game which
is a j panel inside our frame now
there's an issue and that is we set the
size of our frame to 600 by 600 what
that includes is this title bar over
here where it says snake essentially
this panel is actually not 600 by 600
pixels it's a little less than that
because of this title bar
so to resolve this issue we just need to
do frame dot pack so that it will place
the jpanel inside the frame with the
full dimensions
okay and we don't really need the
sidebar anymore so I'm just going to
collapse that
so here you can see our snake game it is
600 by 600 pixels and what we need to do
is we need to define a tile size so I'm
going to Define it as 25 by 25 so that
is the size of one square and basically
we are partitioning the 600 pixels into
24 columns and 24 rows so that whenever
we move the snake it moves over one tile
or one square instead of the exact pixel
number so it is 25 pixels by 25 pixels
so when the snake moves over to the
right it should move over 25 pixels and
if it moves over to the right again it
will move over 50 pixels and then 75
pixels
100 125 and so on
so here I'm going to define a tile size
and set it to 25 pixels
and so we're going to create a new class
to keep track of all the X and Y
positions for each tile so
let's create a new class and actually
I'm going to create it as a private
class
so that only the Snake Game can access
this class so private class tile
and x and into y
and then let's create a Constructor so
tile into X into y
this dot X is equal to X and this dot Y
is equal to y
so when we draw a tile on the game
screen we need to specify an X Y width
and height
so over here we have a width and height
of 25 pixels by 25 pixels but what is
the X and Y coordinate well we scaled
everything by 25 pixels per tile
so if you look at our window here we
have one two three four five
in the X Direction and one two three
four five in the y direction
so the X and Y coordinates start at the
very top left corner which is 0 0 and
the bottom right corner is 600 by 600.
so where is the snake's X and Y position
it will be five five so those are the X
and Y coordinates but because we have a
scale the tile size meaning each tile
has a width and height of 25
to physically place the snake in this
position on the screen we need to
multiply the x and y coordinate by 25 so
this will be 5 times 25 and 5 times 25.
so the X and Y would be 5 5 but
physically pixel wise it'll be 125
pixels 125 pixels okay
so I'm going to create a tile snake head
variable
and then within our Constructor
I'm going to do snake head is equal to
new tile and we need to specify an x and
y coordinate so I'm just going to use 5
5 as the default starting place
so now that we have our tile object we
need to draw this so I'm going to create
a function
public void paint component
and it's going to take in graphics G
which is used for drawing and I'm going
to do super dot paint component
G
and draw G
so we need to define a draw function
so public void draw Graphics G
and for the snake I'm going to set the
color of the pen
to color not green
and I'm going to draw a rectangle so g
dot fill rect
we need to specify the X and Y position
so Snakehead dot X Snakehead dot y
o size for the width and tile size for
the height
all right so now we run our program
so you can see we have a green rectangle
that is the snake head and the width is
25 pixels and height is also 25 pixel
now something here looks off and that is
the X and Y coordinate so where we drew
the snake it should actually be
somewhere over here right because we
specified 5 5 we meant five units to the
right and five units down
now the thing here is when we passed in
the values for the X and Y coordinates
we literally passed in five five so the
fill rect recognizes that as 5 pixels to
the right and five pixels down so to get
it five units down and five units to the
right we need to multiply the X and Y by
the tile size
so over here I'm going to do Snakehead
dot x times tile size
and Snakehead y times tile size
so now if I run the program again
you can see our snake is over here five
units to the right and five units down
okay and physically on the screen it is
5 times 25 so 125 pixels to the right
and 125 pixels down
and just to make it easier for you to
visualize I'm going to draw some grid
lines here
so for INT I is equal to zero I less
than board width divided by tile size
I plus plus
so board width is 600 and tile size is
25 so 600 divided by 25 gets you 24 so
we have 24 rows and 24 Columns of
squares so for each one I'm going to
draw a line so g dot draw line I times
tile size
zero
I times tile size
Board height
and let's draw another line so G that
draw a line
zero
I times tile size
board with
I times title size
so whenever you draw a line you need a
starting point and an end point so
that's why we have X1 y1 and X2 Y2
the first line here we are drawing
vertical lines
so the Y's will be from zero to the
height and X will change so these X1 and
X2 they will move together and basically
we need to change the x value so that it
goes from left to right now for the
second line we are drawing horizontally
so it's going to start from the X
position of zero to the board width and
we need to draw line by line up and down
so we are changing the y coordinate
okay
so now if I run our program
you can see we have our grid lines
all right so now that we have the snake
in the proper position let's draw the
food so the food is also going to be a
tile
so here I'm just going to separate the
two so this is the snake
and for the food we have
Tayo food
and inside the Constructor
I'm going to create a new tile for the
food
so food is equal to new taiyo
and let's just set the X and Y to 10 10.
all right so now that we have a tile
representing the food let's draw it on
the panel
so here I'm going to draw the food
before the snake
so food goes here and I'm going to do G
not set color
dot red
and similarly I'm going to do g dot fill
rect
food.x times tile size
Foo dot y times tile size
and for the width it's going to be tile
size and the height is also going to be
tile size
all right now let's run our program
and you can see we have our food here
and it is 10 units to the right and 10
units down okay
all right so now that we have our food
let's create a function that will
randomly place the food on the screen so
that the X and Y position isn't always
10 10. so to randomly place the food I
need to create a random object so over
here I'm going to do random random
and then down here I'm going to create a
random object So Random equals new
random
and then I'm going to call the place
food
function
and then down here let's define our
place food function
and basically this function will just
randomly set the X and Y coordinates of
the food
so food.x is going to be random than
maxed int of board width divided by tile
size
and food.y
is going to be random than next int
of Board height divided by tile size
so board width and height are both 600
pixels and tile size is 25 so this would
give us 24
so the X Position will be a random
number from 0 to 24. and the Y Position
will also be a random number from 0 to
24.
all right so now if I run our program we
expect the food to be placed in a random
location
over here
and then if I we run it again
and again
you can see the position is changing
every time
okay
all right now that we have the snake and
the food we need to make the snake move
and before we make the snake move we
need to create the game Loop
so when we make the snake move we are
changing the X and Y position of the
snake and to reflect that on the screen
we need to redraw the panel so that we
draw the new rectangle with the updated
X and Y positions
for that reason we need a game Loop so
that the game Loop will constantly
redraw the frames
so to create the game Loop we need a
timer so
over here I'm going to add a new section
for variables and I'm going to call it
game logic
and I'm going to create a variable for
the timer
and we're going to name it game Loop
and then down here I'm going to assign
game Loop
to new timer
and over here we need to tell the timer
how often it should run so let's say 100
milliseconds
so 100 milliseconds is one tenth of a
second
and we need to tell the timer what to do
every 100 milliseconds so we're going to
place the keyword this over here
and then up here
I'm going to implement
action listener
so now you can see we have an error here
and that is we need to
add a new method when we implement the
action listener
so down here we need to create an action
performed method and override it so over
here let's just get rid of this
and then what I'm going to do is call
repaint
so every 100 milliseconds we are going
to call this action performed which will
repaint
and repaint basically calls draw over
and over again
okay
so over here I'm going to do game Loop
dot start
so now if I run a program
you can see we are drawing over and over
again but you don't really see a
difference because we didn't make the
snake move so it is drawing the same
frame over and over again every 100
milliseconds
all right now that we have our snake and
we have our food and we have our game
Loop we need to make the snake move
so just as a recap the top left is 0 0
and the bottom right is 600 600. so it's
600 pixels by 600 pixels or it's 25
tiles down and 24 tiles to the right
okay so where is the snake
the snake is five tiles down and five
tiles to the right or 125 pixels down
125 pixels to the right
so if we want to move the snake we need
to specify a velocity and velocity is
the change in position over time
so just now we created a game Loop and
the loop runs every 100 milliseconds so
every 100 milliseconds we want the snake
to move in some Direction
so for velocity X we have negative and
positive negative is going to the left
and positive is going to the right
because if you're going to the left
you're going towards zero
and if you're going to the right you're
going towards 600 pixels
and velocity Y is up and down so
negative velocity y means you're going
up towards zero and going down means
you're going towards 600 pixels
so when we're drawing our Square when we
update the X and Y position by one we
are moving the snake one tile over okay
so if I want to move to the right
velocity X will be positive one and
whenever we draw our snake each frame we
are moving it over one tile at a time
okay
all right so over here I'm going to
specify a velocity X
and a velocity y
and then over here I'm going to set
velocity X to Zero and velocity of Y
let's just make it 1.
so if velocity Y is one it's going
downwards
now within our game Loop over here I
want to call a move function that will
update the X and Y position of the snake
and after that we will repaint
so up here I'm going to define the move
function
and for the snake head
I'm going to do Snakehead dot X Plus
equal velocity X
and Snakehead dot y plus equal velocity
y
all right so this is going to be called
every 100 milliseconds and we are
updating
X and Y position in this case velocity X
is zero so it's only moving in the y
direction
all right now that I run the program you
can see the snake is moving downwards
and if I go back up and I change this to
zero and I make
velocity x negative one we can expect
the snake to go to the left
and there you go the snake just moved
left
all right let's set this back to zero
so now the snake is not moving because
velocity X and velocity y are both zero
so there is no change in position
all right now that we can make the snake
move we want to be able to control the
snake using arrow keys so I want the
Snake Game to listen to key events
so for that I'm going to implement
key listener
and for the key listener we need to
override three methods so in Visual
Studio code if I just hover over this
and
click on Quick Fix add unimplemented
methods
then I scroll down
you can see we have three methods that
we need to implement
in our case we just need the key press
so I'm just going to take this
and move it up here
let's format this
and we do not need the rest of this so
do not need
and I'm just going to get rid of this
and get rid of this
all right so we just need to Define
these methods we don't need to put
anything inside we just need to Define
them we only care about the key press so
that's whenever you press on a key
so let's get rid of this piece of code
and over here let's define the Four Keys
that we need so up down left and right
so if e dot get key code is equal to key
event
dot VK underscore up
this means that we press the up key I'm
going to set velocity X to Zero
and velocity y
to negative 1.
else if e dot get key code is equal to
key event
key event dot VK down
velocity X will still be zero but
velocity Y is going to be 1.
else if e dot get key code
is equal to
key event dot VK left
velocity X will be negative one
and velocity y will be zero
else if e dot getkey code is equal to
key event
dot VK right
velocity X will be positive one and
velocity y will be zero
all right so now we have our key press
defined now we need to make the game
panel or the Snake Game listen to the
key presses so let's scroll up
and within our Constructor I'm going to
do add key listener this
and we want our snake game to be the one
listening for key presses so I'm going
to do set focusable
to true
and then I'm going to go back to
app.java
and do snake game dot request Focus
so now our snake game is going to be the
one listening for the key presses
all right now let's run our program
and now let's make the snake go down
right up left
down right and so on so the snake is
able to move but we have one problem and
that is the snake is able to move
backwards right so if it goes up it
shouldn't be able to move down
otherwise it will run into its own body
so to fix that we just need to make sure
that the snake is not already heading in
the opposite direction so I'm going to
put n velocity y
is not equal to one
and for moving down
we need to make sure velocity y
is not equal to negative one
moving left velocity X
not equal to one
and moving right velocity X not equal to
negative one
all right so now if I run our program
and I press down I cannot press up to go
back up
all right so now that we have the snake
moving let's have the snake eat the food
and grow its body
all right so for the snake's body we
need an arraylist to store all of its
segments so each part is a tile so I'm
going to use an array list
so over here arraylist
tile let's call it snake body
and then within our Constructor
snake body is equal to new arraylist
tile
all right now that we have an arraylist
to store all the snake's body parts
let's create a function to detect
collision between the snake's head and
the food
so down here let's define a function
chord collision and it's going to take
two tiles tile one and tile two
and to determine if two tiles are
colliding it's very simple we just need
to check their X and Y positions so if
they are in the same X and Y position
that means they are both in the same
tile
so I'll return tile one dot X is equal
to Tio two dot X and tile one dot Y is
equal to tile two dot y
and we're going to use the same function
for detecting whether the snake has also
collided with its own body
So within the move function let's add
this check
so this is for eating the food
if Collision
snake head
food
we are going to add a new segment to the
snake's body so snake body dot add new
tile
food.x food.y
and then we are going to call Place food
and then one more thing we need to do is
in our draw function we need to draw
each body part of the snake
so this is the snake's head and then I'm
going to scroll down a bit
let's draw the snake body
and we are going to iterate through the
arraylist for the snake body
tile snake part is equal to snake body
dot get
I
and then we are going to draw a
rectangle for that snake part so g dot
fill rect
snake part
dot x times tile size
snake part dot y times tile size
and then the width is tile size
and the height is also tile size
all right now let's run our program
and if we collide with the food you can
see we are eating the food and the
segments are there because the color is
green
but
we are not moving any of the snake's
body parts
so we need to Define this in the move
function
all right so to move the snake body we
need to make sure that it moves along
with the head so I'm going to move all
the tiles within the snake body before I
move the head and the reason is if I
move the head first the next tile which
is the first member of the snake body
it's not going to know where to go right
because we are following the leader
which is the snake head so to resolve
this I'm going to iterate backwards on
the arraylist and for each part it is
going to copy the X and Y position of
the part that came before it so
therefore we are basically saying each
tile needs to catch up to the one before
it before the snake head can move
so let's move the snake body
oh it should be snake body
and I'm going to iterate backwards
into I is equal to snake body dot size
minus one
I greater than or equal to zero I minus
minus
so we're going to get the tile for the
snake's part so tile
snake part
is equal to
snake body dot get I
so if I is equal to zero
this means this is the first member of
the snake body the one that comes right
after the snakehead
we are going to do snake part
dot X
and set it to Snakehead dot X
snake part dot Y is equal to Snakehead
dot y
otherwise we are going to have it copy
the X and Y position of the body part
that's before it
so let's get the body part before it
tile prep snake part
is equal to snake body dot get
I minus one
snake part dot X is equal to prev snake
part dot X
snake part dot Y is equal to prev snake
part dot y
so now we are moving the snake's body
along with the head
all right now let's run our program
so when the snake touches the food it
eats the food and it grows by one tile
and you can see the body is moving along
with the snake's head
alright so now that we can grow the
snake
we need to check for game over
conditions so there are two situations
for game over one is the snake collides
with its own body or the snake collides
against the walls
all right let's implement the game over
conditions so over here
I'm going to add a new variable called
game over and I'm going to set this to
false by default
and then within our move function
let's add the game over conditions
so let's start with the first one and
that is the snake collides with its own
body
so I'm going to iterate through all the
body parts of the snake
tile snake part is equal to snake body
that get I
so if we collide with the snake head
so if Collision
snake head snake part
I'm going to set game over to true
and then Within action performed
which is our game Loop
if a game over
I'm going to do game Loop dot stop
so this will end the game right there
so let's run a program
so we're going to eat the food and
grow the snake body so that when it
collides with itself
the game should end
okay there you go
so the game Loop has stopped and the
snake is no longer moving
all right now let's add the other
condition and that is the snake hits one
of the four walls so over here
if
Snakehead dot x times tile size
is less than zero that means the X
position past the left wall
or Snakehead dot x times tile size
is greater than board width
this means that the X position of the
snake has gone past the right side of
the screen
or
Snakehead dot y times tile size is less
than zero this means that the snake has
gone up past the screen
or Snakehead dot y times tile size
is greater than Board height
so the snake has gone down past the
screen
we are going to set game over to true
so let's format this
highlight and shift tab
okay
now let's run our program
okay now if I eat the food and I go down
you can see game over
and then if I run the program again
and go to the left game over so I can't
move anymore
so let's make this more obvious by
putting the word game over here and
actually let's also keep track of the
score so let's do that in the draw
function
all right so within our draw function
let's scroll down
and I'm going to draw the score and the
text for game over
so I'm going to do g dot set font
new font
aerial
font dot plane
16.
so if game over
I'm going to set the color
to color.red
and g dot drawstring
game over
and let's also put the score so string
dot value of
and the score is just going to be the
length of the snake body so how many
times you've eaten the food
so snake body not size
and then I'm going to set the x position
to be tile size -16
and the Y Position will be tile size
else let's just uh tell the user what
their score is so G that drawstring
score
plus string dot value of
snake body dot size
tile size minus 16 and tile size
okay now let's run our program
okay so now you can see the text for
score on the top left and now if I eat
the food score increments by one
two
and then let's try to get game over and
there you go so game over and our score
is five
all right so now there's one more thing
that I want to quickly show you and that
is I'm going to get rid of the grid
lines so let's comment this out
and you can draw the rectangles with
borders so just take this
for food and I'm just going to copy and
paste that here
and this will be fill 3D react and then
I'm going to add one more parameter true
and let's also do the same thing for the
snake head
so fill 3direct
true
and let's actually count out these two
okay
and then finally for the snake body I'm
going to copy and paste this
combat this out
and then let's rename this so fill 3D
rect
and then let's pass in true
all right now let's run our program
so now we have a border around our tiles
so if I have the snake eat the food and
grow its segments
you can see each part is divided by the
border
and we have a fully functional game of
snake
so if this tutorial worked for you make
sure you give the video a like and if
you have any questions let me know Down
Below in the comments and if you want to
see more content like this make sure you
subscribe to the channel and I'll see
you in the next video
bye bye
Parcourir plus de vidéos associées
![](https://i.ytimg.com/vi/1a9WJkZmAbQ/hq720.jpg)
Lecture: 14 | WATER BOAT GAME IN SCRATCH | GAME DEVELOPMENT | SCRATCH TUTORIAL
![](https://i.ytimg.com/vi/VE_bkPrrZdE/hq720.jpg)
Unity 2D CHECKPOINTS Tutorial (Simple and Easy!) | Unity 2D Platformer Tutorial #9
![](https://i.ytimg.com/vi/A3HLeyaBCq4/hq720.jpg?v=646ae0c0)
Juiced Up First Person Character Controller Tutorial - Godot 3D FPS
![](https://i.ytimg.com/vi/ELCQbRvDl0U/hq720.jpg)
How to make a Roblox JOJO game #1 | Making Stand Summoning
![](https://i.ytimg.com/vi/qjw1M12Rcho/hq720.jpg)
Make A Bike Tire in Blender With A Non-Destructive Modelling Workflow
![](https://i.ytimg.com/vi/OuZrhykVytg/hq720.jpg)
What are Events? (C# Basics)
5.0 / 5 (0 votes)