Code Snake Game in Java
Summary
TLDRفي هذا الفيديو سيتم تدوين لعبة ال蟒 (Snake) بلغة Java. يبدأ الشرح بعرض النتيجة النهائية حيث يمكن للاعب اللعب بواسطة الضغط على أي مفتاح السهم. يشرح القناة كيفية إنشاء نافذة لعبه واستخدام مكتبة الرسومات الداخلة في Java. بعد ذلك، يشرح كيفية رسم رأس ال蟒 والطعام والتحريك في النافذة، وكيفية تفاعل ال蟒 مع الطعام لنمو جسمها. وسيتم توضيح كيفية إنشاء حلقة اللعبة والتحكم في ال蟒 بواسطة مفاتيح الأسهم. وسيتم تطبيق الشروط لإنهاء اللعبة عند الارتكاب بالجدران أو ال蟒 بجسدها. وسيتم رسم النتيجة في نهاية اللعبة وإضافة حدود حول المربعات لجعل اللعبة أكثر وضوحًا.
Takeaways
- 🎮 **لعبة ال_python_**: يشرح القناة كيفية إنشاء لعبة ال_snake_ بلغة Java، مما يوفر للمشاهدين نظرة عامة على النتيجة النهائية قبل البدء في الكود.
- 🔑 **بدء اللعبة**: يمكن للاعبين البدء في اللعبة عن طريق الضغط على أي مفتاح الأسهم، مما يتيح لهم تحريك ال_snake_.
- 🍎 **الغذاء في اللعبة**: ينمو جسم ال_snake_ بجزء عندما يلمس الغذاء، والذي يظهر باللون الأحمر.
- 🧩 **هدف اللعبة**: الهدف是从增长_snake_体积而不让它撞到墙壁或其他部位。
- 💻 **استخدم Java ومكتبة الرسومات الداخلية**: يستخدم تьюتوريال Java ومكتبة الرسومات الداخلية لتطوير اللعبة.
- 👾 **تطوير سلسلة جديدة من الدروس**: يشار إلى تطوير سلسلة جديدة من الدروس لتعليم كيفية صنع الألعاب بلغة Java، بما في ذلك الـ Tic-tac-toe و _Snake_.
- 🌐 **مواقع التعلم**: يمكن للمستخدمين الاطلاع على الدروس المتاحة على موقع kenneopecoding.com للبقاء على اطلاع بالتحديثات القادمة.
- ⚙️ **إعداد مشروع Java في Visual Studio Code**: يشرح تьюتوريال كيفية إعداد Visual Studio Code لتطوير Java.
- 🖥️ **إنشاء نافذة للعب**: يبدأ الكود بإنشاء نافذة للعب بحجم 600x600 بكسل.
- 📐 **إنشاء لوحة لرسم اللعبة**: بعد إنشاء النافذة، ينبغي إنشاء لوحة (JPanel) لرسم عناصر اللعبة.
- 🔲 **تصميم ال_tile_**: يستخدم التصميم المربعي (_tile_) بحجم 25x25 بكسل لتقسيم الشاشة إلى مربعات يمكن تحريك ال_snake_ عليها.
- 🔄 **التكرار والتحريك**: يستخدم مسار التكرار (game loop) لإعادة رسم الフレームات وتحريك ال_snake_.
- ⏲️ **الوقت**: يستخدم موقت (timer) لتكرار مسار التكرار بانتظام كل 100 مللي ثانية.
- 🛑 **التحكم في الحركة**: يستخدم مفتاحات الأسهم لتغيير اتجاه ال_snake_.
- 🚫 **الضوابط النهائية**: يجب التحقق من الظروف التي تؤدي إلى النهاية النهائية للعبة، مثل الارتكاب بالجدران أو بجسم ال_snake_.
- 🏁 **النتيجة**: يظهر ال-score_ للاعبين عدد ال Bricks التي أكلتها ال_snake_ قبل النهاية النهائية للعبة.
Q & A
视频中提到的游戏蛇是如何开始的?
-游戏蛇通过按下任意箭头键开始。
蛇在游戏中如何增长身体?
-每当蛇碰到红色的食物时,它的身体就会增长一个节段。
如果蛇撞到墙壁或自己的身体,游戏会怎么样?
-如果蛇撞到墙壁或自己的身体,游戏就会结束。
制作这个游戏使用的编程语言是什么?
-制作这个游戏使用的编程语言是Java。
开发这个游戏时使用的是哪个集成开发环境?
-开发这个游戏时使用的集成开发环境是Visual Studio Code。
游戏的窗口大小是如何设置的?
-游戏的窗口大小设置为600像素宽和600像素高。
蛇游戏中的面板是如何创建的?
-蛇游戏中的面板是通过创建一个继承自JPanel的新类来实现的。
蛇游戏中每个方块的尺寸是如何定义的?
-蛇游戏中每个方块的尺寸定义为25x25像素。
蛇游戏中蛇头的位置是如何确定的?
-蛇头的位置是通过乘以方块尺寸来确定的,例如在(5, 5)的坐标上,实际在屏幕上的位置是(5 * 25, 5 * 25)。
如何在游戏中随机放置食物?
-通过使用Random对象生成随机的X和Y坐标来在屏幕上随机放置食物。
蛇在游戏中是如何移动的?
-蛇在游戏中是通过游戏循环和箭头键的输入来移动的,箭头键改变蛇的移动方向。
游戏结束的条件是什么?
-游戏结束的条件是蛇撞到墙壁或者蛇撞到自己的身体。
如何跟踪并显示蛇的身体增长?
-使用一个ArrayList来存储蛇身体的每一节,每当蛇吃掉食物时,就在ArrayList中添加一个新的Tile对象来表示新增的身体节段。
游戏结束后,玩家的得分是如何计算的?
-游戏结束后,玩家的得分是蛇身体的长度,即玩家吃掉食物的次数。
Outlines
🚀 Introduction to Coding Snake Game in Java
The video begins with an introduction to creating the classic Snake game using Java. The presenter shares the final game interface where the snake grows by eating red food and the player controls the snake using arrow keys. The game ends if the snake hits the wall or its own body. The tutorial will use Java's built-in Graphics Library and the presenter mentions an upcoming series on game development in Java, including tutorials for Tic-tac-toe and other games. The setup for the project using Visual Studio Code is also briefly discussed.
🖥️ Setting Up the Game Window and Panel
The presenter guides through setting up the game window using Java's Swing library to create a JFrame. The window is set to a size of 600x600 pixels and is positioned at the center of the screen. A new class 'SnakeGame' is created to extend JPanel, which will be used for drawing the game elements. The蛇 game panel is added to the JFrame, and the program is run to verify the creation of the window and panel.
🎨 Drawing the Snake and Grid
The video continues with the process of drawing the snake head and the grid lines on the game panel. The snake head is represented by a green rectangle at the starting position. The presenter explains how to calculate the physical pixel position on the screen based on the tile size and coordinates. Grid lines are then drawn to visualize the game area, dividing it into 25x25 pixel squares.
🍎 Drawing the Food and Random Placement
The presenter demonstrates how to draw the food, which is a red rectangle, and how to randomly place it on the game panel using a Random object. The food's position is randomized by generating random numbers within the game area's boundaries, ensuring the food appears in a new location each time the game is run.
🔁 Creating the Game Loop and Snake Movement
The game loop is introduced to continuously redraw the game panel, allowing for the snake's movement. A Timer is set to trigger an action every 100 milliseconds, causing the snake to move based on its velocity. The snake's movement is controlled by updating its X and Y coordinates. The presenter also explains how to implement the game loop and make the snake move in response to user input.
⏪ Implementing Keyboard Controls
The SnakeGame class is updated to implement the KeyListener interface, allowing the snake to respond to key presses for movement. The presenter outlines how to handle arrow key events to change the snake's velocity and ensure the snake cannot move in opposite directions. The snake game panel is set to listen for key events to enable control through the keyboard.
🐍 Snake Body Growth and Collision Detection
An ArrayList is used to store the snake's body segments, and a method is created to detect collisions between the snake's head and the food. When the snake eats the food, a new segment is added to the snake's body. The presenter also adds code to draw the snake's body parts and explains how to update the body segments to move in conjunction with the snake's head.
🏁 Game Over Conditions and Score Tracking
The presenter adds game over conditions to end the game when the snake collides with its own body or the game's 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 tracked and displayed on the screen, which increments each time the snake eats the food.
🎉 Final Touches and Conclusion
The presenter finalizes the game by removing the grid lines and adding borders to the game tiles for better visual distinction. The snake, food, and each segment of the snake's body are updated to have borders. The video concludes with a fully functional Snake game, and the presenter encourages viewers to like the video, ask questions, and subscribe for more content.
Mindmap
Keywords
💡Java
💡Graphics Library
💡Snake Game
💡JFrame
💡KeyListener
💡Tile
💡ArrayList
💡Timer
💡Collision Detection
💡Game Loop
💡Score
Highlights
Coding the game Snake using Java is the focus of the tutorial.
The game starts by tapping any arrow key.
Snake grows by one segment when it touches red food.
The objective is to grow the snake without colliding into walls or its own body.
The game is coded using Java's built-in Graphics Library.
A new coding tutorial series for making games in Java is in progress, including Tic-tac-toe and Snake.
The presenter also has tutorials for HTML, CSS, and JavaScript game development.
Visual Studio Code is used for setting up and coding the project.
A window for the game is created with a size of 600x600 pixels.
A custom JPanel class called SnakeGame is created for drawing the game.
The game uses a tile size of 25x25 pixels for movement and collision detection.
The snake's head and food are represented as tiles on the game panel.
Food is randomly placed on the game screen using a random object.
A game loop with a timer is implemented to continuously redraw the game panel.
The snake's movement is controlled using the arrow keys.
The snake's body is represented as an ArrayList of Tile objects.
Collision detection is used to check for food consumption and body collisions.
The game ends if the snake collides with its body or the game walls.
The score is displayed and incremented each time the snake eats the food.
Grid lines and game over text are added for user clarity.
The final game includes borders around the tiles for better visual distinction.
Transcripts
hey there hope you're having a wonderful
day in this video we're going to be
coding the game Snake using Java so what
you see here is the final result of this
tutorial and to start the game you just
need to tap on any Arrow key
and you can see we have the snake moving
and whenever it touches the food which
is in red
it will grow its body by one segment so
the goal of the game is to
grow the snake's body without colliding
into the walls and if you Collide into
the walls or if the snake collides into
its own body the game is over
okay
so we're going to be coding this game in
Java using the built-in Graphics Library
so before we begin I just want to
quickly mention that I am working on a
new coding tutorial Series where I teach
you how to make games in Java So
currently I'm working on Tic-tac-toe and
snake and there will be more tutorials
in the future
I also have tutorials in HTML CSS and
JavaScript for Doodle Jump breakout
Flappy Birds Space Invaders Wordle
Sudoku 2048 Candy Crush and snake as
well so if you're interested and you
want to stay up to date on new tutorials
make sure you subscribe to this Channel
and you can also find this list on
kenneopecoding.com
all right let's begin so for this
tutorial I'm going to be using visual
studio code if you want to learn how to
set up visual studio code with Java I
have a video on that and I'll link it in
the description below
all right so let's create a project so
Ctrl shift p Java create project and no
build tools I'm going to create this on
my desktop
and let's call it snake
all right now I have my project folder
inside the source folder we have this
app.java file so let's open that
and the first thing I'm going to do is
delete this line
alright so now let's create a window for
our game so what I need to do is import
Java x dot swing
okay
and then in our main function let's
define a few variables so int board with
is going to be 600 pixels
and into Board height and we'll set that
to board width so Board height will also
be 600 pixels
all right let's create a window so
jframe
frame is new jframe and let's give it a
title so we'll just call it snake
let's make the frame visible so frame
dot set visible
we'll set this to true
frame dot set size we're going to set it
to board width
Board height
so this is going to be a window that is
600 pixels by 600 pixels
let's do frame dot set location relative
to null so this is going to open up the
window at the center of our screen
frame that's sizable
we're going to set this to false
and then frame dot set default closing
operation we're going to set this to
jframe dot exit on close
so this is going to make it so that the
program will terminate when the user
clicks on the x button on the window
all right let's run our program
and you can see we have a window
so now that we have our window what we
need now is a jpanel so that we can draw
our game so instead of creating a jpanel
here I'm going to create a new class
that will inherit the jpanel
so over here in our source folder I'm
going to create a new file and I'm going
to call it snake game
dot Java
so now we have our snake game file
and let's add some import statements so
import
java.awt dot asterisk
import
java.awt.event dot asterisk
import
java.util Dot arraylist
so this is going to be used for storing
the segments of the snake's body
import
java.util dot random
so this is going to be used for getting
random X and Y values to place our food
on the screen
finally import Java x dot swing dot
asterisk
okay so those are all the import
statements that we need
so in our class I'm going to extends the
jpanel
so basically we are inheriting here and
for those of you who don't know what
that means we are creating a new class
called snake game that will take on the
properties of Jade panel so basically
it's a version of jpanel with more
things that we can add
all right so now for our snake game
Let's create some variables for the
width and height
let's also create a Constructor
snake game
and this is going to take in two
parameters so board width
and Board height
so here I'm going to do this dot board
with
is equal to board width
and this dot Board height is equal to
Board height
so the reason why we need the this
keyword is to distinguish the two
boardwifts so we have one as a parameter
and another as a field or a member of
the snake game class so to distinguish
the two we say this dot board width
meaning the board width that belongs to
this class
so now we're going to take the board
width and Board height
and set preferred size to new dimension
this dot board with
this dot Board height
let's set the background of the panel to
color dot black
and then we're going to go back to our
app.java file
and we're going to create an instance of
the snake game
snake game is equal to a new snake
game
and we need to pass in the two
parameters so board width and Board
height
and then we're going to take the frame
and add the snake game
so if I run the program
you can see we have our snake game which
is a j panel inside our frame now
there's an issue and that is we set the
size of our frame to 600 by 600 what
that includes is this title bar over
here where it says snake essentially
this panel is actually not 600 by 600
pixels it's a little less than that
because of this title bar
so to resolve this issue we just need to
do frame dot pack so that it will place
the jpanel inside the frame with the
full dimensions
okay and we don't really need the
sidebar anymore so I'm just going to
collapse that
so here you can see our snake game it is
600 by 600 pixels and what we need to do
is we need to define a tile size so I'm
going to Define it as 25 by 25 so that
is the size of one square and basically
we are partitioning the 600 pixels into
24 columns and 24 rows so that whenever
we move the snake it moves over one tile
or one square instead of the exact pixel
number so it is 25 pixels by 25 pixels
so when the snake moves over to the
right it should move over 25 pixels and
if it moves over to the right again it
will move over 50 pixels and then 75
pixels
100 125 and so on
so here I'm going to define a tile size
and set it to 25 pixels
and so we're going to create a new class
to keep track of all the X and Y
positions for each tile so
let's create a new class and actually
I'm going to create it as a private
class
so that only the Snake Game can access
this class so private class tile
and x and into y
and then let's create a Constructor so
tile into X into y
this dot X is equal to X and this dot Y
is equal to y
so when we draw a tile on the game
screen we need to specify an X Y width
and height
so over here we have a width and height
of 25 pixels by 25 pixels but what is
the X and Y coordinate well we scaled
everything by 25 pixels per tile
so if you look at our window here we
have one two three four five
in the X Direction and one two three
four five in the y direction
so the X and Y coordinates start at the
very top left corner which is 0 0 and
the bottom right corner is 600 by 600.
so where is the snake's X and Y position
it will be five five so those are the X
and Y coordinates but because we have a
scale the tile size meaning each tile
has a width and height of 25
to physically place the snake in this
position on the screen we need to
multiply the x and y coordinate by 25 so
this will be 5 times 25 and 5 times 25.
so the X and Y would be 5 5 but
physically pixel wise it'll be 125
pixels 125 pixels okay
so I'm going to create a tile snake head
variable
and then within our Constructor
I'm going to do snake head is equal to
new tile and we need to specify an x and
y coordinate so I'm just going to use 5
5 as the default starting place
so now that we have our tile object we
need to draw this so I'm going to create
a function
public void paint component
and it's going to take in graphics G
which is used for drawing and I'm going
to do super dot paint component
G
and draw G
so we need to define a draw function
so public void draw Graphics G
and for the snake I'm going to set the
color of the pen
to color not green
and I'm going to draw a rectangle so g
dot fill rect
we need to specify the X and Y position
so Snakehead dot X Snakehead dot y
o size for the width and tile size for
the height
all right so now we run our program
so you can see we have a green rectangle
that is the snake head and the width is
25 pixels and height is also 25 pixel
now something here looks off and that is
the X and Y coordinate so where we drew
the snake it should actually be
somewhere over here right because we
specified 5 5 we meant five units to the
right and five units down
now the thing here is when we passed in
the values for the X and Y coordinates
we literally passed in five five so the
fill rect recognizes that as 5 pixels to
the right and five pixels down so to get
it five units down and five units to the
right we need to multiply the X and Y by
the tile size
so over here I'm going to do Snakehead
dot x times tile size
and Snakehead y times tile size
so now if I run the program again
you can see our snake is over here five
units to the right and five units down
okay and physically on the screen it is
5 times 25 so 125 pixels to the right
and 125 pixels down
and just to make it easier for you to
visualize I'm going to draw some grid
lines here
so for INT I is equal to zero I less
than board width divided by tile size
I plus plus
so board width is 600 and tile size is
25 so 600 divided by 25 gets you 24 so
we have 24 rows and 24 Columns of
squares so for each one I'm going to
draw a line so g dot draw line I times
tile size
zero
I times tile size
Board height
and let's draw another line so G that
draw a line
zero
I times tile size
board with
I times title size
so whenever you draw a line you need a
starting point and an end point so
that's why we have X1 y1 and X2 Y2
the first line here we are drawing
vertical lines
so the Y's will be from zero to the
height and X will change so these X1 and
X2 they will move together and basically
we need to change the x value so that it
goes from left to right now for the
second line we are drawing horizontally
so it's going to start from the X
position of zero to the board width and
we need to draw line by line up and down
so we are changing the y coordinate
okay
so now if I run our program
you can see we have our grid lines
all right so now that we have the snake
in the proper position let's draw the
food so the food is also going to be a
tile
so here I'm just going to separate the
two so this is the snake
and for the food we have
Tayo food
and inside the Constructor
I'm going to create a new tile for the
food
so food is equal to new taiyo
and let's just set the X and Y to 10 10.
all right so now that we have a tile
representing the food let's draw it on
the panel
so here I'm going to draw the food
before the snake
so food goes here and I'm going to do G
not set color
dot red
and similarly I'm going to do g dot fill
rect
food.x times tile size
Foo dot y times tile size
and for the width it's going to be tile
size and the height is also going to be
tile size
all right now let's run our program
and you can see we have our food here
and it is 10 units to the right and 10
units down okay
all right so now that we have our food
let's create a function that will
randomly place the food on the screen so
that the X and Y position isn't always
10 10. so to randomly place the food I
need to create a random object so over
here I'm going to do random random
and then down here I'm going to create a
random object So Random equals new
random
and then I'm going to call the place
food
function
and then down here let's define our
place food function
and basically this function will just
randomly set the X and Y coordinates of
the food
so food.x is going to be random than
maxed int of board width divided by tile
size
and food.y
is going to be random than next int
of Board height divided by tile size
so board width and height are both 600
pixels and tile size is 25 so this would
give us 24
so the X Position will be a random
number from 0 to 24. and the Y Position
will also be a random number from 0 to
24.
all right so now if I run our program we
expect the food to be placed in a random
location
over here
and then if I we run it again
and again
you can see the position is changing
every time
okay
all right now that we have the snake and
the food we need to make the snake move
and before we make the snake move we
need to create the game Loop
so when we make the snake move we are
changing the X and Y position of the
snake and to reflect that on the screen
we need to redraw the panel so that we
draw the new rectangle with the updated
X and Y positions
for that reason we need a game Loop so
that the game Loop will constantly
redraw the frames
so to create the game Loop we need a
timer so
over here I'm going to add a new section
for variables and I'm going to call it
game logic
and I'm going to create a variable for
the timer
and we're going to name it game Loop
and then down here I'm going to assign
game Loop
to new timer
and over here we need to tell the timer
how often it should run so let's say 100
milliseconds
so 100 milliseconds is one tenth of a
second
and we need to tell the timer what to do
every 100 milliseconds so we're going to
place the keyword this over here
and then up here
I'm going to implement
action listener
so now you can see we have an error here
and that is we need to
add a new method when we implement the
action listener
so down here we need to create an action
performed method and override it so over
here let's just get rid of this
and then what I'm going to do is call
repaint
so every 100 milliseconds we are going
to call this action performed which will
repaint
and repaint basically calls draw over
and over again
okay
so over here I'm going to do game Loop
dot start
so now if I run a program
you can see we are drawing over and over
again but you don't really see a
difference because we didn't make the
snake move so it is drawing the same
frame over and over again every 100
milliseconds
all right now that we have our snake and
we have our food and we have our game
Loop we need to make the snake move
so just as a recap the top left is 0 0
and the bottom right is 600 600. so it's
600 pixels by 600 pixels or it's 25
tiles down and 24 tiles to the right
okay so where is the snake
the snake is five tiles down and five
tiles to the right or 125 pixels down
125 pixels to the right
so if we want to move the snake we need
to specify a velocity and velocity is
the change in position over time
so just now we created a game Loop and
the loop runs every 100 milliseconds so
every 100 milliseconds we want the snake
to move in some Direction
so for velocity X we have negative and
positive negative is going to the left
and positive is going to the right
because if you're going to the left
you're going towards zero
and if you're going to the right you're
going towards 600 pixels
and velocity Y is up and down so
negative velocity y means you're going
up towards zero and going down means
you're going towards 600 pixels
so when we're drawing our Square when we
update the X and Y position by one we
are moving the snake one tile over okay
so if I want to move to the right
velocity X will be positive one and
whenever we draw our snake each frame we
are moving it over one tile at a time
okay
all right so over here I'm going to
specify a velocity X
and a velocity y
and then over here I'm going to set
velocity X to Zero and velocity of Y
let's just make it 1.
so if velocity Y is one it's going
downwards
now within our game Loop over here I
want to call a move function that will
update the X and Y position of the snake
and after that we will repaint
so up here I'm going to define the move
function
and for the snake head
I'm going to do Snakehead dot X Plus
equal velocity X
and Snakehead dot y plus equal velocity
y
all right so this is going to be called
every 100 milliseconds and we are
updating
X and Y position in this case velocity X
is zero so it's only moving in the y
direction
all right now that I run the program you
can see the snake is moving downwards
and if I go back up and I change this to
zero and I make
velocity x negative one we can expect
the snake to go to the left
and there you go the snake just moved
left
all right let's set this back to zero
so now the snake is not moving because
velocity X and velocity y are both zero
so there is no change in position
all right now that we can make the snake
move we want to be able to control the
snake using arrow keys so I want the
Snake Game to listen to key events
so for that I'm going to implement
key listener
and for the key listener we need to
override three methods so in Visual
Studio code if I just hover over this
and
click on Quick Fix add unimplemented
methods
then I scroll down
you can see we have three methods that
we need to implement
in our case we just need the key press
so I'm just going to take this
and move it up here
let's format this
and we do not need the rest of this so
do not need
and I'm just going to get rid of this
and get rid of this
all right so we just need to Define
these methods we don't need to put
anything inside we just need to Define
them we only care about the key press so
that's whenever you press on a key
so let's get rid of this piece of code
and over here let's define the Four Keys
that we need so up down left and right
so if e dot get key code is equal to key
event
dot VK underscore up
this means that we press the up key I'm
going to set velocity X to Zero
and velocity y
to negative 1.
else if e dot get key code is equal to
key event
key event dot VK down
velocity X will still be zero but
velocity Y is going to be 1.
else if e dot get key code
is equal to
key event dot VK left
velocity X will be negative one
and velocity y will be zero
else if e dot getkey code is equal to
key event
dot VK right
velocity X will be positive one and
velocity y will be zero
all right so now we have our key press
defined now we need to make the game
panel or the Snake Game listen to the
key presses so let's scroll up
and within our Constructor I'm going to
do add key listener this
and we want our snake game to be the one
listening for key presses so I'm going
to do set focusable
to true
and then I'm going to go back to
app.java
and do snake game dot request Focus
so now our snake game is going to be the
one listening for the key presses
all right now let's run our program
and now let's make the snake go down
right up left
down right and so on so the snake is
able to move but we have one problem and
that is the snake is able to move
backwards right so if it goes up it
shouldn't be able to move down
otherwise it will run into its own body
so to fix that we just need to make sure
that the snake is not already heading in
the opposite direction so I'm going to
put n velocity y
is not equal to one
and for moving down
we need to make sure velocity y
is not equal to negative one
moving left velocity X
not equal to one
and moving right velocity X not equal to
negative one
all right so now if I run our program
and I press down I cannot press up to go
back up
all right so now that we have the snake
moving let's have the snake eat the food
and grow its body
all right so for the snake's body we
need an arraylist to store all of its
segments so each part is a tile so I'm
going to use an array list
so over here arraylist
tile let's call it snake body
and then within our Constructor
snake body is equal to new arraylist
tile
all right now that we have an arraylist
to store all the snake's body parts
let's create a function to detect
collision between the snake's head and
the food
so down here let's define a function
chord collision and it's going to take
two tiles tile one and tile two
and to determine if two tiles are
colliding it's very simple we just need
to check their X and Y positions so if
they are in the same X and Y position
that means they are both in the same
tile
so I'll return tile one dot X is equal
to Tio two dot X and tile one dot Y is
equal to tile two dot y
and we're going to use the same function
for detecting whether the snake has also
collided with its own body
So within the move function let's add
this check
so this is for eating the food
if Collision
snake head
food
we are going to add a new segment to the
snake's body so snake body dot add new
tile
food.x food.y
and then we are going to call Place food
and then one more thing we need to do is
in our draw function we need to draw
each body part of the snake
so this is the snake's head and then I'm
going to scroll down a bit
let's draw the snake body
and we are going to iterate through the
arraylist for the snake body
tile snake part is equal to snake body
dot get
I
and then we are going to draw a
rectangle for that snake part so g dot
fill rect
snake part
dot x times tile size
snake part dot y times tile size
and then the width is tile size
and the height is also tile size
all right now let's run our program
and if we collide with the food you can
see we are eating the food and the
segments are there because the color is
green
but
we are not moving any of the snake's
body parts
so we need to Define this in the move
function
all right so to move the snake body we
need to make sure that it moves along
with the head so I'm going to move all
the tiles within the snake body before I
move the head and the reason is if I
move the head first the next tile which
is the first member of the snake body
it's not going to know where to go right
because we are following the leader
which is the snake head so to resolve
this I'm going to iterate backwards on
the arraylist and for each part it is
going to copy the X and Y position of
the part that came before it so
therefore we are basically saying each
tile needs to catch up to the one before
it before the snake head can move
so let's move the snake body
oh it should be snake body
and I'm going to iterate backwards
into I is equal to snake body dot size
minus one
I greater than or equal to zero I minus
minus
so we're going to get the tile for the
snake's part so tile
snake part
is equal to
snake body dot get I
so if I is equal to zero
this means this is the first member of
the snake body the one that comes right
after the snakehead
we are going to do snake part
dot X
and set it to Snakehead dot X
snake part dot Y is equal to Snakehead
dot y
otherwise we are going to have it copy
the X and Y position of the body part
that's before it
so let's get the body part before it
tile prep snake part
is equal to snake body dot get
I minus one
snake part dot X is equal to prev snake
part dot X
snake part dot Y is equal to prev snake
part dot y
so now we are moving the snake's body
along with the head
all right now let's run our program
so when the snake touches the food it
eats the food and it grows by one tile
and you can see the body is moving along
with the snake's head
alright so now that we can grow the
snake
we need to check for game over
conditions so there are two situations
for game over one is the snake collides
with its own body or the snake collides
against the walls
all right let's implement the game over
conditions so over here
I'm going to add a new variable called
game over and I'm going to set this to
false by default
and then within our move function
let's add the game over conditions
so let's start with the first one and
that is the snake collides with its own
body
so I'm going to iterate through all the
body parts of the snake
tile snake part is equal to snake body
that get I
so if we collide with the snake head
so if Collision
snake head snake part
I'm going to set game over to true
and then Within action performed
which is our game Loop
if a game over
I'm going to do game Loop dot stop
so this will end the game right there
so let's run a program
so we're going to eat the food and
grow the snake body so that when it
collides with itself
the game should end
okay there you go
so the game Loop has stopped and the
snake is no longer moving
all right now let's add the other
condition and that is the snake hits one
of the four walls so over here
if
Snakehead dot x times tile size
is less than zero that means the X
position past the left wall
or Snakehead dot x times tile size
is greater than board width
this means that the X position of the
snake has gone past the right side of
the screen
or
Snakehead dot y times tile size is less
than zero this means that the snake has
gone up past the screen
or Snakehead dot y times tile size
is greater than Board height
so the snake has gone down past the
screen
we are going to set game over to true
so let's format this
highlight and shift tab
okay
now let's run our program
okay now if I eat the food and I go down
you can see game over
and then if I run the program again
and go to the left game over so I can't
move anymore
so let's make this more obvious by
putting the word game over here and
actually let's also keep track of the
score so let's do that in the draw
function
all right so within our draw function
let's scroll down
and I'm going to draw the score and the
text for game over
so I'm going to do g dot set font
new font
aerial
font dot plane
16.
so if game over
I'm going to set the color
to color.red
and g dot drawstring
game over
and let's also put the score so string
dot value of
and the score is just going to be the
length of the snake body so how many
times you've eaten the food
so snake body not size
and then I'm going to set the x position
to be tile size -16
and the Y Position will be tile size
else let's just uh tell the user what
their score is so G that drawstring
score
plus string dot value of
snake body dot size
tile size minus 16 and tile size
okay now let's run our program
okay so now you can see the text for
score on the top left and now if I eat
the food score increments by one
two
and then let's try to get game over and
there you go so game over and our score
is five
all right so now there's one more thing
that I want to quickly show you and that
is I'm going to get rid of the grid
lines so let's comment this out
and you can draw the rectangles with
borders so just take this
for food and I'm just going to copy and
paste that here
and this will be fill 3D react and then
I'm going to add one more parameter true
and let's also do the same thing for the
snake head
so fill 3direct
true
and let's actually count out these two
okay
and then finally for the snake body I'm
going to copy and paste this
combat this out
and then let's rename this so fill 3D
rect
and then let's pass in true
all right now let's run our program
so now we have a border around our tiles
so if I have the snake eat the food and
grow its segments
you can see each part is divided by the
border
and we have a fully functional game of
snake
so if this tutorial worked for you make
sure you give the video a like and if
you have any questions let me know Down
Below in the comments and if you want to
see more content like this make sure you
subscribe to the channel and I'll see
you in the next video
bye bye
استعرض المزيد من الفيديوهات ذات الصلة
5.0 / 5 (0 votes)