Code Snake Game in Java

Kenny Yip Coding
19 Jul 202342:51

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

00:00

๐Ÿš€ 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.

05:03

๐Ÿ“ 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.

10:05

๐ŸŽจ 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.

15:08

๐ŸŽ 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.

20:11

๐Ÿ” 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.

25:13

โŒจ๏ธ 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.

30:17

๐Ÿ 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.

35:20

๐Ÿ 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.

40:23

๐ŸŽ‰ 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

The Snake Game is a classic digital game where the player controls a line which grows in length, with the tail following the head in an enclosed space. In the video, the tutorial focuses on coding this game using Java, making it the central theme. The game's objective is to grow the snake's body without colliding with the walls or its own body.

๐Ÿ’กJava

Java is a widely-used programming language known for its versatility and portability. In the context of the video, Java is the chosen language for coding the Snake game, highlighting its suitability for game development and educational purposes.

๐Ÿ’กGraphics Library

A Graphics Library provides a set of functions and tools that allow programmers to render graphics, images, and animations. In the video, the built-in Graphics Library in Java is utilized to draw the game's interface, including the snake, food, and grid lines.

๐Ÿ’กJFrame

JFrame is a class in Java's Swing graphical user interface toolkit that provides a top-level window for a Java application. In the video, a JFrame is created to serve as the window for the Snake game, setting the stage for the game's visuals.

๐Ÿ’กJPanel

JPanel is a class used as a container for other components in a Java Swing application. The video demonstrates creating a custom JPanel class, named SnakeGame, which inherits from JPanel to handle the game's drawing and logic.

๐Ÿ’กGame Loop

A Game Loop is a fundamental concept in game development where the game's state is continuously updated and rendered. In the script, a game loop is created using a Timer object set to run every 100 milliseconds, which keeps the game's animation and logic active.

๐Ÿ’กTile

In the context of the game, a Tile represents a single unit on the game grid. The Snake game uses a grid of 25x25 pixel tiles to manage the snake's movement and the placement of food, with the snake and food each occupying one tile.

๐Ÿ’กKeyListener

KeyListener is an interface in Java used to detect keyboard events. In the video, the SnakeGame class implements KeyListener to respond to arrow key presses, allowing the snake to move in the corresponding direction.

๐Ÿ’กCollision Detection

Collision Detection is the process of determining when two objects in a game intersect with one another. The video script describes implementing collision detection to check if the snake's head has collided with the food or its own body, which is crucial for game logic.

๐Ÿ’กRandom Placement

Random Placement is a technique used in games to add variability and challenge. In the Snake game, the food's position is randomly placed on the grid using Java's Random class, ensuring that each game playthrough is different.

๐Ÿ’กGameOver Condition

A GameOver Condition is a state in a game that triggers the end of the game. In the script, the game is over if the snake collides with the walls or its own body, which is checked within the move function and game loop, providing a clear end state for the game.

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

play00:00

hey there hope you're having a wonderful

play00:01

day in this video we're going to be

play00:03

coding the game Snake using Java so what

play00:06

you see here is the final result of this

play00:08

tutorial and to start the game you just

play00:10

need to tap on any Arrow key

play00:15

and you can see we have the snake moving

play00:17

and whenever it touches the food which

play00:19

is in red

play00:20

it will grow its body by one segment so

play00:24

the goal of the game is to

play00:27

grow the snake's body without colliding

play00:30

into the walls and if you Collide into

play00:33

the walls or if the snake collides into

play00:36

its own body the game is over

play00:38

okay

play00:39

so we're going to be coding this game in

play00:41

Java using the built-in Graphics Library

play00:45

so before we begin I just want to

play00:47

quickly mention that I am working on a

play00:49

new coding tutorial Series where I teach

play00:51

you how to make games in Java So

play00:54

currently I'm working on Tic-tac-toe and

play00:56

snake and there will be more tutorials

play00:58

in the future

play01:00

I also have tutorials in HTML CSS and

play01:03

JavaScript for Doodle Jump breakout

play01:06

Flappy Birds Space Invaders Wordle

play01:09

Sudoku 2048 Candy Crush and snake as

play01:13

well so if you're interested and you

play01:16

want to stay up to date on new tutorials

play01:18

make sure you subscribe to this Channel

play01:20

and you can also find this list on

play01:23

kenneopecoding.com

play01:26

all right let's begin so for this

play01:28

tutorial I'm going to be using visual

play01:30

studio code if you want to learn how to

play01:32

set up visual studio code with Java I

play01:35

have a video on that and I'll link it in

