I didn't really expect this video to blow up. This was meant to be more of a practice project. I probably would have spent more time optimizing the code if I knew it would get this many views lol Well what you see is what you get I guess... //******************************************* public class SnakeGame { public static void main(String[] args) {
new GameFrame(); } } //******************************************* import javax.swing.JFrame; public class GameFrame extends JFrame{ GameFrame(){
} } //******************************************* import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.Random; public class GamePanel extends JPanel implements ActionListener{ static final int SCREEN_WIDTH = 1300; static final int SCREEN_HEIGHT = 750; static final int UNIT_SIZE = 50; static final int GAME_UNITS = (SCREEN_WIDTH*SCREEN_HEIGHT)/(UNIT_SIZE*UNIT_SIZE); static final int DELAY = 175; final int x[] = new int[GAME_UNITS]; final int y[] = new int[GAME_UNITS]; int bodyParts = 6; int applesEaten; int appleX; int appleY; char direction = 'R'; boolean running = false; Timer timer; Random random;
GamePanel(){ random = new Random(); this.setPreferredSize(new Dimension(SCREEN_WIDTH,SCREEN_HEIGHT)); this.setBackground(Color.black); this.setFocusable(true); this.addKeyListener(new MyKeyAdapter()); startGame(); } public void startGame() { newApple(); running = true; timer = new Timer(DELAY,this); timer.start(); } public void paintComponent(Graphics g) { super.paintComponent(g); draw(g); } public void draw(Graphics g) {
keep getting this error, "Error: Could not find or load main class snakeGame" when i try to run the code, it compiles fine but it produces this error after i try to run it. Help on this pls thank you.
Great video! I am working my way through my CS degree and am writing programs that I have to think about for 10x longer than it takes me to code them. Videos like yours remind me that programming is FUN!. It also helps me to understand how the concepts we are learning are used in everyday applications. Subscribed my man! Thanks again!
I'm on the exact same boat. College is so much t a l k i n g about code and not actually coding. I was finally like "Alright i'm just gonna follow a long a few things" and its helped 100x more with learning application than reading it from my text book.
straight-forward, short, easy to understand; I came across your channel through this video and I am happy to watch the whole Java playlist and I´m glad that you still making videos. Well done sir!
Your code is great, but i have a suggestion. At 9:12 You define and initialize the GAME_UNIT final constans, which later creates a huge and unnecessary X[] and y[] coordinate arrays. I would rather write this: _static final int GAME_UNITS = (SCREEN_WIDTH * SCREEN_HEIGHT) / _*_*(UNIT_SIZE*UNIT_SIZE); // 576_** In this case the x[] and y[] arrays will be at size 576 which equals 24x24, and in this case this is the exact size of the the game field. After that I would initialize the arrays like this: final int x[] = new int[GAME_UNITS / (SCREEN_WIDTH / UNIT_SIZE)]; which will give you an array with 24 elements. *This way You will save some memory.*
@@belalehner3937 bro btw i didnot get the move method of the snake especcially first part x[i] = x[i-1] , y[i] = y [i-1] part like what does that mean? Howbit makes it move to the right? I dont understand
No, x[0] y[0] is referring to the head of the snake because this is the first segment until ... x[6] y[6] which is the last segment of the snake body at first. So , in this loop, the sixth body segment which is the last body segment gets the position of the fifth body segment, so it moves right. The same about the fifth segment which gets the coordinates of the fourth coordinates, and so on until you get into the head. So in this way, you shift the snake body including the head to the right.
@@Dartanghan you're wrong because there's a switch statement after that loop which moves the head separately opposed to the rest of the body segments. It means, that if you for example moves the snake down, all the body segments follow each other until they reach the head - this is the loop After that begins the switch statement which gets the input 'D' so the snake head moves down , and all the body segment follow it when the loop begins again
00:03 Creating a snake game using Java 03:36 Setting up the game frame and necessary methods 08:15 Initializing game variables and arrays for the snake game. 12:00 Initializing game panel with timer and random class instance 15:39 Creating a grid for visualization 19:04 Creating the move method for the snake game. 22:08 Shifting coordinates and changing snake direction 25:28 Setting the color and implementing movement for the snake's body 29:06 Checking for snake collision with borders and controlling the snake's movement. 32:58 Updating snake position and increasing body parts 36:42 Placing game over and score display on the screen 39:59 Using random colors to create a multicolored snake
Bro, I'm sure all the people who watch your videos are enjoying your style of teaching and also like your tips. I really enjoy watching all of your tutorials, you make things look fine and easy. Keep it up, Bro!
Great tutorial, I just started learning Java and had no idea it was so powerful. I did some C++ and it seemed I needed a 3rd party framework for everything, but Java has native libraries for just about everything it seems. All the different classes/interfaces and functions/methods are difficult to keep up with but this video is helping a beginner like me become more familiar.
Hey, you can use the fallthrough principle, by adding more cases on top of others and leaving them empty, to better organize your code like this: switch(e.getKeyCode()) { case KeyEvent.VK_A: case KeyEvent.VK_LEFT: if(direction != 'R') { direction = 'L'; } break; case KeyEvent.VK_D: case KeyEvent.VK_RIGHT: if(direction != 'L') { direction = 'R'; } break; case KeyEvent.VK_W: case KeyEvent.VK_UP: if(direction != 'D') { direction = 'U'; } break; case KeyEvent.VK_S: case KeyEvent.VK_DOWN: if(direction != 'U') { direction = 'D'; } break; }
Thank you for this tutorial ! I got stuck twice while coding it, once my snake didn't move anymore and the other the apple was drawn wrong so the snake couldn't detect it. Both were my bad, now it works fine, had a lot of fun with this
@@makslubas99 idk what problem did you face, but in my case i used an else block after the if(running) statement, inside the actionPerformed method which didnt let my snake move for some reason.
Im also preparing for uni next year can you tell me if these videos actually help or if you have some tips,advice or videos you can share i would appreciate it so much and good luck throughout your journey bro
You cannot imagine how you helped me, Bro. I liked this code so much I'm improving it to present it as a simple project for my school :) My plans are: Restart button Pause menu Top score
Wow, that's a pretty impressive score you got In the end. Not that you are only good at coding but also at the games you create. Also thank you for your helpful tutorial.
To shift all lignes or format them in the right tab select all (Ctrl + A) then use the eclipse shortcut (Ctrl + I) or (Ctrl + Shift + I), and for organizing imports use this shortcut (Ctrl +Shift + O)
There's a bug in the checkCollision() method for right border and bottom border that lets you go through the screen that can be solved by adding an " = " after ">" sign or by substracting 1 "UNIT_SIZE": 1. By adding "=" //Checks if head touches right border. if (x[0] >= SCREEN_WIDTH) { running = false; //Checks if head touches bottom border. if (y[0] >= SCREEN_HEIGHT){ running = false; 2. By substracting "UNIT_SIZE" //Checks if head touches right border. if (x[0] > SCREEN_WIDTH - UNIT_SIZE) { running = false; //Checks if head touches bottom border. if (y[0] > SCREEN_HEIGHT - UNIT_SIZE){ running = false;
Hey fantastic tutorial, thank you! One thing I noticed that is off a bit, the checkCollisions() is off by one UNIT_SIZE on the right and bottom, so you can actually go slightly off the screen on those sides. I just subtracted UNIT_SIZE to fix this. if(x[0] > SCREEN_WIDTH-UNIT_SIZE) { running = false; } & if(y[0] > SCREEN_HEIGHT-UNIT_SIZE) { running = false; } Can't wait to dig into more of your videos, thanks again!
yep. What I did was change those two ifs to be equal or greater than SCREEN_WIDTH/SCREEN_HEIGHT I'm a beginner, so I barely understood anything haha, but I thought this would fix it, and I think it did xd
I just substracted screen width or height by one in the condition, if the snakes head is greater than the height or with then its head would go out of the borders
This is the highest quality coding channel I have ever stumbled upon. I will be making full use of the content he is providing. Hopefully he has some more advanced content too.
Amazing tutorial. Not just writing code in hypersonic speed but actually explaining it and have fun. Thanks a lot and please keep up the great Java videos!
Hello there sir, I am a Student learning Java on a Second Year Level , we are currently on the CLI Programming lessons but i already did my advanced learning and studies and i saw this video , and find it very inspiring to me and i am planning to add this on my Mini System Project, I may ask for the source code of your game if you will give me permission :) .. just for educational purposes
} } //***************************************** import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.Random; public class GamePanel extends JPanel implements ActionListener{ static final int SCREEN_WIDTH = 1300; static final int SCREEN_HEIGHT = 750; static final int UNIT_SIZE = 50; static final int GAME_UNITS = (SCREEN_WIDTH*SCREEN_HEIGHT)/(UNIT_SIZE*UNIT_SIZE); static final int DELAY = 175; final int x[] = new int[GAME_UNITS]; final int y[] = new int[GAME_UNITS]; int bodyParts = 6; int applesEaten; int appleX; int appleY; char direction = 'R'; boolean running = false; Timer timer; Random random;
GamePanel(){ random = new Random(); this.setPreferredSize(new Dimension(SCREEN_WIDTH,SCREEN_HEIGHT)); this.setBackground(Color.black); this.setFocusable(true); this.addKeyListener(new MyKeyAdapter()); startGame(); } public void startGame() { newApple(); running = true; timer = new Timer(DELAY,this); timer.start(); } public void paintComponent(Graphics g) { super.paintComponent(g); draw(g); } public void draw(Graphics g) {
There is a small bug in this Programm, if the snake goes to the right, and you quickly press down and left. The snake would just bite in itself bc the head turns right into the snake instead of moving down and then left
Great tutorial. Like the way you code, you should make a tutorial about how we should build up a project and why. Pro tip: Work on the titles, and editing -> Your channel deserved to be much bigger
Thanks for the vid, created the game successfully although I am confused about a lot of things since plenty of new stuff was introduced here lol, guess im better off heading to your earlier guides before doing any more of these :D
tysm for the tutorial! I usually have a hard time following tutorials like these but this one was easy for me to follow and understand even though I only know very basic java. This really helped me, thank you!
You just earned yourself one more subscriber! I've ignored learning Java for many years but it's now come down to Java Or Nothing. I'm only newbie with only a handful of months learning but I'm thoroughly enjoying every minute of it, as scary as it get at times... still a long way to go & hoping learn more.
Hello! Sorry for acting like a n00b but can you please tell us how to add background music to the games? Thank you in advance. Keep up the good work. EDIT: I did my research and figured out.
That's a good question! It's actually very difficult to do so lol. That may require another video topic. This article I found explains how to play .mp3 files. However you may need to download javazoom. Java kind of sucks when it comes to audio :/ www.tutorialsfield.com/how-to-play-mp3-file-in-java/
You learned me a lot about graphics and how a basic game works. However i had one problem: my frame started kind of shacking when i didn't moved my mouse or pressed a key. I fixt it by adding this to the main class: " System.setProperty("sun.java2d.opengl", "true");" Now everything runs smoothly. I don't now if anyone else had this problem or if you now the cause of this issue? but thx for opening my eyes in the Gaming World. :-)
This was fun. I'm wondering if it would be easier to make Apple and Snake classes and if so was that idea opted to make the code more easier to read for new coder?
Sir! I am from Pakistan. Amazing Explanation of Snake Game working. Keep it up, sir! Please make some more projects using Graphics in Java or can you please make tutorials on how to use Graphics class in java. I shall be thankful to you. Love from Pakistan. ♥♥♥
Hello ! Thanks for the great Video ! Just one thing that didn't work for me and that, when I wrote the lines and created the Apple .. nothing showed up on the screen and it remained black .. nothing is added at all ! How to fix this ?
Really struggling lately. I wish I knew how to even think of what I would need when creating a simple game like this. I'm starting to feel like a hopeless idiot.
My program is running till 15:45 .I had created that panel but after that its is not showing any grid, apple or snake on the screen and also not showing any error in the code.
Thank you for the tutorial. Can you or anyone else please explain how x[] and y[] array are getting initial values, i.e how it get to know the coordiates?
First of all I really loved your tutorial! You've made OOP look very simple. However I encountered a problem within this game when I wrote in C for just console. In your code you just check if the head coordinate of the snake matches that of the apple and if it is true the coordinates of the apple exist anywhere outside of the head. Yet as I clearly notice at 40:51 the apple doesn't show up in the canvas, which means that the apple is inside the snake's body. Your code doesn't check if the apple's coordinates match the coordinates of the body hence causing the apple to appear inside the body. So the same problem bothered me in C too and I tried to write an algorithm to figure it out. Once I'm sure my algorithm works properly, I'll post it here. Hope I didn't miss anything in the algorithm. Keep doing this great job bro. Thank you a lot. Loved it!
Lovely. I was excited for this one since early on on the playlist and its great. Thats an interesting way of setting a 2d grid of blocks or places that the sprites can be placed in. I was wondering about making a gui library and a physics or game engine tho ... despite being a beginner lol reaching for the unreachable i guess ... but i learned that problems are actually good in coding because by the time you solve the issues, you understand the reasons behind it
Always doubted my java, but this tutorual has inspired me and given me a very strong foundation, nice tutorial bro, thank you BIG UP!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
So I'm learning Java for the first time, and I was curious, what calls the draw and paintComponent methods? is it that the JPanel finds them automatically and calls them from its class?
So actually time.start() calls all his actions listeners every 75 mili seconds (cause of line timer = new Timer(DELAY,this); and all the actions listeners here are public void actionPerformed(ActionEvent e) and public void keyPressed(KeyEvent e)
Really good Snake game tutorial, now I'll build my own snake game like this one and add some of my own functionality such as giving the player 3 lives and adding menu bar so they can restart the game without having to close and again run the program.
I appreciate your time that you put in to these videos. And, you really know your stuff. I think, for me, I'm still new to programming; I know very little about programming, and I think I take awhile to catch on too. But, I wish you would give more details like "this part of the code does this," etc.
Neat project :D Hoping following along with many of these projects over the summer will help my mind absorb some of the info. Also this was a lowkey flex that you're just goated at snake, huh?
I didn't really expect this video to blow up. This was meant to be more of a practice project.
I probably would have spent more time optimizing the code if I knew it would get this many views lol
Well what you see is what you get I guess...
//*******************************************
public class SnakeGame {
public static void main(String[] args) {
new GameFrame();
}
}
//*******************************************
import javax.swing.JFrame;
public class GameFrame extends JFrame{
GameFrame(){
this.add(new GamePanel());
this.setTitle("Snake");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.pack();
this.setVisible(true);
this.setLocationRelativeTo(null);
}
}
//*******************************************
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class GamePanel extends JPanel implements ActionListener{
static final int SCREEN_WIDTH = 1300;
static final int SCREEN_HEIGHT = 750;
static final int UNIT_SIZE = 50;
static final int GAME_UNITS = (SCREEN_WIDTH*SCREEN_HEIGHT)/(UNIT_SIZE*UNIT_SIZE);
static final int DELAY = 175;
final int x[] = new int[GAME_UNITS];
final int y[] = new int[GAME_UNITS];
int bodyParts = 6;
int applesEaten;
int appleX;
int appleY;
char direction = 'R';
boolean running = false;
Timer timer;
Random random;
GamePanel(){
random = new Random();
this.setPreferredSize(new Dimension(SCREEN_WIDTH,SCREEN_HEIGHT));
this.setBackground(Color.black);
this.setFocusable(true);
this.addKeyListener(new MyKeyAdapter());
startGame();
}
public void startGame() {
newApple();
running = true;
timer = new Timer(DELAY,this);
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
}
public void draw(Graphics g) {
if(running) {
/*
for(int i=0;i0;i--) {
x[i] = x[i-1];
y[i] = y[i-1];
}
switch(direction) {
case 'U':
y[0] = y[0] - UNIT_SIZE;
break;
case 'D':
y[0] = y[0] + UNIT_SIZE;
break;
case 'L':
x[0] = x[0] - UNIT_SIZE;
break;
case 'R':
x[0] = x[0] + UNIT_SIZE;
break;
}
}
public void checkApple() {
if((x[0] == appleX) && (y[0] == appleY)) {
bodyParts++;
applesEaten++;
newApple();
}
}
public void checkCollisions() {
//checks if head collides with body
for(int i = bodyParts;i>0;i--) {
if((x[0] == x[i])&& (y[0] == y[i])) {
running = false;
}
}
//check if head touches left border
if(x[0] < 0) {
running = false;
}
//check if head touches right border
if(x[0] > SCREEN_WIDTH) {
running = false;
}
//check if head touches top border
if(y[0] < 0) {
running = false;
}
//check if head touches bottom border
if(y[0] > SCREEN_HEIGHT) {
running = false;
}
if(!running) {
timer.stop();
}
}
public void gameOver(Graphics g) {
//Score
g.setColor(Color.red);
g.setFont( new Font("Ink Free",Font.BOLD, 40));
FontMetrics metrics1 = getFontMetrics(g.getFont());
g.drawString("Score: "+applesEaten, (SCREEN_WIDTH - metrics1.stringWidth("Score: "+applesEaten))/2, g.getFont().getSize());
//Game Over text
g.setColor(Color.red);
g.setFont( new Font("Ink Free",Font.BOLD, 75));
FontMetrics metrics2 = getFontMetrics(g.getFont());
g.drawString("Game Over", (SCREEN_WIDTH - metrics2.stringWidth("Game Over"))/2, SCREEN_HEIGHT/2);
}
@Override
public void actionPerformed(ActionEvent e) {
if(running) {
move();
checkApple();
checkCollisions();
}
repaint();
}
public class MyKeyAdapter extends KeyAdapter{
@Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_LEFT:
if(direction != 'R') {
direction = 'L';
}
break;
case KeyEvent.VK_RIGHT:
if(direction != 'L') {
direction = 'R';
}
break;
case KeyEvent.VK_UP:
if(direction != 'D') {
direction = 'U';
}
break;
case KeyEvent.VK_DOWN:
if(direction != 'U') {
direction = 'D';
}
break;
}
}
}
}
//*******************************************
I- THANK YOU!!!
why are my listeners no working man! really need help here
Is this code is correct
@@divakarkumarjha1171 put the keylistener in under GameFrame class
keep getting this error, "Error: Could not find or load main class snakeGame" when i try to run the code, it compiles fine but it produces this error after i try to run it. Help on this pls thank you.
A fun channel with good English? Am I dead? Is this heaven?
See Brackeys, he is the King Of Code, but now he retired :(
@Dev Milan Chakraborty :( yes, really, really sad
Watch the coding train... He's great too.
@@covid-21delta99 ☹
@@NHbinaaa111 yep, He just posted yesterday(ノ◕ヮ◕)ノ*.✧
Great video! I am working my way through my CS degree and am writing programs that I have to think about for 10x longer than it takes me to code them. Videos like yours remind me that programming is FUN!. It also helps me to understand how the concepts we are learning are used in everyday applications. Subscribed my man! Thanks again!
I'm on the exact same boat. College is so much t a l k i n g about code and not actually coding. I was finally like "Alright i'm just gonna follow a long a few things" and its helped 100x more with learning application than reading it from my text book.
3 years ago and still helping !! Thank you for giving up your time to help others learn for free!!
This may be one of the most underrated coding tutorial/learning youtube channels with out a doubt
Indeed
thanks man took awhile to make
straight-forward, short, easy to understand;
I came across your channel through this video and I am happy to watch the whole Java playlist and I´m glad that you still making videos.
Well done sir!
Thanks man took awhile to make
bruh you even added ; at the end
@@aspidinton lol
@@itachu. Truly a programmer moment
@@aspidinton truly a ";" moment
Awesome video! It's short, sweet, to the point; and best of all, it's fairly simple and straight forward. Thank you for sharing the knowledge!
Who said it was short
explanation 100, very easy to understand, code neatness 100. thank you
it doesnt run for me on netbeans, what did you do to run it?
Your code is great, but i have a suggestion. At 9:12 You define and initialize the GAME_UNIT final constans, which later creates a huge and unnecessary X[] and y[] coordinate arrays. I would rather write this: _static final int GAME_UNITS = (SCREEN_WIDTH * SCREEN_HEIGHT) / _*_*(UNIT_SIZE*UNIT_SIZE); // 576_** In this case the x[] and y[] arrays will be at size 576 which equals 24x24, and in this case this is the exact size of the the game field. After that I would initialize the arrays like this: final int x[] = new int[GAME_UNITS / (SCREEN_WIDTH / UNIT_SIZE)]; which will give you an array with 24 elements. *This way You will save some memory.*
ı think it could be like this for x SCREEN_WIDTH/UNIT_SIZE = 600/25 =24 for y screenHeight/ unitSize =600/25 =24
@@belalehner3937 bro btw i didnot get the move method of the snake especcially first part x[i] = x[i-1] , y[i] = y [i-1] part like what does that mean? Howbit makes it move to the right? I dont understand
No, x[0] y[0] is referring to the head of the snake because this is the first segment until ... x[6] y[6] which is the last segment of the snake body at first.
So , in this loop, the sixth body segment which is the last body segment gets the position of the fifth body segment, so it moves right.
The same about the fifth segment which gets the coordinates of the fourth coordinates, and so on until you get into the head.
So in this way, you shift the snake body including the head to the right.
@@moshezechariah3705 i think if snakehead doesnot move body doesnot move either
@@Dartanghan you're wrong because there's a switch statement after that loop which moves the head separately opposed to the rest of the body segments.
It means, that if you for example moves the snake down, all the body segments follow each other until they reach the head - this is the loop
After that begins the switch statement which gets the input 'D' so the snake head moves down , and all the body segment follow it when the loop begins again
Underated is the only word that describes you bro. Thanks
00:03 Creating a snake game using Java
03:36 Setting up the game frame and necessary methods
08:15 Initializing game variables and arrays for the snake game.
12:00 Initializing game panel with timer and random class instance
15:39 Creating a grid for visualization
19:04 Creating the move method for the snake game.
22:08 Shifting coordinates and changing snake direction
25:28 Setting the color and implementing movement for the snake's body
29:06 Checking for snake collision with borders and controlling the snake's movement.
32:58 Updating snake position and increasing body parts
36:42 Placing game over and score display on the screen
39:59 Using random colors to create a multicolored snake
Hey bro I think i did everything right but when i run it just a black window pop up. I am new to this so can you tell me what can be wrong?
This is going to be #1 Java channel on TH-cam
Yes
Bro, I'm sure all the people who watch your videos are enjoying your style of teaching and also like your tips. I really enjoy watching all of your tutorials, you make things look fine and easy. Keep it up, Bro!
Thank you very much for your help, this is my first massive JAVA project. You are a great teacher, good luck!
Great tutorial, I just started learning Java and had no idea it was so powerful. I did some C++ and it seemed I needed a 3rd party framework for everything, but Java has native libraries for just about everything it seems. All the different classes/interfaces and functions/methods are difficult to keep up with but this video is helping a beginner like me become more familiar.
Hey guys, i added this to my code, to also move with the wasd:
public void keyTyped(KeyEvent e) {
switch(e.getKeyChar()) {
case 'a':
if(direction != 'R') {
direction = 'L';
}
break;
case 'w':
if(direction != 'D') {
direction = 'U';
}
break;
case 's':
if(direction != 'U') {
direction = 'D';
}
break;
case 'd':
if(direction != 'L') {
direction = 'R';
}
break;
default:
break;
}
}
this goes after the keypressed method, i find it useful for me because I play a lot of FPS games so yeah i added it for convenience
help me bro, it says the selection cannot be launched and there are no recent launches.. I want a sol..
@@mahisai4186I have the same thing happening idk what to do
Hey, you can use the fallthrough principle, by adding more cases on top of others and leaving them empty, to better organize your code like this:
switch(e.getKeyCode()) {
case KeyEvent.VK_A:
case KeyEvent.VK_LEFT:
if(direction != 'R') {
direction = 'L';
}
break;
case KeyEvent.VK_D:
case KeyEvent.VK_RIGHT:
if(direction != 'L') {
direction = 'R';
}
break;
case KeyEvent.VK_W:
case KeyEvent.VK_UP:
if(direction != 'D') {
direction = 'U';
}
break;
case KeyEvent.VK_S:
case KeyEvent.VK_DOWN:
if(direction != 'U') {
direction = 'D';
}
break;
}
Thank you for this tutorial ! I got stuck twice while coding it, once my snake didn't move anymore and the other the apple was drawn wrong so the snake couldn't detect it. Both were my bad, now it works fine, had a lot of fun with this
how did u fix the snake not moving i am currently having this issue
I'm still having issues cz the snake ain't moving.
what could I be doing Wrong?
@@makslubas99 My snake is not moving as well. Can u help me please.
@@makslubas99 idk what problem did you face, but in my case i used an else block after the if(running) statement, inside the actionPerformed method which didnt let my snake move for some reason.
@@Cyber_Boy101 i did write (running = false) and not (!running)
Great video, just finished it and works perfect, this is the first fun thing ive done with java, thanks for the videos,keep up the great work.
I have been learnt html css javascript and java by watching your video. i have much respect for you. thank you very much!!
This was a really good experience.
I never get bored with your video.
thank you for all the work under ground, your videos are so helpful.
I'm preparing for uni mate, so these "learn through projects" videos are helping a lot. Keep it up and thank you!
same bro, you keep it up too and good luck
Im also preparing for uni next year can you tell me if these videos actually help or if you have some tips,advice or videos you can share i would appreciate it so much and good luck throughout your journey bro
bro, your channel is truly underrated. u deserve more than at least 10,000,000 subs
Thank you 🙏 Bro code. My instructor cited your video sometimes and I learned a lot from your video. It’s cool. Appreciate your work.❤
You cannot imagine how you helped me, Bro. I liked this code so much I'm improving it to present it as a simple project for my school :)
My plans are:
Restart button
Pause menu
Top score
@@ClumpypooCP i am not presentig it as mine, I just need to study
Wow, that's a pretty impressive score you got In the end. Not that you are only good at coding but also at the games you create. Also thank you for your helpful tutorial.
I recently started watching your gui tutorial, and have learned so much about java thank you so much
I have completed this project. It was amazing. Give us more project like this.
This is so amazing!!!! Thankyou!!!!!!
thanks for watching!
To shift all lignes or format them in the right tab select all (Ctrl + A) then use the eclipse shortcut (Ctrl + I) or (Ctrl + Shift + I), and for organizing imports use this shortcut (Ctrl +Shift + O)
There's a bug in the checkCollision() method for right border and bottom border that lets you go through the screen that can be solved by adding an " = " after ">" sign or by substracting 1 "UNIT_SIZE":
1. By adding "="
//Checks if head touches right border.
if (x[0] >= SCREEN_WIDTH) {
running = false;
//Checks if head touches bottom border.
if (y[0] >= SCREEN_HEIGHT){
running = false;
2. By substracting "UNIT_SIZE"
//Checks if head touches right border.
if (x[0] > SCREEN_WIDTH - UNIT_SIZE) {
running = false;
//Checks if head touches bottom border.
if (y[0] > SCREEN_HEIGHT - UNIT_SIZE){
running = false;
Excellent tutorial of a simple snake game project with proper explanation. Thank you.
Hey fantastic tutorial, thank you! One thing I noticed that is off a bit, the checkCollisions() is off by one UNIT_SIZE on the right and bottom, so you can actually go slightly off the screen on those sides. I just subtracted UNIT_SIZE to fix this.
if(x[0] > SCREEN_WIDTH-UNIT_SIZE) {
running = false;
}
&
if(y[0] > SCREEN_HEIGHT-UNIT_SIZE) {
running = false;
}
Can't wait to dig into more of your videos, thanks again!
i noticed that in the video, thank you for this comment :)
yep. What I did was change those two ifs to be equal or greater than SCREEN_WIDTH/SCREEN_HEIGHT
I'm a beginner, so I barely understood anything haha, but I thought this would fix it, and I think it did xd
I just substracted screen width or height by one in the condition, if the snakes head is greater than the height or with then its head would go out of the borders
This is really a good game... where I learned lot of graphics...
Thank you buddy......
This is the highest quality coding channel I have ever stumbled upon. I will be making full use of the content he is providing. Hopefully he has some more advanced content too.
help me bro, it says the selection cannot be launched and there are no recent launches.. I want a sol..
Amazing tutorial. Not just writing code in hypersonic speed but actually explaining it and have fun. Thanks a lot and please keep up the great Java videos!
help me bro, it says the selection cannot be launched and there are no recent launches.. I want a sol..
You create some of the best java tutorials I've ever come across thank you so much :)
Hello there sir, I am a Student learning Java on a Second Year Level , we are currently on the CLI Programming lessons but i already did my advanced learning and studies and i saw this video , and find it very inspiring to me and i am planning to add this on my Mini System Project, I may ask for the source code of your game if you will give me permission :) .. just for educational purposes
Hi Neil!
Here ya go:
//*****************************************
public class SnakeGame {
public static void main(String[] args) {
new GameFrame();
}
}
//*****************************************
import javax.swing.JFrame;
public class GameFrame extends JFrame{
GameFrame(){
this.add(new GamePanel());
this.setTitle("Snake");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.pack();
this.setVisible(true);
this.setLocationRelativeTo(null);
}
}
//*****************************************
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class GamePanel extends JPanel implements ActionListener{
static final int SCREEN_WIDTH = 1300;
static final int SCREEN_HEIGHT = 750;
static final int UNIT_SIZE = 50;
static final int GAME_UNITS = (SCREEN_WIDTH*SCREEN_HEIGHT)/(UNIT_SIZE*UNIT_SIZE);
static final int DELAY = 175;
final int x[] = new int[GAME_UNITS];
final int y[] = new int[GAME_UNITS];
int bodyParts = 6;
int applesEaten;
int appleX;
int appleY;
char direction = 'R';
boolean running = false;
Timer timer;
Random random;
GamePanel(){
random = new Random();
this.setPreferredSize(new Dimension(SCREEN_WIDTH,SCREEN_HEIGHT));
this.setBackground(Color.black);
this.setFocusable(true);
this.addKeyListener(new MyKeyAdapter());
startGame();
}
public void startGame() {
newApple();
running = true;
timer = new Timer(DELAY,this);
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
}
public void draw(Graphics g) {
if(running) {
/*
for(int i=0;i0;i--) {
x[i] = x[i-1];
y[i] = y[i-1];
}
switch(direction) {
case 'U':
y[0] = y[0] - UNIT_SIZE;
break;
case 'D':
y[0] = y[0] + UNIT_SIZE;
break;
case 'L':
x[0] = x[0] - UNIT_SIZE;
break;
case 'R':
x[0] = x[0] + UNIT_SIZE;
break;
}
}
public void checkApple() {
if((x[0] == appleX) && (y[0] == appleY)) {
bodyParts++;
applesEaten++;
newApple();
}
}
public void checkCollisions() {
//checks if head collides with body
for(int i = bodyParts;i>0;i--) {
if((x[0] == x[i])&& (y[0] == y[i])) {
running = false;
}
}
//check if head touches left border
if(x[0] < 0) {
running = false;
}
//check if head touches right border
if(x[0] > SCREEN_WIDTH) {
running = false;
}
//check if head touches top border
if(y[0] < 0) {
running = false;
}
//check if head touches bottom border
if(y[0] > SCREEN_HEIGHT) {
running = false;
}
if(!running) {
timer.stop();
}
}
public void gameOver(Graphics g) {
//Score
g.setColor(Color.red);
g.setFont( new Font("Ink Free",Font.BOLD, 40));
FontMetrics metrics1 = getFontMetrics(g.getFont());
g.drawString("Score: "+applesEaten, (SCREEN_WIDTH - metrics1.stringWidth("Score: "+applesEaten))/2, g.getFont().getSize());
//Game Over text
g.setColor(Color.red);
g.setFont( new Font("Ink Free",Font.BOLD, 75));
FontMetrics metrics2 = getFontMetrics(g.getFont());
g.drawString("Game Over", (SCREEN_WIDTH - metrics2.stringWidth("Game Over"))/2, SCREEN_HEIGHT/2);
}
@Override
public void actionPerformed(ActionEvent e) {
if(running) {
move();
checkApple();
checkCollisions();
}
repaint();
}
public class MyKeyAdapter extends KeyAdapter{
@Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_LEFT:
if(direction != 'R') {
direction = 'L';
}
break;
case KeyEvent.VK_RIGHT:
if(direction != 'L') {
direction = 'R';
}
break;
case KeyEvent.VK_UP:
if(direction != 'D') {
direction = 'U';
}
break;
case KeyEvent.VK_DOWN:
if(direction != 'U') {
direction = 'D';
}
break;
}
}
}
}}//*****************************************
@@BroCodez hey man, i wanna know, what does painComponent do?
@@Eric-vs2he If you don't use it, it will not erase the snake's body when it's moving.
Awesome...Thanks for the Tutorial.. Keep it up Bro Code !!!
Man, you are good at explaining. Please continue to build more game projects.
Thanks. I coded along as a new learner. Your explanations were top notch!
There is a small bug in this Programm, if the snake goes to the right, and you quickly press down and left. The snake would just bite in itself bc the head turns right into the snake instead of moving down and then left
This is great...all your videos are great...you rock dude!
I could never thank you enough! I learned a lot! Thank you so much.
MY CODE IS NOT RUNNING PROPERLY THROW THE EXCEPTION INDEX OUT OF BOUNDS PLEASE HELP
This is the best channel of java on TH-cam
Great tutorial. Like the way you code, you should make a tutorial about how we should build up a project and why. Pro tip: Work on the titles, and editing -> Your channel deserved to be much bigger
same profile picture lol
Great Tutorial. Easy to understand. I didn't play snake since 1999 on my NOKIA phone :)
help me bro, it says the selection cannot be launched and there are no recent launches.. I want a sol..
Thanks for this game... Your code is clean and tidy. Easy to read. Now I feel I understand swing much better. Thanks!!!
This was extremely helpful and the first tutorial that actually helped me. Thank you so much
thanks for watching Subhendu!
good job bro! as a programmer in other languages, this helped me learn the basic syntax of java.
Your voice totally remember me of Professor Akali's voice. Thanks for the tutorials :D
what a strange thing to think about here
I like that this isn't one of those videos where they explain what a variable is every time
Thanks for the vid, created the game successfully although I am confused about a lot of things since plenty of new stuff was introduced here lol, guess im better off heading to your earlier guides before doing any more of these :D
yeah,the color change is pretty cool,makes the game to the next level,you are a natural.
tysm for the tutorial!
I usually have a hard time following tutorials like these but this one was easy for me to follow and understand even though I only know very basic java.
This really helped me, thank you!
That was super fun to watch! GUI is an absolute nightmare to me but definitely will try this.
You just earned yourself one more subscriber!
I've ignored learning Java for many years but it's now come down to Java Or Nothing. I'm only newbie with only a handful of months learning but I'm thoroughly enjoying every minute of it, as scary as it get at times...
still a long way to go & hoping learn more.
Update??
Excellent dude. Expecting more java projects for beginners. keep rocking.
Hello! Sorry for acting like a n00b but can you please tell us how to add background music to the games?
Thank you in advance.
Keep up the good work.
EDIT: I did my research and figured out.
That's a good question! It's actually very difficult to do so lol. That may require another video topic. This article I found explains how to play .mp3 files. However you may need to download javazoom. Java kind of sucks when it comes to audio :/
www.tutorialsfield.com/how-to-play-mp3-file-in-java/
@@BroCodez Yeah.:/ I did it with .wav instead of .mp3.
Now I will know this too.
Thank you for your response.:D
very clear and simple to understand. I had no experince and I could add something to the code! Really good video, I suggest it.
This is a full tutorial to my school exercise lol. But I already finished it unfortunately
I wish I would be allowed to use java in school. We have to use pascal (shit lang)...
@@creepercheater0148 me too (pascal is the biggest shit ever)
@@gigo3795 ohh yess
Hey cool tutorial for java beginners
nice, found my weekend project
This is a big help! I'm planning on getting Java certified in a year or so, gotta start somewhere. Keep up the good work!
You learned me a lot about graphics and how a basic game works. However i had one problem: my frame started kind of shacking when i didn't moved my mouse or pressed a key. I fixt it by adding this to the main class: " System.setProperty("sun.java2d.opengl", "true");" Now everything runs smoothly. I don't now if anyone else had this problem or if you now the cause of this issue? but thx for opening my eyes in the Gaming World. :-)
thank you, I also had this problem. This fixed it.
Game is so much more responsive with this propert. Thanks!
amazing code with simplified understanding thanks buddy
What eclipse theme are you using? Btw really nice explanation 🔥👍
Big Fan of you bro. Make these games more. A new subscriber ❤️ is here.
This was fun. I'm wondering if it would be easier to make Apple and Snake classes and if so was that idea opted to make the code more easier to read for new coder?
Sir! I am from Pakistan. Amazing Explanation of Snake Game working. Keep it up, sir! Please make some more projects using Graphics in Java or can you please make tutorials on how to use Graphics class in java. I shall be thankful to you. Love from Pakistan. ♥♥♥
Hello ! Thanks for the great Video !
Just one thing that didn't work for me and that, when I wrote the lines and created the Apple .. nothing showed up on the screen and it remained black .. nothing is added at all !
How to fix this ?
Im having the same problem
This is awesome bro.
Thank you so much.
I love Java programming.
Really struggling lately. I wish I knew how to even think of what I would need when creating a simple game like this. I'm starting to feel like a hopeless idiot.
Lol
same hahaha
Your tutorials are amazing, but I’m having an issue, when I run the program nothing appears, how can I solve this?
most likely you are forgetting to run the draw(); method in the paintComponent(Graphics g) method
I found the best Coding teacher, I'm sure that I will master java soon
My program is running till 15:45 .I had created that panel but after that its is not showing any grid, apple or snake on the screen and also not showing any error in the code.
Same problem i got did you find the solution?
I Love it!!! I am done with my code too. Superb!!!
Thank you for the tutorial. Can you or anyone else please explain how x[] and y[] array are getting initial values, i.e how it get to know the coordiates?
i dont know this - but my guess is that it is part of the import settings (at the very top you have the imports =)
By default the initial value is zero
Bro casually shows us that he is a snake god
Great to get on board when I am a student and this has definitely helped me out with the methods and supers.
Thanks Bro!
First of all I really loved your tutorial! You've made OOP look very simple.
However I encountered a problem within this game when I wrote in C for just console. In your code you just check if the head coordinate of the snake matches that of the apple and if it is true the coordinates of the apple exist anywhere outside of the head. Yet as I clearly notice at 40:51 the apple doesn't show up in the canvas, which means that the apple is inside the snake's body.
Your code doesn't check if the apple's coordinates match the coordinates of the body hence causing the apple to appear inside the body. So the same problem bothered me in C too and I tried to write an algorithm to figure it out. Once I'm sure my algorithm works properly, I'll post it here. Hope I didn't miss anything in the algorithm.
Keep doing this great job bro. Thank you a lot. Loved it!
you got that code yet?
Lovely. I was excited for this one since early on on the playlist and its great. Thats an interesting way of setting a 2d grid of blocks or places that the sprites can be placed in. I was wondering about making a gui library and a physics or game engine tho ... despite being a beginner lol reaching for the unreachable i guess ... but i learned that problems are actually good in coding because by the time you solve the issues, you understand the reasons behind it
Woooow .. so well organised!!
can i run this code in visual studio code
Try it and see
yes
Always doubted my java, but this tutorual has inspired me and given me a very strong foundation, nice tutorial bro, thank you
BIG UP!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
So I'm learning Java for the first time, and I was curious, what calls the draw and paintComponent methods? is it that the JPanel finds them automatically and calls them from its class?
So actually time.start() calls all his actions listeners every 75 mili seconds (cause of line timer = new Timer(DELAY,this); and all the actions listeners here are public void actionPerformed(ActionEvent e) and public void keyPressed(KeyEvent e)
@@fabianzbranski2061 that is true but i'm getting an error when I type .start() and Timer(DELAY,this); i have not syntax erros tho
Really good Snake game tutorial, now I'll build my own snake game like this one and add some of my own functionality such as giving the player 3 lives and adding menu bar so they can restart the game without having to close and again run the program.
Hey do you know how to restart the game by pressing a key...
Great practice and great video, congratulations Bro Code!!!
wow... I learn more here....!
I appreciate your time that you put in to these videos. And, you really know your stuff. I think, for me, I'm still new to programming; I know very little about programming, and I think I take awhile to catch on too. But, I wish you would give more details like "this part of the code does this," etc.
WoW ! Thanks for such a great tutorial.
An excellent example for game's developers. And I really like it.
You are really good making videos .
Well done!!
This seriously reminds me of the meme "Do you ever look at someone and wonder... What is going ON inside their head??"
Really easy to understand. It was a really good video.
A good channel with good English and gives source code in the comments. Am I dreaming?!?!
You are the best Sir. Keep it up
Very complicated but very good👍👍
Good to know java still exists
thanks for this tutorial, I hope you can make more of these kind of videos in the future!
Neat project :D Hoping following along with many of these projects over the summer will help my mind absorb some of the info.
Also this was a lowkey flex that you're just goated at snake, huh?