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; } } } } //*******************************************
@farhanaparesai16413 жыл бұрын
I- THANK YOU!!!
@yashkadulkar60363 жыл бұрын
why are my listeners no working man! really need help here
@divakarkumarjha11713 жыл бұрын
Is this code is correct
@yashkadulkar60363 жыл бұрын
@@divakarkumarjha1171 put the keylistener in under GameFrame class
@lil_jeke3 жыл бұрын
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.
@areggrigorian79633 жыл бұрын
A fun channel with good English? Am I dead? Is this heaven?
@covid-21delta993 жыл бұрын
See Brackeys, he is the King Of Code, but now he retired :(
@covid-21delta993 жыл бұрын
@Dev Milan Chakraborty :( yes, really, really sad
@shivangmishra26423 жыл бұрын
Watch the coding train... He's great too.
@farnoodgh96263 жыл бұрын
@@covid-21delta99 ☹
@lener63453 жыл бұрын
@@NHbinaaa111 yep, He just posted yesterday(ノ◕ヮ◕)ノ*.✧
@maxxpellowski29163 жыл бұрын
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!
@trickorpete29872 жыл бұрын
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.
@colekrause58823 жыл бұрын
This may be one of the most underrated coding tutorial/learning youtube channels with out a doubt
@-_--le3zk3 жыл бұрын
Indeed
@jacobwall80663 жыл бұрын
thanks man took awhile to make
@janmail80184 жыл бұрын
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!
@jacobwall80663 жыл бұрын
Thanks man took awhile to make
@aspidinton2 жыл бұрын
bruh you even added ; at the end
@itachu.10 ай бұрын
@@aspidinton lol
@aspidinton10 ай бұрын
@@itachu. Truly a programmer moment
@itachu.10 ай бұрын
@@aspidinton truly a ";" moment
@americaneagle2073 Жыл бұрын
3 years ago and still helping !! Thank you for giving up your time to help others learn for free!!
@belalehner3937 Жыл бұрын
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.*
@Dartanghan2 ай бұрын
ı think it could be like this for x SCREEN_WIDTH/UNIT_SIZE = 600/25 =24 for y screenHeight/ unitSize =600/25 =24
@Dartanghan2 ай бұрын
@@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
@moshezechariah37052 ай бұрын
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.
@Dartanghan2 ай бұрын
@@moshezechariah3705 i think if snakehead doesnot move body doesnot move either
@moshezechariah37052 ай бұрын
@@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
@alexandrulolea4631 Жыл бұрын
I'm preparing for uni mate, so these "learn through projects" videos are helping a lot. Keep it up and thank you!
@frcjiang7654 Жыл бұрын
same bro, you keep it up too and good luck
@saleharja95383 жыл бұрын
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!
@mechasmoke3 жыл бұрын
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!
@justarandomguyontheinterne4400 Жыл бұрын
Who said it was short
@21kHzBANK21kHZ Жыл бұрын
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.
@MananGandhi3 жыл бұрын
bro, your channel is truly underrated. u deserve more than at least 10,000,000 subs
@keanjaycox79593 жыл бұрын
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!
@fazoodle79722 жыл бұрын
i noticed that in the video, thank you for this comment :)
@obedpadilla5264 Жыл бұрын
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
@SalmanM190 Жыл бұрын
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
@allamtajusarof56493 жыл бұрын
explanation 100, very easy to understand, code neatness 100. thank you
@marctaylorhooker75423 жыл бұрын
it doesnt run for me on netbeans, what did you do to run it?
@ewoutlagendijk73853 жыл бұрын
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
@makslubas993 жыл бұрын
how did u fix the snake not moving i am currently having this issue
@Cyber_Boy101 Жыл бұрын
I'm still having issues cz the snake ain't moving. what could I be doing Wrong?
@Cyber_Boy101 Жыл бұрын
@@makslubas99 My snake is not moving as well. Can u help me please.
@jarintabassum4795 Жыл бұрын
@@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.
@Felix-qk3dn4 ай бұрын
@@Cyber_Boy101 i did write (running = false) and not (!running)
@sergeyb60714 жыл бұрын
This is going to be #1 Java channel on KZbin
@valencehockey16683 жыл бұрын
Yes
@Phougat11 ай бұрын
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.
@njcreationskrgproduction82194 жыл бұрын
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
@BroCodez4 жыл бұрын
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; } } } }}//*****************************************
@Eric-vs2he Жыл бұрын
@@BroCodez hey man, i wanna know, what does painComponent do?
@tasneemayham974 Жыл бұрын
@@Eric-vs2he If you don't use it, it will not erase the snake's body when it's moving.
@cooler09b3 жыл бұрын
Thank you very much for your help, this is my first massive JAVA project. You are a great teacher, good luck!
@famelitegamer33174 жыл бұрын
I recently started watching your gui tutorial, and have learned so much about java thank you so much
@justinbanza47513 жыл бұрын
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.
@thezouchcoop3 жыл бұрын
Underated is the only word that describes you bro. Thanks
@diegoaristizabalElDiego223 жыл бұрын
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
@diegoaristizabalElDiego223 жыл бұрын
@@ClumpypooCP i am not presentig it as mine, I just need to study
@davyswanson74124 жыл бұрын
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.
@premkarki27 ай бұрын
Thank you 🙏 Bro code. My instructor cited your video sometimes and I learned a lot from your video. It’s cool. Appreciate your work.❤
@juanpablocuellar85063 жыл бұрын
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
@mahisai41863 жыл бұрын
help me bro, it says the selection cannot be launched and there are no recent launches.. I want a sol..
@dvm_asf Жыл бұрын
@@mahisai4186I have the same thing happening idk what to do
@roddy20156 ай бұрын
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; }
@yokisaku2 жыл бұрын
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!
@wasifali61693 жыл бұрын
Man, you are good at explaining. Please continue to build more game projects.
@foysalkhan28794 ай бұрын
I have completed this project. It was amazing. Give us more project like this.
@thekontuli28283 жыл бұрын
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.
@andiuptown171110 ай бұрын
Update??
@julchni31892 жыл бұрын
These videos are really helpful, I watch them with my friends on Voicely whenever we practice coding. We all agree that we learned more from KZbin videos than from school lol
@yeartwothousandfive Жыл бұрын
School only teach us the basics things in coding..
@SumbaSlice3 жыл бұрын
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!
@mahisai41863 жыл бұрын
help me bro, it says the selection cannot be launched and there are no recent launches.. I want a sol..
@carrotlemon26653 жыл бұрын
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!
@davidjuhasz51794 жыл бұрын
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
@Hassan-zw9tb3 жыл бұрын
same profile picture lol
@93f9d2 жыл бұрын
I have been learnt html css javascript and java by watching your video. i have much respect for you. thank you very much!!
@ScienceDayYT3 жыл бұрын
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;
@julesssssssss2 жыл бұрын
good job bro! as a programmer in other languages, this helped me learn the basic syntax of java.
@pranavigoud166711 ай бұрын
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
@Phougat10 ай бұрын
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?
@jisterl7485 Жыл бұрын
You create some of the best java tutorials I've ever come across thank you so much :)
@TechSupportDave3 жыл бұрын
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.
@mahisai41863 жыл бұрын
help me bro, it says the selection cannot be launched and there are no recent launches.. I want a sol..
@bruce90674 жыл бұрын
This is so amazing!!!! Thankyou!!!!!!
@BroCodez4 жыл бұрын
thanks for watching!
@robertkeiko Жыл бұрын
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.
@mr.fakeman47184 жыл бұрын
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.
@BroCodez4 жыл бұрын
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/
@mr.fakeman47184 жыл бұрын
@@BroCodez Yeah.:/ I did it with .wav instead of .mp3. Now I will know this too. Thank you for your response.:D
@ramazandurmaz30123 жыл бұрын
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!
@lucaswentzloff18992 жыл бұрын
you got that code yet?
@favillc5833 жыл бұрын
Your voice totally remember me of Professor Akali's voice. Thanks for the tutorials :D
@satsuki-rin3 жыл бұрын
what a strange thing to think about here
@jawadshah80433 жыл бұрын
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. ♥♥♥
@henryle39253 жыл бұрын
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
@snakepink81532 жыл бұрын
yeah,the color change is pretty cool,makes the game to the next level,you are a natural.
@Zechey3 жыл бұрын
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
@shahtanmay9022 жыл бұрын
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.
@hashim3992 жыл бұрын
Hey do you know how to restart the game by pressing a key...
@jasonclair50463 жыл бұрын
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?
@osamaahmedbhatti14463 жыл бұрын
Thankyou bro.I've never coded in Java before but watching this helped me understand and learn a lot. You've earned a sub. Keep it up and thanks a lot again
@dahoyasmine22483 жыл бұрын
I could never thank you enough! I learned a lot! Thank you so much.
@safaidansari96232 жыл бұрын
MY CODE IS NOT RUNNING PROPERLY THROW THE EXCEPTION INDEX OUT OF BOUNDS PLEASE HELP
@jawnaw20002 жыл бұрын
Thanks. I coded along as a new learner. Your explanations were top notch!
@nestam68444 жыл бұрын
This is a full tutorial to my school exercise lol. But I already finished it unfortunately
@creepercheater01483 жыл бұрын
I wish I would be allowed to use java in school. We have to use pascal (shit lang)...
@gigo37953 жыл бұрын
@@creepercheater0148 me too (pascal is the biggest shit ever)
@creepercheater01483 жыл бұрын
@@gigo3795 ohh yess
@jankubik28383 жыл бұрын
Great Tutorial. Easy to understand. I didn't play snake since 1999 on my NOKIA phone :)
@mahisai41863 жыл бұрын
help me bro, it says the selection cannot be launched and there are no recent launches.. I want a sol..
@subhendumandal72184 жыл бұрын
This was extremely helpful and the first tutorial that actually helped me. Thank you so much
@BroCodez4 жыл бұрын
thanks for watching Subhendu!
@med_reda_hak2 жыл бұрын
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)
@aaronfeys95703 жыл бұрын
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. :-)
@giovannimarcon7980 Жыл бұрын
thank you, I also had this problem. This fixed it.
@Toeterrr Жыл бұрын
Game is so much more responsive with this propert. Thanks!
@harsha40483 жыл бұрын
Big Fan of you bro. Make these games more. A new subscriber ❤️ is here.
@leaf564483 жыл бұрын
What eclipse theme are you using? Btw really nice explanation 🔥👍
@guruprasadsimimath907 ай бұрын
I missed "break;" after each case for "switch(direction)" the snake was going GameOver for every LEFT and UP directon thanks a lot BRO for teaching a noob how to build a Java game, this is a huge thing for me! ❣
@MrPaulOMalley2 жыл бұрын
Thank you so much for posting this tutorial. I learned a lot typing out the code for this game in Apache NetBeans 12.6 IDE. The only malfunction I came across occurs if, for example, the snake is going downward with its head not near any of its body "segments" (except "segment" # 1 of course) or, for the sake of clarity, with its entire body vertical in the game window and I rapidly press the left arrow followed by the up arrow, the game is over as the snake's head winds up colliding with its first body "segment". The snake's head doesn't make it one UNIT_SIZE distance to the left since the "up" directional change command is being issued so quickly right after the "left" directional change command. And, since the snake is technically not going downward anymore, it is allowed to move upward and thus end up colliding with itself (its first body "segment"). Apparently, the snake's directional changes are being processed faster than the changes to the x and y coordinates of all its body parts when the directional keys are pressed in rapid succession. Is there a remedy for this?
@MrPaulOMalley2 жыл бұрын
Eureka! I found a solution to the problem I previously mentioned. In the method public void keyPressed(KeyEvent e), I added an extra conditional statement to each case of the switch (e.getKeyCode()) block. The code is the following now for me in GamePanel.java: { case KeyEvent.VK_LEFT: if ((direction != 'R') && (Y[0] != Y[1])) direction = 'L'; break; case KeyEvent.VK_RIGHT: if ((direction != 'L') && (Y[0] != Y[1])) direction = 'R'; break; case KeyEvent.VK_UP: if ((direction != 'D') && (X[0] != X[1])) direction = 'U'; break; case KeyEvent.VK_DOWN: if ((direction != 'U') && (X[0] != X[1])) direction = 'D'; break; } These x and y coordinate conditional requirements for the head and the first body "segment" of the snake prevent any instantaneous 180-degree direction changes from rapidly pressing, for example, the left-arrow key followed by the up-arrow key (pressing one immediately after the other) when the snake is traveling downward as I described in my previous reply. An instantaneous 180-degree direction change involves the snake's head not moving leftward first before moving upward when the up-arrow key is pressed immediately after the left-arrow key. Problem solved.
@elidegen20002 жыл бұрын
you could build in a delay so that after every key press you will have to wait for example .5 sec until the next key press is registrated
@MrPaulOMalley2 жыл бұрын
@@elidegen2000 As you can see from my reply to my own comment, I concocted a solution that works flawlessly. However, I am interested in your delay solution since it is the more practical solution in other keyboard interface design implementations. I've tried putting a delay in via "try {Thread.sleep(600);} catch (InterruptedException ex) {Thread.currentThread().interrupt();}, but this only results in pausing the running of the program by 600 milliseconds. I get a pause in the snake's movement lasting .6 seconds, not a delay in getting the next keyboard press, which is what we want. Do you know where to place the delay in the Java code for the desired effect, that is, in which method?
@elidegen20002 жыл бұрын
@@MrPaulOMalley okay I don’t see your answer I’m sorry… unfortunately I’m a rookie so i don’t know either how to solve this… i also thought about trying with the sleep function but I don’t know any other solution
@oleknapiorkowski8980 Жыл бұрын
@@MrPaulOMalley its not working bro :( Do you have working solution?
@kemann38152 жыл бұрын
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
@ziskador3 жыл бұрын
I like that this isn't one of those videos where they explain what a variable is every time
@mennaeldamaty52693 жыл бұрын
Your tutorials are amazing, but I’m having an issue, when I run the program nothing appears, how can I solve this?
@techdoge36253 жыл бұрын
most likely you are forgetting to run the draw(); method in the paintComponent(Graphics g) method
@fatimaadreeta2 жыл бұрын
That was super fun to watch! GUI is an absolute nightmare to me but definitely will try this.
@husein_alfil3 жыл бұрын
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 ?
@oliver1233 жыл бұрын
Im having the same problem
@ChaperoneDad3 жыл бұрын
Great to get on board when I am a student and this has definitely helped me out with the methods and supers. Thanks Bro!
@AdachiGacha2 жыл бұрын
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?
@HaziqSeru Жыл бұрын
can i run this code in visual studio code
@architech59406 ай бұрын
Try it and see
@ghost-qp6yh5 ай бұрын
yes
@kasulejuma33143 жыл бұрын
Always doubted my java, but this tutorual has inspired me and given me a very strong foundation, nice tutorial bro, thank you BIG UP!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
@alexb27733 жыл бұрын
nice, found my weekend project
@mr.claroOF Жыл бұрын
This video was fabulous, a simple and very detailed lesson, however I would like to know how I could do to make a little system that resets the game, in a KeyPresser, I tried several ways and none worked as expected, I don't care idea how to reset snake pro values 0, 0 again. Could you please advise me on how to do this?
@MisterWealth3 жыл бұрын
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.
@osmansiddiqi40573 жыл бұрын
Lol
@kathrin39083 жыл бұрын
same hahaha
@刌 Жыл бұрын
I found the best Coding teacher, I'm sure that I will master java soon
@divyanshibhardwaj45442 жыл бұрын
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.
@hamzabutt753 Жыл бұрын
Same problem i got did you find the solution?
@tamasataniska30592 жыл бұрын
Above everything else, the last game play was so satisfying !
@gursevaksingh25043 жыл бұрын
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?
@TainDK2 жыл бұрын
i dont know this - but my guess is that it is part of the import settings (at the very top you have the imports =)
@yonasghirmay64732 жыл бұрын
By default the initial value is zero
@prajnap93942 жыл бұрын
This is really a good game... where I learned lot of graphics... Thank you buddy......
@justprem42153 жыл бұрын
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?
@fabianzbranski20613 жыл бұрын
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)
@spilza33103 жыл бұрын
@@fabianzbranski2061 that is true but i'm getting an error when I type .start() and Timer(DELAY,this); i have not syntax erros tho
@vindydog76643 жыл бұрын
Completed my first project !! 😀 Thank you very much!! Simple & clear explanation. Love to see u succeed ahead.
@safaidansari96232 жыл бұрын
please share code of snack game
@piyushsinghal95183 жыл бұрын
This seriously reminds me of the meme "Do you ever look at someone and wonder... What is going ON inside their head??"
@shrabantiroy67112 жыл бұрын
A good channel with good English and gives source code in the comments. Am I dreaming?!?!
@synfpv0072 жыл бұрын
This was very nice and fun programming on a rainy day - I modified your game where the snake will change color each time it eats an apple :)
@e.88862 жыл бұрын
Hi! May I ask how you did that? What does your code for that look like?
@MacN_ Жыл бұрын
Thank you for the tutorial! I completed this program and it all works just fine. ✌
@BlackMark3tBaby5 ай бұрын
Beautifully concise and easy to follow. Thanks for this! SUBBED!!
@Rasmus-tz3zp Жыл бұрын
This tutorial was really good. even though I did not understand much, I followed it and understood then basic concepts! I just wonder... HOW DO YOU KNOW all the steps for making a game like this? I wonder
@chemistry9130 Жыл бұрын
Good to know java still exists
@lovegirls102 жыл бұрын
This is a wonderful lesson because your guide absolutely understands. Thank you so much for your lesson.
@abhishek-gu6qt Жыл бұрын
amazing code with simplified understanding thanks buddy
@hizokadarkwolf2 жыл бұрын
This was amazing. I'm going to add new features and improve others. For instance, increase the speed of the snake, add a Restart Game option, save the highest scores, and add your initials to the saved scores.
@hizokadarkwolf2 жыл бұрын
I have already: - added an image and "restart game" text to the game over screen - added a restart game call
@danielnassi53042 жыл бұрын
@@hizokadarkwolf how?
@genisys3753 жыл бұрын
I had two problems with the snake: Sometimes lag and sometimes it went off the edges. If someone has any of these problems, here is the solution. The lag I resolved adding this line in the main class before call GameFrame: System.setProperty("sun.java2d.opengl", "true"); The problem with edges I resolved modifing the next if conditions in the checkCollitions method: //Check if head touches right border if (x[0] > SCREEN_WIDTH - UNIT_SIZE) { running = false; } //Check if head touches bottom border if (y[0] > SCREEN_HEIGHT - UNIT_SIZE) { running = false; } I work on Linux and I use Apache Netbeans.
@developerjunior4463 жыл бұрын
Bro Really Fantastic. I don't believe do it myself !!! Thank you so much. Hope Android course
@fiona76512 жыл бұрын
this is bringing me back to why i wanted to learn computer science
@raj143182 жыл бұрын
realy good code one queestion by which button the snake will move like left,right,up,down???
@zbigniewsak70453 жыл бұрын
An excellent example for game's developers. And I really like it.
@fixiple27227 ай бұрын
Thank you, I followed your tutorial. Everything went perfectly fine
@0ri0nexe Жыл бұрын
I love u. I am french and the coding content is soooo limited in my language, u speak with a perfect english and this is exactly the video I needed, thank u.
@xx-qf8pi3 жыл бұрын
Great video. This could be a series and you can perfect the game in each episode. e.g. Would be cool to have a tutorial on howt ot store the top 10 scores and input username once you hit top10.
@dean980523 жыл бұрын
@@ShanleH easy, use an array for the hi score list