play01:37

the description below

play01:39

all right so let's create a project so

play01:42

Ctrl shift p Java create project and no

play01:46

build tools I'm going to create this on

play01:49

my desktop

play01:50

and let's call it snake

play01:54

all right now I have my project folder

play01:57

inside the source folder we have this

play02:00

app.java file so let's open that

play02:03

and the first thing I'm going to do is

play02:05

delete this line

play02:08

alright so now let's create a window for

play02:10

our game so what I need to do is import

play02:15

Java x dot swing

play02:19

okay

play02:21

and then in our main function let's

play02:23

define a few variables so int board with

play02:27

is going to be 600 pixels

play02:30

and into Board height and we'll set that

play02:33

to board width so Board height will also

play02:37

be 600 pixels

play02:39

all right let's create a window so

play02:41

jframe

play02:43

frame is new jframe and let's give it a

play02:47

title so we'll just call it snake

play02:49

let's make the frame visible so frame

play02:52

dot set visible

play02:54

we'll set this to true

play02:58

frame dot set size we're going to set it

play03:01

to board width

play03:03

Board height

play03:05

so this is going to be a window that is

play03:07

600 pixels by 600 pixels

play03:10

let's do frame dot set location relative

play03:14

to null so this is going to open up the

play03:18

window at the center of our screen

play03:20

frame that's sizable

play03:23

we're going to set this to false

play03:25

and then frame dot set default closing

play03:29

operation we're going to set this to

play03:31

jframe dot exit on close

play03:36

so this is going to make it so that the

play03:39

program will terminate when the user

play03:40

clicks on the x button on the window

play03:44

all right let's run our program

play03:46

and you can see we have a window

play03:50

so now that we have our window what we

play03:52

need now is a jpanel so that we can draw

play03:55

our game so instead of creating a jpanel

play03:58

here I'm going to create a new class

play04:00

that will inherit the jpanel

play04:03

so over here in our source folder I'm

play04:06

going to create a new file and I'm going

play04:08

to call it snake game

play04:12

dot Java

play04:14

so now we have our snake game file

play04:17

and let's add some import statements so

play04:19

import

play04:21

java.awt dot asterisk

play04:24

import

play04:27

java.awt.event dot asterisk

play04:30

import

play04:31

java.util Dot arraylist

play04:36

so this is going to be used for storing

play04:38

the segments of the snake's body

play04:41

import

play04:42

java.util dot random

play04:45

so this is going to be used for getting

play04:48

random X and Y values to place our food

play04:51

on the screen

play04:52

finally import Java x dot swing dot

play04:56

asterisk

play04:58

okay so those are all the import

play04:59

statements that we need

play05:02

so in our class I'm going to extends the

play05:06

jpanel

play05:08

so basically we are inheriting here and

play05:11

for those of you who don't know what

play05:12

that means we are creating a new class

play05:14

called snake game that will take on the

play05:17

properties of Jade panel so basically

play05:19

it's a version of jpanel with more

play05:22

things that we can add

play05:24

all right so now for our snake game

play05:26

Let's create some variables for the

play05:29

width and height

play05:34

let's also create a Constructor

play05:37

snake game

play05:40

and this is going to take in two

play05:42

parameters so board width

play05:45

and Board height

play05:47

so here I'm going to do this dot board

play05:49

with

play05:51

is equal to board width

play05:53

and this dot Board height is equal to

play05:56

Board height

play05:59

so the reason why we need the this

play06:01

keyword is to distinguish the two

play06:04

boardwifts so we have one as a parameter

play06:07

and another as a field or a member of

play06:10

the snake game class so to distinguish

play06:12

the two we say this dot board width

play06:15

meaning the board width that belongs to

play06:18

this class

play06:20

so now we're going to take the board

play06:22

width and Board height

play06:24

and set preferred size to new dimension

play06:29

this dot board with

play06:32

this dot Board height

play06:35

let's set the background of the panel to

play06:38

color dot black

play06:43

and then we're going to go back to our

play06:45

app.java file

play06:47

and we're going to create an instance of

play06:49

the snake game

play06:51

snake game is equal to a new snake

play06:55

game

play06:57

and we need to pass in the two

play06:59

parameters so board width and Board

play07:02

height

play07:04

and then we're going to take the frame

play07:06

and add the snake game

play07:10

so if I run the program

play07:12

you can see we have our snake game which

play07:15

is a j panel inside our frame now

play07:18

there's an issue and that is we set the

play07:20

size of our frame to 600 by 600 what

play07:24

that includes is this title bar over

