Тёмный

Java snake game 🐍 

Bro Code
Подписаться 2,2 млн
Просмотров 1,5 млн
50% 1

Java snake game tutorial for beginners
#Java #snake #game
Coding boot camps hate him! See how he can teach you to code with this one simple trick...
Bro Code is the self-proclaimed #1 tutorial series on coding in various programming languages and other how-to videos in the known universe.

Опубликовано:

 

26 сен 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 1,6 тыс.   
@BroCodez
@BroCodez 4 года назад
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; } } } } //*******************************************
@farhanaparesai1641
@farhanaparesai1641 3 года назад
I- THANK YOU!!!
@yashkadulkar6036
@yashkadulkar6036 3 года назад
why are my listeners no working man! really need help here
@divakarkumarjha1171
@divakarkumarjha1171 3 года назад
Is this code is correct
@yashkadulkar6036
@yashkadulkar6036 3 года назад
@@divakarkumarjha1171 put the keylistener in under GameFrame class
@lil_jeke
@lil_jeke 3 года назад
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.
@areggrigorian7963
@areggrigorian7963 3 года назад
A fun channel with good English? Am I dead? Is this heaven?
@covid-21delta99
@covid-21delta99 3 года назад
See Brackeys, he is the King Of Code, but now he retired :(
@covid-21delta99
@covid-21delta99 3 года назад
@Dev Milan Chakraborty :( yes, really, really sad
@shivangmishra2642
@shivangmishra2642 3 года назад
Watch the coding train... He's great too.
@farnoodgh9626
@farnoodgh9626 3 года назад
@@covid-21delta99 ☹
@lener6345
@lener6345 3 года назад
@@NHbinaaa111 yep, He just posted yesterday(ノ◕ヮ◕)ノ*.✧
@maxxpellowski2916
@maxxpellowski2916 3 года назад
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!
@trickorpete2987
@trickorpete2987 2 года назад
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.
@colekrause5882
@colekrause5882 3 года назад
This may be one of the most underrated coding tutorial/learning youtube channels with out a doubt
@-_--le3zk
@-_--le3zk 3 года назад
Indeed
@jacobwall8066
@jacobwall8066 2 года назад
thanks man took awhile to make
@janmail8018
@janmail8018 4 года назад
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!
@jacobwall8066
@jacobwall8066 2 года назад
Thanks man took awhile to make
@aspidinton
@aspidinton 2 года назад
bruh you even added ; at the end
@julianthunellaxnas9787
@julianthunellaxnas9787 Год назад
nah ur crazy this was hard
@itachu.
@itachu. 8 месяцев назад
@@aspidinton lol
@aspidinton
@aspidinton 8 месяцев назад
@@itachu. Truly a programmer moment
@belalehner3937
@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.*
@Dartanghan
@Dartanghan Месяц назад
ı think it could be like this for x SCREEN_WIDTH/UNIT_SIZE = 600/25 =24 for y screenHeight/ unitSize =600/25 =24
@Dartanghan
@Dartanghan Месяц назад
@@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
@moshezechariah3705
@moshezechariah3705 26 дней назад
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
@Dartanghan 26 дней назад
@@moshezechariah3705 i think if snakehead doesnot move body doesnot move either
@moshezechariah3705
@moshezechariah3705 26 дней назад
@@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
@americaneagle2073
@americaneagle2073 Год назад
3 years ago and still helping !! Thank you for giving up your time to help others learn for free!!
@21kHzBANK21kHZ
@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.
@mechasmoke
@mechasmoke 3 года назад
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
@saleharja9538
@saleharja9538 3 года назад
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!
@premkarki2
@premkarki2 5 месяцев назад
Thank you 🙏 Bro code. My instructor cited your video sometimes and I learned a lot from your video. It’s cool. Appreciate your work.❤
@MananGandhi
@MananGandhi 3 года назад
bro, your channel is truly underrated. u deserve more than at least 10,000,000 subs
@keanjaycox7959
@keanjaycox7959 3 года назад
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!
@fazoodle7972
@fazoodle7972 2 года назад
i noticed that in the video, thank you for this comment :)
@obedpadilla5264
@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
@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
@allamtajusarof5649
@allamtajusarof5649 3 года назад
explanation 100, very easy to understand, code neatness 100. thank you
@marctaylorhooker7542
@marctaylorhooker7542 3 года назад
it doesnt run for me on netbeans, what did you do to run it?
@Phougat
@Phougat 10 месяцев назад
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.
@ewoutlagendijk7385
@ewoutlagendijk7385 3 года назад
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
@makslubas99 3 года назад
how did u fix the snake not moving i am currently having this issue
@Cyber_Boy101
@Cyber_Boy101 Год назад
I'm still having issues cz the snake ain't moving. what could I be doing Wrong?
@Cyber_Boy101
@Cyber_Boy101 Год назад
@@makslubas99 My snake is not moving as well. Can u help me please.
@jarintabassum4795
@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-qk3dn
@Felix-qk3dn 2 месяца назад
​@@Cyber_Boy101 i did write (running = false) and not (!running)
@thezouchcoop
@thezouchcoop 3 года назад
Underated is the only word that describes you bro. Thanks
@davyswanson7412
@davyswanson7412 3 года назад
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.
@justinbanza4751
@justinbanza4751 3 года назад
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.
@diegoaristizabalElDiego22
@diegoaristizabalElDiego22 3 года назад
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
@diegoaristizabalElDiego22
@diegoaristizabalElDiego22 3 года назад
@@ClumpypooCP i am not presentig it as mine, I just need to study
@cooler09b
@cooler09b 3 года назад
Thank you very much for your help, this is my first massive JAVA project. You are a great teacher, good luck!
@sergeyb6071
@sergeyb6071 4 года назад
This is going to be #1 Java channel on RU-vid
@valencehockey1668
@valencehockey1668 3 года назад
Yes
@yokisaku
@yokisaku 2 года назад
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!
@njcreationskrgproduction8219
@njcreationskrgproduction8219 3 года назад
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
@BroCodez
@BroCodez 3 года назад
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
@Eric-vs2he Год назад
@@BroCodez hey man, i wanna know, what does painComponent do?
@tasneemayham974
@tasneemayham974 Год назад
@@Eric-vs2he If you don't use it, it will not erase the snake's body when it's moving.
@carrotlemon2665
@carrotlemon2665 2 года назад
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!
@robertkeiko
@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.
@bruce9067
@bruce9067 4 года назад
This is so amazing!!!! Thankyou!!!!!!
@BroCodez
@BroCodez 4 года назад
thanks for watching!
@julchni3189
@julchni3189 2 года назад
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 RU-vid videos than from school lol
@yeartwothousandfive
@yeartwothousandfive Год назад
School only teach us the basics things in coding..
@juanpablocuellar8506
@juanpablocuellar8506 3 года назад
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
@mahisai4186
@mahisai4186 3 года назад
help me bro, it says the selection cannot be launched and there are no recent launches.. I want a sol..
@dvm_asf
@dvm_asf Год назад
@@mahisai4186I have the same thing happening idk what to do
@roddy2015
@roddy2015 5 месяцев назад
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; }
@guruprasadsimimath90
@guruprasadsimimath90 6 месяцев назад
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! ❣
@wasifali6169
@wasifali6169 3 года назад
Man, you are good at explaining. Please continue to build more game projects.
@AdachiGacha
@AdachiGacha 2 года назад
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?
@TechSupportDave
@TechSupportDave 3 года назад
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.
@mahisai4186
@mahisai4186 3 года назад
help me bro, it says the selection cannot be launched and there are no recent launches.. I want a sol..
@henryle3925
@henryle3925 3 года назад
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
@jisterl7485
@jisterl7485 Год назад
You create some of the best java tutorials I've ever come across thank you so much :)
@davidjuhasz5179
@davidjuhasz5179 3 года назад
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-zw9tb
@Hassan-zw9tb 3 года назад
same profile picture lol
@foysalkhan2879
@foysalkhan2879 2 месяца назад
I have completed this project. It was amazing. Give us more project like this.
@divyanshibhardwaj4544
@divyanshibhardwaj4544 2 года назад
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
@hamzabutt753 Год назад
Same problem i got did you find the solution?
@jankubik2838
@jankubik2838 3 года назад
Great Tutorial. Easy to understand. I didn't play snake since 1999 on my NOKIA phone :)
@mahisai4186
@mahisai4186 3 года назад
help me bro, it says the selection cannot be launched and there are no recent launches.. I want a sol..
@thekontuli2828
@thekontuli2828 2 года назад
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.
@andiuptown1711
@andiuptown1711 8 месяцев назад
Update??
@zansa7858
@zansa7858 10 месяцев назад
Bro casually shows us that he is a snake god
@mr.fakeman4718
@mr.fakeman4718 4 года назад
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.
@BroCodez
@BroCodez 4 года назад
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.fakeman4718
@mr.fakeman4718 4 года назад
@@BroCodez Yeah.:/ I did it with .wav instead of .mp3. Now I will know this too. Thank you for your response.:D
@julesssssssss
@julesssssssss 2 года назад
good job bro! as a programmer in other languages, this helped me learn the basic syntax of java.
@SumbaSlice
@SumbaSlice 3 года назад
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!
@mahisai4186
@mahisai4186 3 года назад
help me bro, it says the selection cannot be launched and there are no recent launches.. I want a sol..
@RaahimFahd
@RaahimFahd 4 месяца назад
Everything was so easy to understand and remake except that high score at the end!
@pranavigoud1667
@pranavigoud1667 9 месяцев назад
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
@Phougat
@Phougat 9 месяцев назад
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?
@93f9d
@93f9d 2 года назад
I have been learnt html css javascript and java by watching your video. i have much respect for you. thank you very much!!
@nestam6844
@nestam6844 3 года назад
This is a full tutorial to my school exercise lol. But I already finished it unfortunately
@creepercheater0148
@creepercheater0148 3 года назад
I wish I would be allowed to use java in school. We have to use pascal (shit lang)...
@gigo3795
@gigo3795 3 года назад
@@creepercheater0148 me too (pascal is the biggest shit ever)
@creepercheater0148
@creepercheater0148 3 года назад
@@gigo3795 ohh yess
@snakepink8153
@snakepink8153 2 года назад
yeah,the color change is pretty cool,makes the game to the next level,you are a natural.
@Zechey
@Zechey 3 года назад
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
@mr.claroOF
@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?
@justtheone8544
@justtheone8544 2 года назад
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?
@정수영-q4w
@정수영-q4w 2 года назад
Im trying to learn JAVA and this video makes me easy to learn. thank you so much. i wanna do more function in this project that i wanna add button like restarting button when game is over can u teach me how can i do?
@dahoyasmine2248
@dahoyasmine2248 2 года назад
I could never thank you enough! I learned a lot! Thank you so much.
@safaidansari9623
@safaidansari9623 2 года назад
MY CODE IS NOT RUNNING PROPERLY THROW THE EXCEPTION INDEX OUT OF BOUNDS PLEASE HELP
@abhishek-gu6qt
@abhishek-gu6qt Год назад
amazing code with simplified understanding thanks buddy
@HaziqSeru
@HaziqSeru Год назад
can i run this code in visual studio code
@architech5940
@architech5940 4 месяца назад
Try it and see
@ghost-qp6yh
@ghost-qp6yh 4 месяца назад
yes
@joshuabarber684
@joshuabarber684 2 года назад
Tip: if your keyboard doesn't have arrow keys like mine, instead of using KeyEvent.VK_LEFT, RIGHT, etc, you can use KeyEvent.VK_A, where VK_A = A key, VK_B = B key, etc. I used the WASD keys.
@randysierra5869
@randysierra5869 2 года назад
I DONT KNOW WHAT TO DO, I DID SOMETHING WRONG BUT IS NOT LISTENING TO THE KEYWORD, AND THE SNAKE IS NOT MOVING IN DIRECTIONS. DO YOU KNOW HOW TO SOLVE?
@ishatomar5418
@ishatomar5418 Год назад
@@randysierra5869 same issue with me , if you had solved the problem then plzz help me out too..
@piyushsinghal9518
@piyushsinghal9518 3 года назад
This seriously reminds me of the meme "Do you ever look at someone and wonder... What is going ON inside their head??"
@jasonclair5046
@jasonclair5046 2 года назад
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?
@harsha4048
@harsha4048 3 года назад
Big Fan of you bro. Make these games more. A new subscriber ❤️ is here.
@subhendumandal7218
@subhendumandal7218 3 года назад
This was extremely helpful and the first tutorial that actually helped me. Thank you so much
@BroCodez
@BroCodez 3 года назад
thanks for watching Subhendu!
@shahtanmay902
@shahtanmay902 2 года назад
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.
@hashim399
@hashim399 2 года назад
Hey do you know how to restart the game by pressing a key...
@leaf56448
@leaf56448 3 года назад
What eclipse theme are you using? Btw really nice explanation 🔥👍
@fatimaadreeta
@fatimaadreeta 2 года назад
That was super fun to watch! GUI is an absolute nightmare to me but definitely will try this.
@mennaeldamaty5269
@mennaeldamaty5269 3 года назад
Your tutorials are amazing, but I’m having an issue, when I run the program nothing appears, how can I solve this?
@techdoge3625
@techdoge3625 3 года назад
most likely you are forgetting to run the draw(); method in the paintComponent(Graphics g) method
@med_reda_hak
@med_reda_hak 2 года назад
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)
@husein_alfil
@husein_alfil 3 года назад
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 ?
@oliver123
@oliver123 3 года назад
Im having the same problem
@stenationtv
@stenationtv 10 месяцев назад
How to implement a restart game method?
@ramazandurmaz3012
@ramazandurmaz3012 3 года назад
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!
@lucaswentzloff1899
@lucaswentzloff1899 2 года назад
you got that code yet?
@alexb2773
@alexb2773 3 года назад
nice, found my weekend project
@BlackMark3tBaby
@BlackMark3tBaby 4 месяца назад
Beautifully concise and easy to follow. Thanks for this! SUBBED!!
@kemann3815
@kemann3815 2 года назад
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
@shrabantiroy6711
@shrabantiroy6711 2 года назад
A good channel with good English and gives source code in the comments. Am I dreaming?!?!
@chemistry9130
@chemistry9130 Год назад
Good to know java still exists
@MisterWealth
@MisterWealth 3 года назад
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.
@osmansiddiqi4057
@osmansiddiqi4057 3 года назад
Lol
@kathrin3908
@kathrin3908 3 года назад
same hahaha
@jawnaw2000
@jawnaw2000 Год назад
Thanks. I coded along as a new learner. Your explanations were top notch!
@tamasataniska3059
@tamasataniska3059 2 года назад
Above everything else, the last game play was so satisfying !
@joa9899
@joa9899 Год назад
thank you! so brief and interesting!
@ChaperoneDad
@ChaperoneDad 3 года назад
Great to get on board when I am a student and this has definitely helped me out with the methods and supers. Thanks Bro!
@ziskador
@ziskador 3 года назад
I like that this isn't one of those videos where they explain what a variable is every time
@justprem4215
@justprem4215 2 года назад
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?
@fabianzbranski2061
@fabianzbranski2061 2 года назад
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)
@spilza3310
@spilza3310 2 года назад
@@fabianzbranski2061 that is true but i'm getting an error when I type .start() and Timer(DELAY,this); i have not syntax erros tho
@developerjunior446
@developerjunior446 3 года назад
Bro Really Fantastic. I don't believe do it myself !!! Thank you so much. Hope Android course
@fiona7651
@fiona7651 2 года назад
this is bringing me back to why i wanted to learn computer science
@ScienceDayYT
@ScienceDayYT 3 года назад
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;
@osamaahmedbhatti1446
@osamaahmedbhatti1446 3 года назад
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
@MrPaulOMalley
@MrPaulOMalley 2 года назад
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?
@MrPaulOMalley
@MrPaulOMalley 2 года назад
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.
@elidegen2000
@elidegen2000 2 года назад
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
@MrPaulOMalley
@MrPaulOMalley 2 года назад
@@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?
@elidegen2000
@elidegen2000 2 года назад
@@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
@oleknapiorkowski8980 Год назад
@@MrPaulOMalley its not working bro :( Do you have working solution?
@prajnap9394
@prajnap9394 2 года назад
This is really a good game... where I learned lot of graphics... Thank you buddy......
@festivityreal
@festivityreal 2 года назад
Bro Code is the type of dude who develops a game just to play
@synfpv007
@synfpv007 2 года назад
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.8886
@e.8886 2 года назад
Hi! May I ask how you did that? What does your code for that look like?
@AmanNgmOP
@AmanNgmOP Год назад
I found the best Coding teacher, I'm sure that I will master java soon
@xx-qf8pi
@xx-qf8pi 3 года назад
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.
@dean98052
@dean98052 3 года назад
@@ShanleH easy, use an array for the hi score list
@amc1140
@amc1140 2 года назад
Why do we need the move() in ActionPerformed (instead of within another method) when we already have the timer and loops to make it iterative?? I know it's critical but there was no explanation
@dollygamble7207
@dollygamble7207 Год назад
What a GIGA CHAD, it's easy to understand!
@Rasmus-tz3zp
@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
@misszombiesue
@misszombiesue Год назад
damn bro code is really good at snake
@g_bluana6965
@g_bluana6965 28 дней назад
I learnt so much from this. Thanks so much!!
@zbigniewsak7045
@zbigniewsak7045 3 года назад
An excellent example for game's developers. And I really like it.
@geo_pop2331
@geo_pop2331 Год назад
Bro code is truly my savior
@konstantinklein7050
@konstantinklein7050 2 месяца назад
like, comment, subscribed, now im ready to watch this guide
@Heisenberg28954
@Heisenberg28954 2 года назад
That's why programming is Fun
Далее
Java pong game 🏓
1:07:44
Просмотров 293 тыс.
Exploring Word Chains
9:45
Просмотров 203 тыс.
Как он понял?
00:13
Просмотров 108 тыс.
Making a Game with Java with No Experience
8:41
Просмотров 367 тыс.
Coding Adventure: Simulating Fluids
47:52
Просмотров 1,8 млн
Multithreading in Java Explained in 10 Minutes
10:01
Просмотров 926 тыс.
before you code, learn how computers work
7:05
Просмотров 367 тыс.
Java login system 👨‍💻
30:36
Просмотров 313 тыс.
The Unity Tutorial For Complete Beginners
46:39
Просмотров 3,6 млн
Code Flappy Bird in Java
54:02
Просмотров 100 тыс.