Java snake game 🐍

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's going on everybody it's bro here hope you're doing well and in this video I'm going to be teaching you guys how we can create a game of snake using Java so let's get into it if you find this video helpful please remember to Like comment and subscribe your support will help keep this channel running alright guys so snake let's do it let's create a new project go to file new Java project I'll call this project named snake click finish don't create and then let's create three separate classes within our source folder so file new class this class will contain the main method I'll call this snake game and then check public static void main finish and let's create another class file new class and this will be called game frame it will extend the jframe class so game frame extends J frame and we'll also need this import and let's create the last class file new class and this will be called game panel and game panel will extends J panel and it will also implements the action listener interface so we'll need to add these imports as well and if you want you can add unimplemented methods at this point but we'll return to this later so let's create the constructors for these classes we don't need to do so within our snake game class because we have the main method let's create the constructor for the game frame class so game frame and then the same thing for our game panel class game panel then let's go to our snake game class we're going to create an instance of our game frame class so I'm going to show you guys a shortcut so in past lessons what we've done is type in the name of the class such as game frame and then I usually name this something such as frame equals new game frame so one shortcut is if you don't plan on using this named instance of another class like game frame you don't actually or necessarily need this portion of this line of code so I don't really plan on using this frame for anything else so what we could do is just say new game frame and this will still create an instance of our game frame so from now on I'm going to show you guys a few shortcuts here or there so let's head to our game frame class and let's do something similar with our game panel like what we did with our game frame so what we've done before is say something such as game panel panel equals new game panel and then we would take this dot add panel so instead what we could do is that I'm just going to copy this portion get rid of this named instance and then place this dot add new game panel and this would work the same so that's another shortcut you guys might be interested in all right so let's finish constructing this frame so this and we'll add a title so set title I'll call this snake this dot set default close operation jframe dot exit on close this dot set resizable false this dot pack so if we add components to AJ frame this PAC function is actually going to take our j frame and fit it snugly around all of the components that we add to the frame and this dot set visible true and if we want this window to appear in the middle of our computer screen we can use this method this dot set location relative to and then pass in no so right now we won't really see anything but this is going to appear in the middle of our computer so that is it for the game frame class we're going to finish everything else within the game panel class we have our let's declare all of the methods that we'll need so after our constructor let's create a method called start game so public void start game and then another method called paint component so public void paint component and then as a parameter we're going to set up graphics G and then we'll have a draw method so public void draw and we will also need a parameter graphics G all right just a few more so we'll need a move function why is this giving us a problem okay so make sure to get those imports as well so after the draw function let's add a move function so public void move so with snake according to the rules at least I guess the snake eats apples so that's basically how you score a point so we'll have a method called public void check Apple I don't know why they called it Apple but okay whatever and we'll want to check for any collisions so public void check collisions and then we'll want a game over method so public void game over and we're going to set up a parameter of graphics G then we have our action performed method and lastly we're going to create an inner class so public class my key adapter and this will extends key adapter and this will just have one method so let's add a note that we're overriding a method so an override and the method is public void key pressed and the parameter is key event and we'll just call this B and add all the imports actually we should take care of that next so at the top of your program for this class at least make sure you get everything related to java.awt as well as Java dot aw t dot event so we can take out a few of these and let me check to see what else we would need so we'll also need Java X dot swing and then Oh swing not sing and then lastly import Java dot util dot random and we are good all right so here are all the methods that we'll need the constructor for our game panel start game pink component draw move check Apple check collisions game over action performed and inner class called Mikey adapter or whatever else you want to call this with one method called key pressed so if you have everything we're good to go then so before the constructor we're going to declare everything that we're going to need for this program so let's begin with the screen wit so I'm going to make this static final int screen underscore width and I'll set this to 600 let's do the same thing for a screen Hayate so static final int screen height all right so with snake we kind of have these things called units I would say we're going to have some sort of matrix like how big do we want the objects in our game so I'm going to call this unit size and it'll make more sense when we actually create a visible game panel but for now let's just type in static final int unit size so how big do we want the objects in this game and then we'll want to calculate how many objects we can actually fit on the screen so static final int and we'll call this game underscore units and what we'll do is set this equal to screen underscore width times screen underscore height and then just divide this by the size of the units so unit underscore size then let's create a delay for our timer that we're going to implement later so static final int delay and when I tested this 75 was fairly quick so the higher the number for your delay the slower the game is and vice-versa so for this next part we're going to create two arrays an array called X and another called Y these arrays are going to hold all of the coordinates for all the body parts of our snake including the head of the snake so let's create two arrays final int x equals new int and for the size of this array I'm just going to set this to whatever our game units is because the snake isn't really going to be bigger than the game itself and then let's create another array called Y so this array is going to hold all of the x coordinates of the body parts including the head of our snake and this one is going to hold all of the y coordinates and let's set the initial amount of body parts we want for the snake so inte body parts and maybe let's set this to six so we'll begin with six body parts on the snake and let's create well declare an integer called apples Gaytan and this will initially be zero int Apple X this will be the x-coordinate of where the Apple is located and it's going to appear randomly each time that the snake eats an apple and int Apple Y for the Y positioning then we'll want a direction we can easily do this with a character value so char direction and we can initialize this to something or set this to something so let's have the snake begin going right when we start the game so we'll have our for right L for left you for up or D for down so I'm just going to have the snake begin by going right and then we'll want a boolean value called running and we'll set this to false to begin with let's declare a timer called timer and an instance of the random class called random and that is everything that we need to declare before the constructor so let's go to the constructor next and the first thing we'll do is finish creating this instance of the random class so random equals new random and we're going to set the preferred size for this game panel so this dot set preferred size and we're going to pass in a dimension but we'll just say new dimension and then within the parentheses of new dimension we can pass in some arguments such as the screen width and the screen height so screen width and screen height let's set the background color so this set background let's say black color black and we'll want to set the focus ability so this dot set focusable true we're going to add a key listener so this dot add key listener and we're going to create a new my key adapter alright so when we finish constructing this game panel we're going to call the start game method so start game and we'll head to the start game method next I forgot to add a method so let's do that I'll add this after the draw method so we'll want to populate the game with an apple so we can actually score a point so let's create a method called public void and we'll call this new apple all right so that should be all the methods that we need but yeah I did forget about this one so when we start this game what we're going to do first is call the new apple method to create a new apple on the screen for us let's take our boolean called running and set this equal to true because it's false to begin with and then we'll finish creating this instance of our timer so timer equals new timer we're going to pass in our delay value so this will dictate how fast the game is running so 75 is somewhat brisk and we're going to pass in this because we're using the action listener interface and then lastly we're just going to take our timer and use the start function and that is it for the start game method so let's go to paint component and we're going to type in super dot paint component and pass in G so there's one thing I want to explain to you guys let's just run this once so here are the dimensions for our game it's 600 by 600 and each item in this game is going to have a dimension or dimensions of 25 pixels for the width and the height so that's a little difficult to actually see on this game so what I'm going to do is turn this into a matrix or grid just to help us visualize things so this part is completely optional but I'm just going to turn this into a grid so it's easier for us to see things so I'm just going to create a for loop within the draw method for int I equals 0 and I'm going to continue this as long as I is less than our screen underscore height divided by the unit underscore size I'm basically going to be using this for loop to draw lines across our game panel so it becomes some sort of grid and then I'm going to increment I by 1 each time so we're going to draw lines across the x-axis and then y-axis so we'll use the G dot draw line method and we're going to pass in some starting coordinates and ending coordinates so since we have this in a for loop we're going to utilize this index of I so for the x position I times unit underscore size for y2 we're going to set this to 0 for X 2 we're going to type I times unit underscore size and then y2 the screen height so let's take a look at this so here are all of these spaces along the x-axis so let's do the same thing for the y-axis so it's a similar process G draw a line but we're going to change a few things around so for this first argument this will be 0 then I times unit size for the second the third is going to be screen underscore width and the fourth argument is i times unit underscore size so let's take a look so here is our grid so each item in this game is going to take up one of these spaces so if we were to increase the unit size let's say 50 well all of the items in this game are going to be larger than so that's what the purpose of the unit size is how big do we want the items in this game so for now I'm just going to keep in this for loop just to help us develop this game but by the end we'll probably take out this grid or you can keep it in doesn't matter so let's work on generating the coordinates of the apple within the new apple method the purpose of the new apple method is to generate the coordinates of a new apple for us whenever this method is called so anytime we begin the game or score a point or eat an apple basically so let's take our variable Apple X so this is the x coordinate of our Apple equals random dot next int so we're going to have this Apple appear someplace along the x-axis so the range is going to be our screen underscore with however we're going to divide this by the unit underscore size so it's as if we're going to get one of these positions so this will be one two three four and then we'll just continue on like that but let's also cast this as an integer just to be safe so it doesn't break this program and then we're going to multiply this at the end by our unit underscore size and then let's do the same thing for y so apple y equals random dot next int then we're casting screen underscore height this time divided by unit size and then after this is complete multiply this by the unit size because we want this Apple to be placed evenly within one of these item spots I would say alright so then let's draw this Apple on the screen and it's going to appear randomly every time we actually draw this so let's head back to the draw method and we're going to draw the Apple so first let's set the color so G dot set color and we'll set this to red I guess it could also be like a green apple too but let's set it to red for now because I want the snick to be green so g dot set color and then let's use g dot fill oval for a circle so we're going to pass in the coordinates Apple X Apple Y the width and the height and we're going to pass in the unit size so this is how large the Apple is so let's run this so here's that Apple it should fit within one of these grid spaces and be aligned up perfectly within it and every time we run this it will most likely appear in a different spot so we know that the Apple is working done and if you were to go back and change the item size let's say back to 50 well all of the grid spaces will be larger same thing with the items such as the Apple and the body parts of the snake as well but I'll just keep this at 25 but I wanted a visual demonstration of how the unit size kind of plays into this program so let's work on creating the move method of this game panel class so we're going to be moving the snake with this method first we're going to create a for loop to iterate through all the body parts of the snake so we'll have int I 4 index and stuff that's equal to the amount of body parts that we have for our snake so I equals body parts we'll continue this as long as I is greater than 0 and then we'll decrement I by 1 after each iteration of this for loop so what we're going to be doing is actually shifting the body parts of our snake around so we'll take X array X at index I and we're going to set this equal to our ax at index I minus one so basically we're shifting all the coordinates in this array over by one spot basically and let's do the same thing for y so Y at index I equals Y at index I minus one so let's also create a switch that will change the direction of where our snake is headed so we'll create a switch and we're going to examine our direction variable and direction is a character value so we'll have this store the letter R for right L for left you for up and D for down so we're going to create a case for each of these possible directions so we'll have a case you for up and what we're going to do for this case is take our array Y at index 0 this is the y-coordinate of the head of our snake and we're going to set this to y 0 minus our unit underscore size so it's going to go to the next position and then we will break and then let's do the same for each of the cases and make a few changes so case D will equal Y at index 0 equals Y at index 0 plus the unit size and let's create one for L for left so we're going to take our x array at index 0 equals our ax at index 0 minus the unit size so this will make us go to the left and then case our for right X at 0 equals x at 0 plus the unit size and that is it for the move method so we just need to draw the snake we need to draw the head and we need to draw the body so let's go to our draw method and fill in these things so let's draw the head of the snake and the body so we're going to create a for loop to iterate through all of the body parts of the snake so for int I the index and we'll set this equal to 0 we'll continue this for loop as long as I is less than the amount of body parts that we have and then we're going to increment our index by one after each iteration so if I is equal to zero then we're dealing with the head of our snake we can either draw this the same color or we can draw it a different color so if I is equal to zero let's take G and set the color to color green and then let's take G and use the fill rect for rectangle method and we're going to set X to our array X at index I and then our coordinate Y will be our array Y at index I as well and the width and height are going to be our unit size so I'm going to copy this and we're going to change width and height to unit size so if I does not equal zero we're dealing with the body of our snake so else let's take G again and set the color for the body but I'll pick a different shade of green so instead of saying color dot green or so I'll just say new color and type in an RGB value so I already picked one out one that was decent was 45 and 180 and zero and then we just need to use G that fill rect and we can keep that the same so let's run this and take a look at what we have so far here so here is the head of our snake but we cannot yet see the body so we'll actually need to call the move function so we're actually going to call that within the where is it the actionperformed method so we're going to fill in a few things within this method next so we're going to check if our game is running so if it is running this is going to be true the first thing we'll want to do is move our snake and then we're going to check to see if we ran into the Apple so check Apple then check collisions and if this game is no longer running we're going to call the repaint method okay let's try this so here's our snake it's actually moving pretty fast but it's just going to go off the screen so let's set up the collisions next we're first going to check to see if the head of our snake collides with its body at all so we need to iterate through all of the body parts of the snake so we're going to do this with a for loop so we'll take int I equals the amount of body parts that we have and we're going to continue this as long as I is greater than zero then we are going to decrement I by one after each iteration so what we're going to check is if and you might have to put this within double parenthesis X at index zero that's the head of our snake is equal to X at our end x and y at index zero is equal to Y at index I so if this is the case that means the head collided with the body so we're going to take our running bullion value and set this to false so basically this is going to trigger a GAMEOVER method for us later on so let's also check to see if the head of the snake touches any of the borders so that will also cause a game over so I'm just going to add a comment here just to help us separate things so this checks if head collides with body and this next portion will check if head touches left border so all this is is if X at zero is less than zero then all we do is set running to equal false now let's check to see if head touches right border so I'm going to copy this and we're going to check to see if X at index zero is greater than our screen underscore width and then we'll have running become false then so let's check to see if head touches top border so we're going to examine the y-coordinate this time Y at index zero is less than zero and then check if head touches bottom border so if y at index zero is greater than our screen height and then lastly we should stop the timer so if running is false timer stopped and that is everything for the check collisions method so let's run this so the snake should stop after it reaches this border which it did so if the head of the snake passes over one of these four borders or if the head of the snake touches any of its body parts at least then the game is going to be over basically it so let's actually control the snake so we're going to fill in a few things within the inner class of Mikey adapter so head to the key pressed method and we're going to create a switch that's going to examine the e key event and we're going to get key code so within the switch we're going to have four cases one for each of the arrow keys so let's begin with the left arrow key so case key event dot VK underscore left and we don't want the user to be able to turn 180 degrees in the opposite direction otherwise they might get a game over because they're going directly into themselves basically so we want to limit the user to only 90 degree turns so we're going to check to see if the direction but I misspelled it if Direction does not equal r4 right then we'll let them go left Direction equals L and let's make a few other cases oh and we should break afterwards do don't forget about that so case key event VK ripe if direction does not equal left we'll change the direction to right so R and then case key event VK underscore up if direction does not equal D for down will change direction to you for up and lastly VK underscore down if the direction does not equal you for up we'll set the direction to D for down so with this we should be able to control the snake now let's give it a try so I'm going down left up right cool so if I touch any of the borders the game is over let's work on actually grabbing the Apple next so let's work on that method so that is within the where is it the check Apple method there's not much to write here we're going to examine the coordinates of the snake and the coordinates of the Apple so we're going to use an if statement and I'm using double parenthesis for this portion if X at index 0 this is the x position of the head of our snake is equal to Apple X that's the exposition of the Apple and we'll do the same thing for the Y coordinates so change X to Y for this next portion and within the body of this if statement we're going to increase the amount of body parts that we have so we're going to increment this by one you can just type in body parts plus plus we'll take our apples eaten variable and increase this by one so this will function as the score basically and then we're going to call the new Apple method to generate a new Apple for us so let's test this now just to be sure that this is working fine so the body should increase by one it was a little difficult to see yeah it looks like it's increasing by one body part after one Apple is eaten cool so that is working fine so let's work on the game over screen next now within the draw method we're going to surround all of this within an if statement so before this I'll add if running so if our game is running do all of this however I think I'm going to indent everything just so it's a little easier to read so give me one moment all right let's see where this ends got it so if the game is running do all this else we're going to call the game over method so else game over and we're going to pass in G and G is our graphics that we're receiving with this parameter so let's go to the game over method and we're going to write some text on the screen and we are receiving graphics Jeep so let's set up the game over text so let's set the color G dot set color to maybe red so color dot red and the font is well so g dot set font and we will pass in a font instance so new font and pick a style I will pick in curry but choose whatever style you like that's available font bold because I want this bold and a size so maybe 75 so there's these things called font metrics which are useful for aligning up text in the center of the screen so we're going to create an instance of font metrics so font metrics and we'll call this maybe metrics equals get font metrics and then we're passing in G dot get font that looks good so this next part is a little tricky we're going to use G draw string so as arguments we need to pass in a string x-coordinate and y-coordinate so the string is going to be game over and for X I'm just going to paste this and we can take a closer look we're going to take our screen with minus the metrics of the string with game over divided by 2 so these are the metrics and basically this is going to this within the very center of the screen width and then for why this is a little more simple we're just going to take our screen underscore height divide it by two so this will give us the string game over in the center of the screen we're at least close to it yep there we are let's also place the score at the top of the program so maybe we'll place it right up here somewhere and just a save time I'm going to copy all of this code from the game over method and reapply it so I'm going to paste all of this within the draw method and we're going to add this after we draw all the body parts of the snake so we're going to use these lines of code to draw the current score so I'll keep the color is red red for apples I will change the font size down slightly to maybe 40 we'll keep the metrics the same however we'll change the string so let's display score colon space plus our apples eaten variable and then we'll take this this text and place it within metrics dot string width so place this within the parentheses so score plus apples eaten and then we'll want to move this more to the top of the screen so let's take I'll replace this first and take G dot get font and we're going to get size so this should now display the score of our game so let's run it so it says score 0 and it goes up by one every time we eat an apple I would also like to display the score on the game over screen so I'm actually going to copy all of this code that we just pasted here after the changes and I'm going to paste this within the game over method so this will display the score however we might have to rename metrics so I'll have this as metrics 1 and metrics 2 so the score should be displayed now at the game over screen which it does cool alright so let's go over some artistic stuff so we can actually get rid of these grid lines if you want so we actually did that near the beginning of the draw method I'll just turn this into a comment that was more or less just a tool to help us visualize the item size so this should remove the gridlines if you do not like them cool and one other fun thing I realize that you can do is that you can actually have the color of the snake change randomly so this is totally optional though but I thought it was kind of fun to add this line in so what I'm going to do is take G dot set color to new color then we can pass in three RGB values and it's on a scale from 0 to 255 so I'm going to take random dot next int and pass in 255 so we'll get a random number so let's do that with each of these values alright so this is what ends up happening it's not necessary but I thought it was kind of cool to have like a multicolored snake so you can either keep that in or you know take it out if you don't like it there's just something I wanted to mention because I thought it was pretty cool alright so that's everything let's run this one last time so that's the end of this video if you would like a copy of all this code I'll post all of this in the comments down below but yeah that's how you can create a simple game of snake using Java hey you yeah I'm talking to you if you learn something new then you can help me help you in three easy steps by smashing that like button drop a comment down below and subscribe if you'd like to become a fellow bro you
Info
Channel: Bro Code
Views: 545,684
Rating: undefined out of 5
Keywords: Java snake game, Java snake game tutorial, java snake game eclipse, java snake tutorial, java snake code, java, snake, game, tutorial, for beginners, java snake game code eclipse, snake game in java, java snake game, snake game java, java snake, snake in java
Id: bI6e6qjJ8JQ
Channel Id: undefined
Length: 43min 30sec (2610 seconds)
Published: Mon Jul 20 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.