play07:26

here where it says snake essentially

play07:29

this panel is actually not 600 by 600

play07:32

pixels it's a little less than that

play07:34

because of this title bar

play07:36

so to resolve this issue we just need to

play07:38

do frame dot pack so that it will place

play07:41

the jpanel inside the frame with the

play07:44

full dimensions

play07:46

okay and we don't really need the

play07:49

sidebar anymore so I'm just going to

play07:50

collapse that

play07:51

so here you can see our snake game it is

play07:54

600 by 600 pixels and what we need to do

play07:57

is we need to define a tile size so I'm

play08:02

going to Define it as 25 by 25 so that

play08:04

is the size of one square and basically

play08:07

we are partitioning the 600 pixels into

play08:11

24 columns and 24 rows so that whenever

play08:15

we move the snake it moves over one tile

play08:18

or one square instead of the exact pixel

play08:21

number so it is 25 pixels by 25 pixels

play08:25

so when the snake moves over to the

play08:27

right it should move over 25 pixels and

play08:30

if it moves over to the right again it

play08:32

will move over 50 pixels and then 75

play08:35

pixels

play08:36

100 125 and so on

play08:40

so here I'm going to define a tile size

play08:43

and set it to 25 pixels

play08:46

and so we're going to create a new class

play08:48

to keep track of all the X and Y

play08:50

positions for each tile so

play08:54

let's create a new class and actually

play08:56

I'm going to create it as a private

play08:58

class

play08:59

so that only the Snake Game can access

play09:01

this class so private class tile

play09:05

and x and into y

play09:08

and then let's create a Constructor so

play09:10

tile into X into y

play09:15

this dot X is equal to X and this dot Y

play09:18

is equal to y

play09:21

so when we draw a tile on the game

play09:24

screen we need to specify an X Y width

play09:27

and height

play09:28

so over here we have a width and height

play09:32

of 25 pixels by 25 pixels but what is

play09:36

the X and Y coordinate well we scaled

play09:39

everything by 25 pixels per tile

play09:43

so if you look at our window here we

play09:46

have one two three four five

play09:49

in the X Direction and one two three

play09:52

four five in the y direction

play09:55

so the X and Y coordinates start at the

play09:58

very top left corner which is 0 0 and

play10:01

the bottom right corner is 600 by 600.

play10:05

so where is the snake's X and Y position

play10:08

it will be five five so those are the X

play10:12

and Y coordinates but because we have a

play10:14

scale the tile size meaning each tile

play10:18

has a width and height of 25

play10:20

to physically place the snake in this

play10:23

position on the screen we need to

play10:25

multiply the x and y coordinate by 25 so

play10:29

this will be 5 times 25 and 5 times 25.

play10:33

so the X and Y would be 5 5 but

play10:37

physically pixel wise it'll be 125

play10:40

pixels 125 pixels okay

play10:45

so I'm going to create a tile snake head

play10:48

variable

play10:50

and then within our Constructor

play10:52

I'm going to do snake head is equal to

play10:55

new tile and we need to specify an x and

play10:58

y coordinate so I'm just going to use 5

play11:01

5 as the default starting place

play11:05

so now that we have our tile object we

play11:07

need to draw this so I'm going to create

play11:11

a function

play11:13

public void paint component

play11:18

and it's going to take in graphics G

play11:21

which is used for drawing and I'm going

play11:24

to do super dot paint component

play11:27

G

play11:29

and draw G

play11:32

so we need to define a draw function

play11:35

so public void draw Graphics G

play11:42

and for the snake I'm going to set the

play11:45

color of the pen

play11:47

to color not green

play11:51

and I'm going to draw a rectangle so g

play11:54

dot fill rect

play11:56

we need to specify the X and Y position

play11:59

so Snakehead dot X Snakehead dot y

play12:04

o size for the width and tile size for

play12:08

the height

play12:09

all right so now we run our program

play12:13

so you can see we have a green rectangle

play12:15

that is the snake head and the width is

play12:18

25 pixels and height is also 25 pixel

play12:23

now something here looks off and that is

play12:25

the X and Y coordinate so where we drew

play12:28

the snake it should actually be

play12:30

somewhere over here right because we

play12:32

specified 5 5 we meant five units to the

play12:35

right and five units down

play12:37

now the thing here is when we passed in

play12:39

the values for the X and Y coordinates

play12:43

we literally passed in five five so the

play12:47

fill rect recognizes that as 5 pixels to

play12:50

the right and five pixels down so to get

play12:52

it five units down and five units to the

play12:55

