Part 4 – Snake Game Tutorial – Snake Movement Control and Collision Detection

Part 4 – Snake Game Tutorial – Snake Movement Control and Collision Detection


Hello guys, welcome back to our snake game tutorial in Java in this video We’re going to add some refinements in the improvement of our snake and some collision detection between the Our game form borders. We’re also going to add some Pressing of Start to start the game so that when we run the program it will not go into move Immediately we need to press a start and then we’re going to add some restrictions in the movement of the snake So if we press the left and the snake is going left. It should not be going right immediately It should be going up first or down first before going to the right and vice versa We’re going to add some game over screen and “Restart the Game” options so that if the user Died because it collided with the border the user can restart it by pressing the button R Okay, so let’s start programming. So the first thing that we need to do is to add some Variables that will hold the logic of our game. So we need to add some boolean variables Private boolean isGameOver So this by default will be false and isStarted is equals to True so isStarted will be Executed once when we start the program, that’s the time that The game will be, or isStarted will be evaluated So what we need, what we need to change first is Here in our paintComponent we need to add some logic here first, so if isStarted So if the user just started the game You need to print in the form so let’s say let’s set for a color, setColor dot gray and then g dot set or drawstring So press Enter to Start the game and then let’s Print So, let’s make it in the middle so divided by 2 minus 100 and Then the The Y will be almost the same game Form dot height divided by 2 Then we need to Add some listener if the user press the Enter So we need to check it via the keyboard Object if keyboard dot isDown KeyEvent_VK or sorry dot VK_Enter so if the user presses or pressed the Enter So we need to make the isStarted to be false Okay, so if if it is game over so let’s add something here setColor again, let’s make it again gray Sorry, drawstring So game over then that’s out put it in The middle also And then below that word game over that’s huh Print the press R to restart the game So this time It should be The same but Below the message GameForm dot width divided by 2 minus, lets say 18 Otherwise if the user is not started And it is not it yet game over. So let’s draw the snake. So this three Condition the condition here. We’ll This is our main logic in our game so for the game loop it will going to execute and Depends on the values of this variable But we can see the press enter to start the game or a game over message. So let’s test if We can see those messages, okay, so press ENTER to start the game Okay, so I press Enter, but the snake is already moving right now so what we need to do is to separate the initialization of this variables and the starting of the actual game so Let’s create another method In it for initialize So in the initialization that is the time that we need to grease up the snake and the food so Let’s set the direction and the position of our snake okay, and then let’s initialize the food and the snake here And initialize so we need this if we press the The R for a restart of the game so let’s try Okay So let’s try again, so I press Enter I Think it is running already Maybe we need to initialize it if We press the Enter so we can call the initialize here initialize() And then common we initialize in the constructor That’s An error So it’s a null pointer exception In our game engine Okay, so that direction doesn’t have anybody so we need to make the direction to be Initialized first, so we need to copy the Direction is equals to direction dot down. Let’s try again Another error Our snake it’s not yet initialize Okay, so we need this Code to be in our constructor and then remove this comment So the thing that we need to initialize is the default direction so let’s start by the default direction which is down and then and then the default the position of our snake is 270 by 270 Try again Okay, press Enter, let’s try again I Press ENTER to start the game, okay So That’s the first part. So we need to add For the next one we need to add some border collision to check if the snake can be Can die if it collided to the border of our game form? Okay, so we have created the initial messages as I By pressing the enter will going to start the game now we need to Check if the snake Collided with the wall So as of right now the wall that we consider is like this The actual border line of our reform. So this is the right wall The top or the left wall and our bottom wall So, how are we going to check if the head collided with one of those walls? So to do that Let’s go back here in our model So let’s say we have a wall. So let’s add some color to Visualize the wall Okay So let’s say this is our form so the We can borrow it so the initial Or the top left the topmost Leftmost corner of our wall starts at y 0 or X 0 and y 0 and Then it increments based on its position so this X 0 and y 1 Sorry You can use this one Okay So let’s add at least two position here I Said let’s say that is the coordinates of our wall. So let’s say the snake is heading towards the left wall and it reached the The leftmost Wall, so it it just touched The head just touched the wall but the coordinates are different because this one will have a coordinate of our wall will have a coordinate of X 0 and y Let’s say Y 5 While our head will have an X of X 1 and Y of 5 Though they have the same y Y-axis, they have different x axis. So this is not considered as dead. So if if the user is fast enough to press the W for up or S for down The head might be go over here or over here So So it means that it avoided to be collided with the wall, so what is the thing that we considered as collided if the head It’s something like this one, so if the head is the same as one of the coordinates of our wall So let’s say now the X the head Has an X of 0 and Y is 15 That is considered as dead, so snake now will be dead based on this condition this is this is the one that we need to check what about if the snake so let’s say It goes beyond the wall, so this is possible because our game has a delay of 50 milliseconds, so there’s a chance that the checking Or while while the head is Directly Collided with the wall. There’s a chance that the game engine might not check it because of a delay of 50 milliseconds so there’s a possibility that the head might go over here or beyond so this is one of the Conditions to need to check if the X if the X or if the head’s X is Equals to zero or less than or equal to zero. It means that it is Collided with our left wall now if the head is more than Let’s paste it here and Now if the position of our head is something like this As you can remember in our game our game form only Or have the size of 600 by 600. So it means that our this one will be 600 The the width and the height is 600 so and That width is composed also of a pixels. So it means that the overall length of this The height of our game form is 600 600 pixels So it means that if the head is more than the 600 the snake is also dead because it goes over the height of our Snake now if the condition is something like this Let’s copy again the head and copy the body Okay So if if this is the case it it means that it collided with our the right wall so the the same is The same condition is true the X of the wall for the right is equals to the X of the head and also the Y and another case is that if the head is Equals to zero equals or Less than to zero. It means that it collided with the top wall so those are the conditions that we need to check for For us to say that the snake is the snake collided with the wall and is now dead so to do this we need to go back here in our code and then Add another function in the snake class, so let’s create a function Public boolean isDead So as you can see, it’s like asking a question is this name already dead or is it dead? so we have some checking here, but first we need to get the The position the exact position of the head when we call this Function isDead(). So let’s pass that value By calling the snake body dot get and then index 0 Okay, so let’s let’s get the head so So by accessing the index 0 the index 0 is the initial point in our ArrayList snake body So this is the head So since the snake body is composed of ArrayList of Points we can get the one object and then put it in a separate object which is we created here as head and Of type point then we can check if the head dot getLocations dot X plus 10 is greater than or equals to Game form that since its That is X such that should be win Or Or head dot get location dot X is less than or Equal to 0 or is less than 0 we can check it that way Okay, so So let’s add some comment here so this is Collided with the right wall and The condition the lower part is Collided with the left wall. So if these conditions are true We have an error so return true So if either the X is more than The game the game form width or it is less than zero then it is considered as dead So if head then let’s check for the top and bottom wall it’s less than equals to game form dot height or Head sorry head Get location that Y is less than zero So let’s return true So this one is Collided with the bottom wall and this one Collided with the top wall So if both if returns false we can return isDead as false Okay, so how can we use the isDead so let’s go back here game engine In our update we didn’t We need to add a condition of if not, so I’ve used the exclamation point so it means that we’re going to reverse the boolean value of is game over So if not isGameOver So it means that if it’s not yet game over We need to execute these codes So if it’s not game over we can continue the playing but if If the snake is dead So this this isDead() is the function that we have created here. So this one So if the snake is dead we can set the isGameOver to false. Not true and then Okay, so that’s it. Now that the snake is gameover And then let’s add some checking for the restart So if the current status isGameOver and The user press the R We can initialize it, initialize It means we it means that we have restarted the game so lets try. Okay So if we collided in the wall top wall first nobody so we have a message here, press R to restart the game, R Is it really R, wait isDown VK_R, if it is game over If not Okay, so we have So if the user press The R we need to initialize it and then set the isGameOver to False again. Okay, so let’s try Okay, so top wall, okay so press R to restart the game R So we still have some trailing there, okay, so we need to delete We need to delete those remaining snake body before we can okay, so in the initialize we can maybe When we initialize the snake, So, let’s call it again so new Snake So that we can remove the trailing tails of this snake if it died, okay? So that’s it Okay so our last Task for this video is how to control the snake so that it will not go Directly from right if it is moving to to left so we need to have some checking for those movements so let’s say if I am moving right like the pressing of A will be Disabled so you need to go up first before pressing the A for the left Or down first and then press the D for the right So no Movement something like this So you cannot move from upwards to downwards Immediately, so you need to move left or right then downwards So it’s it likes you’re moving 360 degrees before Okay, so let’s program the restriction so again as these two variables are Are doing it is controlling the whole game flow We need to add another Boolean variables to control or restrict the movements of the snake if it is moving in a specific direction So let’s create two variables restrictLeftRight Let’s say it’s false Then restrictUpDown which is false again Okay, so by default if the if the snake is currently moving downwards the restrictUpDown will be True and the restrictLeftRight will be false so that we can move either left or right only you cannot go up Or down because it is currently going down so You need we need to add Another method so So we have already checkSnakeMovement() So let’s add another method here. It’s private void restrictSnakeMovement() So if Direction is equals to direction dot left or Direction is equals to direction dot right. Okay So we need to restrict the Or the restricteftRight will be true Sorry restrict And the restrictUpDown Will be false. So it means that you can move the You can move either up or down if you are currently moving from left to right then another if again if their action is equals to Direction dot up or direction is equals to direction dot down Okay, so we can reverse the meaning of For the state of this variables so this one is false and this one is true Alright so now we need to Update this checkSnakeMovement() So you cannot you cannot press you cannot press the VK_A and VK_D if you are already moving in the in that direction or in in the left right direction so we can add another if here if if restrictLeftRight if this is true What are the movements that are available for us? is this one Right so we can copy here Okay else if restrictUpDown We can we can do the Therefore right this one you can comment it first checkSnakeMovement(), restrictMovement(), so we can we need to call the restrictMovement() here restrictSnakeMovement() Then change or maybe We can call first the check snake movement before we can restrict So let’s try So R So up. Okay. Yes we Cannot You cannot move left just down, lets try again, so let’s say I’m moving left I cannot press the D or The movement to right only either up. Okay good or down I’m up I’m moving To the right they can only move up or down Let’s try again. So I am moving right So down okay right down. Okay, so I am I collided with the wall. Okay, so I try again So that is the movement so that is a correct movement for our snake so it So it needs to turn around before it can move to the opposite direction So if we are going to right you cannot go to left immediately just go down or go up so let’s If you’re going to right you can go up and then left so that you can go to the opposite side Okay, that’s it guys in our next video We will make the food to appear randomly in our game and make the snake to eat it and grow So that’s it. Thanks guys for watching If you have any questions about our video today Just write it in the comment section below and don’t forget to subscribe to be updated in these tutorials. Thank you

3 thoughts on “Part 4 – Snake Game Tutorial – Snake Movement Control and Collision Detection

  1. After i'm done with the code at 24:00
    I sometimes can't press start to start the game.
    It just doesn't work but most of the time I can whats going on?
    EDIT: I figured out when it doesn't work.. its when I press anything but enter before I press enter

  2. I figured it out all on my own bro..
    I went to this code:
    protected void paintComponent(Graphics g) {

    super.paintComponent(g);

    if (isStarted) {

    g.setColor(Color.gray);

    g.drawString("Press enter to start the game. ",

    GameForm.WIDTH / 2 – 100,

    GameForm.HEIGHT / 2);

    if (keyboard.isDown(KeyEvent.VK_ENTER)) {

    isStarted = false;

    initialize();
    and then below this I typed in:
    }else {

    initialize();

    }
    so that if I use any other key the game will just initalize again

Leave a Reply

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