Part 5 – Snake Game Tutorial – Generate Food, Body Collissions and More.

Part 5 – Snake Game Tutorial – Generate Food, Body Collissions and More.

hello guys welcome back this is the part
5 of our snake game development tutorials in Java so what we have so far
right now is the snake and a simple menu that we can press enter and
then start the game, lets start it again ok and then some collision detection ok
and then starting the game so the one crucial thing that are missing in
our game is the food so we need to generate the food so that the snake can
eat it and we can grow the snake and when the snake is becomes longer it will
be much difficult to control and then we need to print some score here to show
how many food that the snake already eaten ok so lets start okay so the first task that we
need to do is to create a setting of the food location so the here in the food
class we can add a method public void setFoodLocation() so this is crucial
because we need to call the setFoodLocation() multiple times in a game
so whenever the snake eats the food it will generate another food and then show
it in this specified location so that’s why we need to have a setFoodLocation()
as function to call for our food to appear. So this is also set location X Y
ok so that is the set food location an X in our game engine we have set the food to
200 by 150 but we can produce it randomly so we need to set it as 0 and
then when we when we start the game we need to
produce the food randomly in our game so randomly means we need to have some
basic computation of the location or the possible location of our food so we need
the create another method here and then name it produce food so produce food
will be called multiple times so location X so let’s set it first to zero
and location Y is set to zero, then food that sell food location is locX
and locY now how are we going to produce it randomly so the lower portion
let’s create a another method private int generateRandomOnGrid() so we need to
make sure that the value that will be produced by this one will be the same to
be exactly the same as in the head the location of the head so as you can
imagine we can say that this one is a whole pixel so let’s let’s color this
one is blue so so what if this is an specified pixel since if you look at our
snake the snake has the size of 10 so 10 pixel so we can assume that this this
four blocks might be the head so let’s say this is the head and it is made of
10 by 10 pixels of one-box is equivalent to 5 pixel 5 pixels by 5 pixel and this
one is also 5 pixel by 5 picture and then the food that we produced and put in the coordinates something like this so let’s change this color to okay so
for example this is the food and this is the head so now if the head is running
towards the food and it appears here I’m sorry it appears here so there is an
overlap how can we say that the snake or the head it’s the food so it
should be it should cover and the entire food not something like an overlap like
this one so we need to produce the food exactly where the head is where the head
will be possible will be possibly appear so that’s if the head is on this
position the food should be here so that if the snake is coming towards the food
it will be something like this and then this okay so let’s clear this one and overlaps the entire food and then we can
say that if the head or the snake gets the food so if it covers the food
entirely that’s the time that the we can say that the snake has eaten the food
and the snake will becomes longer so let’s go back here so to make that
feasible we need to generate a random number using the Math
that class Math dot floor and here have a variable high and low so
the floor will return the nearest the nearest floor flooring number so it is
rounding down the value since we can generate a random number using the
random method in in the Math class but the random has a return of double so we
need to convert it to integer that’s why we have a typecasting here so Math dot
random so times the minimum should be 1 plus high minus low and plus low multiplied by 20, so that is that would be the computation so this will appear the random number will
appear exactly on the by 10 it is not totally random it is it will appear
based on the size of the snake, so if if the the value generated is let’s say
our game form is 600 by 600 so if the generated number is let’s say 17 it will
be converted to flooring number which is 10 so it will align itself with the head
of our snake so it will align like this one or like
this one or like this one alright so it was not going to overlap like this case
so we cannot check it if the food is entirely, is being eaten by D snakes we
need to have a way to generate exactly that is aligned with the head of the
snake and the body also of the snake so this is the generateRandomOnGrid(), so we can call it here the generateRandomOnGrid(), then past the minimum and maximum the high the high and the and then pass low so the the high should be game form dot width divided by 20 minus 5 then the low is 1 then the same for Height so this this will make it exactly
aligned with the head of our snake so now we can call this a produceFood() in
our initialization so here so let’s check mmm-hmm where is our food okay so we
didn’t draw the food yet so we need to draw it here so in the else part we can
say that food draw g okay so there it is so next is how to
make the checking that the snake overlaps with the food and then the
snake becomes longer and we were going to produce again the snake, the food so
that’s the next task here okay so the next step is to have a checking if the
head overlaps directly with the food so we need to have a method for that so
let’s head back to snake, so here we need to already have a checking for isDead()
and then we need to have another method here you can call it isFoodEaten(),
and its parameter is the food so remember the food is of type the Point
also so internally there is an x and y value here so we need to check the head
so we need to get first the head so as we have done here we get the head using the
snake body ArrayList, index zero okay so if head dot getLocation dot X is equal
to F dot I think there is no, okay so let’s head
back first year we need to return the current location of the food so we need
to create a method public point getFoodLocation() then return, return this dot food location so go back here and then f dot get food
location dot get location dot X so if they are equal then another checking if
head dot get location dot Y is equals to f dot getFoodLocation dot getLocation dot Y so isFoodEaten or we can return it as
true, return true otherwise it is false return false, now we can check we can use
this isFoodEaten in the game engine so let’s go in the update here so let’s
check so if snake dot isFoodEaten the parameter is food so if it is already
eaten we can produce again the food produceFood() and then grow the snake grow the snake let’s test first if the game will generate another food if we eat the initial food here, ok
so that’s it so if as you can see if we collided with the food it means that it
the snake eats the food and generate another set of food. Ok so but the snake
is not growing so we need to add the code for that one ok so let’s go let’s head back to the
snake and then let’s add another a method so we can we can call it a public
void growSnake(), so grossSnake() is basically just adding a point object in
the array list of snake body So snakeBody dot add then
new Point okay the parameter here will be the last index of the snakes we can, int size equals to a snake
body dot size so we can get the last position based on
the size minus one where we can we can the deduct it already here, dot get
location dot X, comma, so the same, snake snakeBody dot get size dot get
location that Y, okay so that’s it So we are just appending in the
last portion of our ArrayList the next body of the snake, so if the snake eats
the food we can call it here snake dot growSnake(), run the program okay so if we We need to eat at least ten so that
we can see if the snake now is growing yeah it is growing now okay so the next part is that when this
snake is long enough there’s a possibility that it can collide with its
body so we need to add that code because currently there’s none so as you
can see I can overlap my own body and do not die so we need to have some logic
for handling that okay. Okay so our next checking is the collision for the body
so we can we can add it here in the isDead() because that’s the same if the head
collided with the body it is considered as dead. So we can we need to look for
for the entire length of the body because we need to check if he had
collides with any part of the body so we need to check one by one if the location
of the head is equals to the one of the body parts of the snake so if head
dot X equals two snakeBody dot get, dot X and then head
dot Y is equals to snakeBody dot get i dot Y, then return true so there’s no
I just don’t need to have a break here because the return will break the isDead so let’s check ok so if I’ve eaten the food okay okay okay so let’s make it
long enough to collide its own its own body okay so let’s try okay so so I died
when I collided with my tail okay so that’s that’s the correct one so our
next part or our next task is to have a score so currently we don’t have any
score yet so we need to show to the player how many foods that the snake
already eaten so let’s create a variable here foodEaten is equals to 0 so
if it is initialized we can set it again with zero okay then let’s print it here so G dot let’s set color it to blue, sorry
blue then G that drawstring score plus foods eaten so let’s show it then X and
then game form dot height, minus lets say 20 now we need to increment the food seat
and whenever the snake successfully eats a food so lets delete these first and then
go here so foods eaten plus plus so let’s try so as you can see there’s a score but
it’s a little bit lower so we can we can make it higher so let’s make it 40 okay so on so as you can see when we eat
the food, so the score increments by one okay so that is the
next test so our last us is how how are going to save this core so let’s say I
already ate overlaps away what happened with that one let’s check the second
again okay so if our last us is to create a high score say being the high
score so the moment that let’s say I already have four as a score if I gave
upward if I died and game over and when I press a restart I can see the high
score here in the lower right portion of our game form so we need to save it in a
separate file and increment it so if the if my current score is much greater than
the high score we need to update the high score with the current high score
that I have right now so let’s say I already have five so the high score will
be save as five or six or seven so that is our next task okay okay so our next task is to create a way
to save this corner and the high score in a file so it means that when we start
the program it will create a file and save the initial score there and
whenever we close the program and start again we need to have a way to save this
corner and load the appropriate high score if there is any so we need to
create two functions here to load or to generate the file and save the high
score initially and get the high score so the first method here is the read
high score okay so we need to specify a default location
in our in our program so let’s say so I have a here in the documents so we can
say desktop okay so see if you are using a map the root directory is the forward
slash sign then you the folder users then the user and then the folder under
that user which is desktop because I’ll say the high score dot txt so if you’re
using Windows you can put the exact parameters you like like this one so
let’s say C we’re using Windows seeing C users let’s say my user My Documents My Documents and in the text file so
high high score the txt so since I’m using Mac I’m using that
this format okay so I’m gonna annotate this for Windows user okay so we have
the default location and let’s create a line which is now and then the value
let’s default it to zero okay so let’s create a try and attach because the
class that we are using is required to be defined inside they try try and catch
the block so trade me file reader so file reader sequels to new file reader
so it will do that the file so let’s change this one file name so if the file
name the statics is the file reader well created for you with an empty contents
so we need to import it so it is under the Java that i/o file reader okay next
is we need to have a buffered reader buffered reader read as it goes to new
buffered reader and the parameter should be the file reader again we need to
import this one so import buffered reader from Java that IO mmm-hmm okay so listen this equal sign
next we need to look so while line sorry while while lines equals to read that
triggered that read line it’s not equals to now it means that it
while it can read the line we can we can put the the whatever value that this
text file has so this is the reading of our file and then whatever the bodies
will be appended in the val which is a string next we need to close the
reader’s reader that close okay so if val is not equals to null and not well
that equals to empty okay we need to convert it to integer as a return
integer that value of pop so the integer that value off will convert the valve
into a integer type because our return value is integer here so if there’s an
error we can so e^x that Princeton trace to show the what are the methods that
causes errors in this method and then if we need to return case this is the
return now if the valve has enough value or it
is an empty value we can return zero okay so that’s it so the next method
that we need to create is the update high score so this method will update
the high score whenever the current high score the current score is more than the
high score so again the same file name I can copy it here this is the location
you will see that this file will be created when we run the program so next
we need again the try and catch block okay so we need the final writer suppose
to a new fine writer file writer is the class that we use to write the file
alright contents in a text file okay so again we need to import it under
the in Java that IO then we the buffered writer buffered writer of writers goes
to new buffered writer so the parameter is writer this one and
then we need to import it again the password writer then we can now write
whatever the value so since the foods eaten can contains the score that is the
parameter that we need to add then we need to convert it to string so that’s
why I mean we appended an empty string so if if you pass it like that this one
I think will generate an error maybe so then we need to close the buffered
writer and then print stop trace for some errors we have one okay so we’re and we are going to call
this two methods so we need to call them in okay so here in our pain component so
here in the is game over so we need to get the score and score sequels to read
high score and then if scores equals to zero need date high score this is the
the first time that the score is being loaded else if if foods eaten is greater
than the current score we need to call again the update high score then we need to show need to show also
the high scorer here after this one so we need to copy the drawstring high
score is get high score and then it should be appear in the right lower
right corner of our form so be informed that with – let’s say 100 hey that’s
right mm-hmm have an arrow where it is so we have the
get high score the method is undefined for the
undefined so we have here read read high score and sorry not not
get high score so read high score it’s run so that’s let’s test the program okay so our high score is ups have a
narrower what is this we have the B print stuck tracer oh it’s very long no such file or a directory so we have say if it is just started maybe we can we can generate or we can
because this one read I score we need to we need to call the read high score
first wait read high score so if there’s no file for that one Sara died scoreless
empty then if we if we if the score is equal to zero at the high score so
there’s no file with the same name might think okay let’s let’s check nothing so
we don’t have any file here in the desktop users let’s check again the air door mmm-hmm here in high score you need to
create the file first before we can generate okay so we have we have already the
Eurydice corner so do I think there’s a problem here
we need to I think we need to add a because the moment that the snake died
that’s the time that the file will be created so let let’s add another touch
here so file not found exception find that found you need to import it in
Java that IO and we need to know we need we don’t need to print stuck trace we
can output a much user-friendly error message there is a problem loading the
file or this one will be find that phone okay there’s a problem reading the file or
updating updating the file yeah that’s right may already have been a high score which
is two so lets me get much higher let’s say four five okay six then let’s kill
this thing it’s just the one hmm all right okay so let’s run it again okay this is this the correct one so I
have this corner one file not found as you can see in the back that is file not
found and the snake died great there’s a problem loading the file so
what is the let’s check if the file is created okay so we have the one I scored
that txt and it doesn’t have any value maybe we can if he is it’s game over so we can update
the hmm maybe we in our error here so produce the foods eaten is the correct
score okay let’s go back here I think we have a problem in here to me to convert
it to string okay let’s try it again let’s write again and so let’s make it at least two okay
okay so we have now the high score here appears as correct score so let’s make
this snake a lot longer so – so notice the score
so I say about three for five so if the snake dies the high
score should be fine okay so that’s correct so we have
successfully updated the high score and save it in a in a file so as you can see
here okay so did this is the score so fine so now a snake game correctly loads the
high score so let’s try it again let’s create a much higher score so 3 4 5 6 ok ok so we have now the high score as 10
so that’s it that is the snake game that is a little bit complete so that’s it
this is our completed snake game in Java so now guys I want some feedback from
you you can suggest additional improvements on our simple snake game
just write it in the comment section below and I will code it and record the
video and that it features that you want ok so thank you guys for watching and
don’t forget to subscribe this channel for more programming tutorials see you

11 thoughts on “Part 5 – Snake Game Tutorial – Generate Food, Body Collissions and More.


    This is basically the final snake I have.. my bro showed me a bunch of things and
    told me how to make the walls without trouble, they work and the food doesn't spawn in them 🙂 and I think I'm gonna keep learning from these code examples and also he told me I should start commenting and explaining every single bit of the code myself unit'l I get a better understanding of what does what explicitly

Leave a Reply

Your email address will not be published. Required fields are marked *