right we need to multiply the X and Y by

play12:58

the tile size

play13:01

so over here I'm going to do Snakehead

play13:03

dot x times tile size

play13:06

and Snakehead y times tile size

play13:10

so now if I run the program again

play13:13

you can see our snake is over here five

play13:15

units to the right and five units down

play13:17

okay and physically on the screen it is

play13:20

5 times 25 so 125 pixels to the right

play13:24

and 125 pixels down

play13:28

and just to make it easier for you to

play13:31

visualize I'm going to draw some grid

play13:33

lines here

play13:34

so for INT I is equal to zero I less

play13:38

than board width divided by tile size

play13:43

I plus plus

play13:45

so board width is 600 and tile size is

play13:48

25 so 600 divided by 25 gets you 24 so

play13:52

we have 24 rows and 24 Columns of

play13:55

squares so for each one I'm going to

play13:58

draw a line so g dot draw line I times

play14:03

tile size

play14:05

zero

play14:06

I times tile size

play14:09

Board height

play14:13

and let's draw another line so G that

play14:15

draw a line

play14:17

zero

play14:18

I times tile size

play14:21

board with

play14:23

I times title size

play14:27

so whenever you draw a line you need a

play14:29

starting point and an end point so

play14:31

that's why we have X1 y1 and X2 Y2

play14:35

the first line here we are drawing

play14:37

vertical lines

play14:38

so the Y's will be from zero to the

play14:42

height and X will change so these X1 and

play14:46

X2 they will move together and basically

play14:48

we need to change the x value so that it

play14:51

goes from left to right now for the

play14:53

second line we are drawing horizontally

play14:55

so it's going to start from the X

play14:58

position of zero to the board width and

play15:01

we need to draw line by line up and down

play15:04

so we are changing the y coordinate

play15:08

okay

play15:09

so now if I run our program

play15:12

you can see we have our grid lines

play15:16

all right so now that we have the snake

play15:18

in the proper position let's draw the

play15:20

food so the food is also going to be a

play15:24

tile

play15:25

so here I'm just going to separate the

play15:27

two so this is the snake

play15:30

and for the food we have

play15:33

Tayo food

play15:35

and inside the Constructor

play15:37

I'm going to create a new tile for the

play15:40

food

play15:41

so food is equal to new taiyo

play15:44

and let's just set the X and Y to 10 10.

play15:49

all right so now that we have a tile

play15:51

representing the food let's draw it on

play15:53

the panel

play15:54

so here I'm going to draw the food

play15:58

before the snake

play15:59

so food goes here and I'm going to do G

play16:03

not set color

play16:05

dot red

play16:07

and similarly I'm going to do g dot fill

play16:11

rect

play16:13

food.x times tile size

play16:17

Foo dot y times tile size

play16:20

and for the width it's going to be tile

play16:22

size and the height is also going to be

play16:25

tile size

play16:27

all right now let's run our program

play16:30

and you can see we have our food here

play16:32

and it is 10 units to the right and 10

play16:34

units down okay

play16:37

all right so now that we have our food

play16:39

let's create a function that will

play16:41

randomly place the food on the screen so

play16:43

that the X and Y position isn't always

play16:45

10 10. so to randomly place the food I

play16:49

need to create a random object so over

play16:53

here I'm going to do random random

play16:56

and then down here I'm going to create a

play16:59

random object So Random equals new

play17:02

random

play17:04

and then I'm going to call the place

play17:06

food

play17:07

function

play17:09

and then down here let's define our

play17:11

place food function

play17:15

and basically this function will just

play17:17

randomly set the X and Y coordinates of

play17:20

the food

play17:21

so food.x is going to be random than

play17:24

maxed int of board width divided by tile

play17:29

size

play17:31

and food.y

play17:33

is going to be random than next int

play17:36

of Board height divided by tile size

play17:42

so board width and height are both 600

play17:45

pixels and tile size is 25 so this would

play17:49

give us 24

play17:50

so the X Position will be a random

play17:52

number from 0 to 24. and the Y Position

play17:56

will also be a random number from 0 to

play17:58

24.

play18:00

all right so now if I run our program we

play18:03

expect the food to be placed in a random

play18:05

location

play18:06

over here

play18:07

and then if I we run it again

play18:11

and again

play18:13

you can see the position is changing

play18:16

every time

play18:18

okay

play18:19

all right now that we have the snake and

play18:22

the food we need to make the snake move

play18:24

and before we make the snake move we

play18:26

need to create the game Loop

play18:29

so when we make the snake move we are

play18:31

changing the X and Y position of the

play18:33

snake and to reflect that on the screen

play18:35

we need to redraw the panel so that we

play18:39

draw the new rectangle with the updated

play18:41

X and Y positions

play18:43

for that reason we need a game Loop so

play18:45

that the game Loop will constantly

play18:47

redraw the frames

play18:50

so to create the game Loop we need a

play18:52

timer so

play18:54

over here I'm going to add a new section

play18:57

for variables and I'm going to call it

play18:59

game logic

play19:00

and I'm going to create a variable for

play19:03

the timer

play19:04

and we're going to name it game Loop

play19:07

and then down here I'm going to assign

play19:10

game Loop

play19:11

to new timer

play19:14

and over here we need to tell the timer

play19:16

how often it should run so let's say 100

play19:20

milliseconds

play19:21

so 100 milliseconds is one tenth of a

play19:25

second

play19:26

and we need to tell the timer what to do

play19:28

every 100 milliseconds so we're going to

play19:32

place the keyword this over here

play19:35

and then up here

play19:39

I'm going to implement

play19:42

action listener

play19:46

so now you can see we have an error here

play19:48

and that is we need to

play19:50

add a new method when we implement the

play19:53

action listener

play19:55

so down here we need to create an action

play19:58

performed method and override it so over

play20:02

here let's just get rid of this

play20:05

and then what I'm going to do is call

play20:08

repaint

play20:10

so every 100 milliseconds we are going

play20:13

to call this action performed which will

play20:16

repaint

play20:17

and repaint basically calls draw over

play20:21

and over again

play20:22

okay

play20:24

so over here I'm going to do game Loop

play20:26

dot start

play20:30

so now if I run a program

play20:33

you can see we are drawing over and over

play20:35

again but you don't really see a

play20:37

difference because we didn't make the

play20:39

snake move so it is drawing the same

play20:41

frame over and over again every 100

play20:43

milliseconds

play20:47

all right now that we have our snake and

play20:50

we have our food and we have our game

play20:52

Loop we need to make the snake move

play20:55

so just as a recap the top left is 0 0

play20:59

and the bottom right is 600 600. so it's

play21:04

600 pixels by 600 pixels or it's 25

play21:08

tiles down and 24 tiles to the right

play21:12

okay so where is the snake

play21:16

the snake is five tiles down and five

play21:19

tiles to the right or 125 pixels down

play21:23

125 pixels to the right

play21:26

so if we want to move the snake we need

play21:28

to specify a velocity and velocity is

play21:32

the change in position over time

play21:35

so just now we created a game Loop and

play21:38

the loop runs every 100 milliseconds so

play21:42

every 100 milliseconds we want the snake

play21:44

to move in some Direction

play21:46

so for velocity X we have negative and

play21:50

positive negative is going to the left

play21:52

and positive is going to the right

play21:53

because if you're going to the left

play21:55

you're going towards zero

play21:57

and if you're going to the right you're

play21:59

going towards 600 pixels

play22:02

and velocity Y is up and down so

play22:05

negative velocity y means you're going

play22:07

up towards zero and going down means

play22:10

you're going towards 600 pixels

play22:12

so when we're drawing our Square when we

play22:16

update the X and Y position by one we

play22:20

are moving the snake one tile over okay

play22:24

so if I want to move to the right

play22:27

velocity X will be positive one and

play22:30

whenever we draw our snake each frame we

play22:34

are moving it over one tile at a time

play22:36

okay

play22:38

all right so over here I'm going to

play22:41

specify a velocity X

play22:45

and a velocity y

play22:49

and then over here I'm going to set

play22:52

velocity X to Zero and velocity of Y

play22:56

let's just make it 1.

play22:58

so if velocity Y is one it's going

play23:01

downwards

play23:03

now within our game Loop over here I

play23:06

want to call a move function that will

play23:09

update the X and Y position of the snake

play23:11

and after that we will repaint

play23:15

so up here I'm going to define the move

play23:19

function

play23:22

and for the snake head

play23:25

I'm going to do Snakehead dot X Plus

play23:28

equal velocity X

play23:31

and Snakehead dot y plus equal velocity

play23:35

y

play23:38

all right so this is going to be called

play23:40

every 100 milliseconds and we are

play23:43

updating

play23:44

X and Y position in this case velocity X

play23:46

is zero so it's only moving in the y

play23:49

direction

play23:53

all right now that I run the program you

play23:55

can see the snake is moving downwards

play23:58

and if I go back up and I change this to

play24:01

zero and I make

play24:03

velocity x negative one we can expect

play24:06

the snake to go to the left

play24:11

and there you go the snake just moved

play24:13

left

play24:14

all right let's set this back to zero

play24:17

so now the snake is not moving because

play24:19

velocity X and velocity y are both zero

play24:22

so there is no change in position

play24:25

all right now that we can make the snake

play24:27

move we want to be able to control the

play24:30

snake using arrow keys so I want the

play24:33

Snake Game to listen to key events

play24:36

so for that I'm going to implement

play24:39

key listener

play24:42

and for the key listener we need to

play24:44

override three methods so in Visual

play24:47

Studio code if I just hover over this

play24:48

and

play24:50

click on Quick Fix add unimplemented

play24:52

methods

play24:54

then I scroll down

play24:56

you can see we have three methods that

play24:59

we need to implement

play25:01

in our case we just need the key press

play25:03

so I'm just going to take this

play25:07

and move it up here

play25:10

let's format this

play25:13

and we do not need the rest of this so

play25:16

do not need

play25:18

and I'm just going to get rid of this

play25:20

and get rid of this

play25:24

all right so we just need to Define

play25:27

these methods we don't need to put

play25:29

anything inside we just need to Define

play25:31

them we only care about the key press so

play25:33

that's whenever you press on a key

play25:36

so let's get rid of this piece of code

play25:40

and over here let's define the Four Keys

play25:42

that we need so up down left and right

play25:45

so if e dot get key code is equal to key

play25:50

event

play25:52

dot VK underscore up

play25:57

this means that we press the up key I'm

play26:00

going to set velocity X to Zero

play26:03

and velocity y

play26:05

to negative 1.

play26:08

else if e dot get key code is equal to

play26:13

key event

play26:15

key event dot VK down

play26:21

velocity X will still be zero but

play26:24

velocity Y is going to be 1.

play26:29

else if e dot get key code

play26:33

is equal to

play26:34

key event dot VK left

play26:39

velocity X will be negative one

play26:42

and velocity y will be zero

play26:46

else if e dot getkey code is equal to

play26:50

key event

play26:52

dot VK right

play26:55

velocity X will be positive one and

play26:58

velocity y will be zero

play27:02

all right so now we have our key press

play27:03

defined now we need to make the game

play27:07

panel or the Snake Game listen to the

play27:10

key presses so let's scroll up

play27:12

and within our Constructor I'm going to

play27:16

do add key listener this

play27:20

and we want our snake game to be the one

play27:23

listening for key presses so I'm going

play27:26

to do set focusable

play27:28

to true

play27:31

and then I'm going to go back to

play27:32

app.java

play27:34

and do snake game dot request Focus

play27:40

so now our snake game is going to be the

play27:42

one listening for the key presses

play27:47

all right now let's run our program

play27:51

and now let's make the snake go down

play27:54

right up left

play27:57

down right and so on so the snake is

play28:00

able to move but we have one problem and

play28:03

that is the snake is able to move

play28:05

backwards right so if it goes up it

play28:08

shouldn't be able to move down

play28:10

otherwise it will run into its own body

play28:14

so to fix that we just need to make sure

play28:16

that the snake is not already heading in

play28:19

the opposite direction so I'm going to

play28:22

put n velocity y

play28:25

is not equal to one

play28:28

and for moving down

play28:30

we need to make sure velocity y

play28:33

is not equal to negative one

play28:37

moving left velocity X

play28:40

not equal to one

play28:43

and moving right velocity X not equal to

play28:47

negative one

play28:49

all right so now if I run our program

play28:51

and I press down I cannot press up to go

play28:54

back up

play28:56

all right so now that we have the snake

play28:58

moving let's have the snake eat the food

play29:02

and grow its body

play29:06

all right so for the snake's body we

play29:08

need an arraylist to store all of its

play29:10

segments so each part is a tile so I'm

play29:14

going to use an array list

play29:17

so over here arraylist

play29:20

tile let's call it snake body

play29:24

and then within our Constructor

play29:27

snake body is equal to new arraylist

play29:31

tile

play29:36

all right now that we have an arraylist

play29:37

to store all the snake's body parts

play29:40

let's create a function to detect

play29:43

collision between the snake's head and

play29:45

the food

play29:47

so down here let's define a function

play29:51

chord collision and it's going to take

play29:53

two tiles tile one and tile two

play29:59

and to determine if two tiles are

play30:01

colliding it's very simple we just need

play30:04

to check their X and Y positions so if

play30:07

they are in the same X and Y position

play30:08

that means they are both in the same

play30:11

tile

play30:13

so I'll return tile one dot X is equal

play30:17

to Tio two dot X and tile one dot Y is

play30:22

equal to tile two dot y

play30:26

and we're going to use the same function

play30:28

for detecting whether the snake has also

play30:31

collided with its own body

play30:34

So within the move function let's add

play30:36

this check

play30:38

so this is for eating the food

play30:41

if Collision

play30:44

snake head

play30:47

food

play30:50

we are going to add a new segment to the

play30:52

snake's body so snake body dot add new

play30:58

tile

play30:59

food.x food.y

play31:03

and then we are going to call Place food

play31:08

and then one more thing we need to do is

play31:11

in our draw function we need to draw

play31:13

each body part of the snake

play31:16

so this is the snake's head and then I'm

play31:19

going to scroll down a bit

play31:21

let's draw the snake body

play31:24

and we are going to iterate through the

play31:27

arraylist for the snake body

play31:39

tile snake part is equal to snake body

play31:43

dot get

play31:45

I

play31:47

and then we are going to draw a

play31:49

rectangle for that snake part so g dot

play31:53

fill rect

play31:54

snake part

play31:56

dot x times tile size

play32:01

snake part dot y times tile size

play32:06

and then the width is tile size

play32:09

and the height is also tile size

play32:14

all right now let's run our program

play32:18

and if we collide with the food you can

play32:21

see we are eating the food and the

play32:22

segments are there because the color is

play32:24

green

play32:26

but

play32:27

we are not moving any of the snake's

play32:30

body parts

play32:32

so we need to Define this in the move

play32:35

function

play32:38

all right so to move the snake body we

play32:40

need to make sure that it moves along

play32:42

with the head so I'm going to move all

play32:45

the tiles within the snake body before I

play32:47

move the head and the reason is if I

play32:50

move the head first the next tile which

play32:53

is the first member of the snake body

play32:55

it's not going to know where to go right

play32:58

because we are following the leader

play32:59

which is the snake head so to resolve

play33:02

this I'm going to iterate backwards on

play33:04

the arraylist and for each part it is

play33:07

going to copy the X and Y position of

play33:10

the part that came before it so

play33:12

therefore we are basically saying each

play33:15

tile needs to catch up to the one before

play33:17

it before the snake head can move

play33:20

so let's move the snake body

play33:23

oh it should be snake body

play33:27

and I'm going to iterate backwards

play33:30

into I is equal to snake body dot size

play33:34

minus one

play33:37

I greater than or equal to zero I minus

play33:41

minus

play33:43

so we're going to get the tile for the

play33:46

snake's part so tile

play33:49

snake part

play33:51

is equal to

play33:52

snake body dot get I

play33:57

so if I is equal to zero

play34:01

this means this is the first member of

play34:03

the snake body the one that comes right

play34:05

after the snakehead

play34:07

we are going to do snake part

play34:11

dot X

play34:13

and set it to Snakehead dot X

play34:17

snake part dot Y is equal to Snakehead

play34:21

dot y

play34:23

otherwise we are going to have it copy

play34:26

the X and Y position of the body part

play34:29

that's before it

play34:32

so let's get the body part before it

play34:34

tile prep snake part

play34:38

is equal to snake body dot get

play34:42

I minus one

play34:45

snake part dot X is equal to prev snake

play34:49

part dot X

play34:52

snake part dot Y is equal to prev snake

play34:55

part dot y

play34:59

so now we are moving the snake's body

play35:01

along with the head

play35:04

all right now let's run our program

play35:07

so when the snake touches the food it

play35:10

eats the food and it grows by one tile

play35:13

and you can see the body is moving along

play35:16

with the snake's head

play35:20

alright so now that we can grow the

play35:22

snake

play35:24

we need to check for game over

play35:27

conditions so there are two situations

play35:30

for game over one is the snake collides

play35:33

with its own body or the snake collides

play35:35

against the walls

play35:39

all right let's implement the game over

play35:40

conditions so over here

play35:44

I'm going to add a new variable called

play35:47

game over and I'm going to set this to

play35:49

false by default

play35:51

and then within our move function

play35:56

let's add the game over conditions

play36:02

so let's start with the first one and

play36:03

that is the snake collides with its own

play36:05

body

play36:09

so I'm going to iterate through all the

play36:10

body parts of the snake

play36:19

tile snake part is equal to snake body

play36:23

that get I

play36:25

so if we collide with the snake head

play36:30

so if Collision

play36:33

snake head snake part

play36:37

I'm going to set game over to true

play36:43

and then Within action performed

play36:46

which is our game Loop

play36:49

if a game over

play36:52

I'm going to do game Loop dot stop

play36:56

so this will end the game right there

play36:59

so let's run a program

play37:02

so we're going to eat the food and

play37:06

grow the snake body so that when it

play37:09

collides with itself

play37:11

the game should end

play37:15

okay there you go

play37:17

so the game Loop has stopped and the

play37:19

snake is no longer moving

play37:22

all right now let's add the other

play37:24

condition and that is the snake hits one

play37:27

of the four walls so over here

play37:31

if

play37:33

Snakehead dot x times tile size

play37:37

is less than zero that means the X

play37:40

position past the left wall

play37:43

or Snakehead dot x times tile size

play37:48

is greater than board width

play37:51

this means that the X position of the

play37:54

snake has gone past the right side of

play37:57

the screen

play38:01

or

play38:02

Snakehead dot y times tile size is less

play38:06

than zero this means that the snake has

play38:08

gone up past the screen

play38:11

or Snakehead dot y times tile size

play38:15

is greater than Board height

play38:18

so the snake has gone down past the

play38:20

screen

play38:23

we are going to set game over to true

play38:28

so let's format this

play38:30

highlight and shift tab

play38:33

okay

play38:36

now let's run our program

play38:41

okay now if I eat the food and I go down

play38:44

you can see game over

play38:49

and then if I run the program again

play38:52

and go to the left game over so I can't

play38:55

move anymore

play38:56

so let's make this more obvious by

play38:59

putting the word game over here and

play39:02

actually let's also keep track of the

play39:04

score so let's do that in the draw

play39:06

function

play39:09

all right so within our draw function

play39:11

let's scroll down

play39:14

and I'm going to draw the score and the

play39:16

text for game over

play39:18

so I'm going to do g dot set font

play39:21

new font

play39:23

aerial

play39:26

font dot plane

play39:29

16.

play39:32

so if game over

play39:35

I'm going to set the color

play39:38

to color.red

play39:42

and g dot drawstring

play39:45

game over

play39:47

and let's also put the score so string

play39:50

dot value of

play39:53

and the score is just going to be the

play39:55

length of the snake body so how many

play39:57

times you've eaten the food

play39:59

so snake body not size

play40:04

and then I'm going to set the x position

play40:05

to be tile size -16

play40:09

and the Y Position will be tile size

play40:15

else let's just uh tell the user what

play40:18

their score is so G that drawstring

play40:22

score

play40:25

plus string dot value of

play40:29

snake body dot size

play40:33

tile size minus 16 and tile size

play40:39

okay now let's run our program

play40:43

okay so now you can see the text for

play40:44

score on the top left and now if I eat

play40:47

the food score increments by one

play40:50

two

play40:55

and then let's try to get game over and

play40:58

there you go so game over and our score

play41:00

is five

play41:03

all right so now there's one more thing

play41:05

that I want to quickly show you and that

play41:07

is I'm going to get rid of the grid

play41:08

lines so let's comment this out

play41:11

and you can draw the rectangles with

play41:13

borders so just take this

play41:17

for food and I'm just going to copy and

play41:19

paste that here

play41:21

and this will be fill 3D react and then

play41:24

I'm going to add one more parameter true

play41:29

and let's also do the same thing for the

play41:31

snake head

play41:33

so fill 3direct

play41:36

true

play41:38

and let's actually count out these two

play41:42

okay

play41:44

and then finally for the snake body I'm

play41:46

going to copy and paste this

play41:48

combat this out

play41:55

and then let's rename this so fill 3D

play41:58

rect

play41:59

and then let's pass in true

play42:03

all right now let's run our program

play42:06

so now we have a border around our tiles

play42:10

so if I have the snake eat the food and

play42:13

grow its segments

play42:15

you can see each part is divided by the

play42:19

border

play42:24

and we have a fully functional game of

play42:27

snake

play42:32

so if this tutorial worked for you make

play42:34

sure you give the video a like and if

play42:37

you have any questions let me know Down

play42:38

Below in the comments and if you want to

play42:41

see more content like this make sure you

play42:43

subscribe to the channel and I'll see

play42:46

you in the next video

play42:48

bye bye

Rate This
โ˜…
โ˜…
โ˜…
โ˜…
โ˜…

5.0 / 5 (0 votes)

Related Tags
Java ProgrammingSnake GameGame DevelopmentGraphics LibraryTutorialsCodingVisual Studio CodeKeyListenerActionListenerObject-Oriented