Java snake game 🐍

แชร์
ฝัง
  • เผยแพร่เมื่อ 19 ก.ค. 2020
  • 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.
  • วิทยาศาสตร์และเทคโนโลยี

ความคิดเห็น • 1.6K

  • @BroCodez
    @BroCodez  4 ปีที่แล้ว +997

    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 ปีที่แล้ว +2

      I- THANK YOU!!!

    • @yashkadulkar6036
      @yashkadulkar6036 3 ปีที่แล้ว +2

      why are my listeners no working man! really need help here

    • @divakarkumarjha1171
      @divakarkumarjha1171 3 ปีที่แล้ว +2

      Is this code is correct

    • @yashkadulkar6036
      @yashkadulkar6036 3 ปีที่แล้ว +1

      @@divakarkumarjha1171 put the keylistener in under GameFrame class

    • @lil_jeke
      @lil_jeke 3 ปีที่แล้ว +1

      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 ปีที่แล้ว +1118

    A fun channel with good English? Am I dead? Is this heaven?

    • @covid-21delta99
      @covid-21delta99 3 ปีที่แล้ว +36

      See Brackeys, he is the King Of Code, but now he retired :(

    • @covid-21delta99
      @covid-21delta99 3 ปีที่แล้ว +8

      @Dev Milan Chakraborty :( yes, really, really sad

    • @shivangmishra2642
      @shivangmishra2642 3 ปีที่แล้ว +6

      Watch the coding train... He's great too.

    • @farnoodgh9626
      @farnoodgh9626 2 ปีที่แล้ว

      @@covid-21delta99 ☹

    • @lener6345
      @lener6345 2 ปีที่แล้ว

      @@NHbinaaa111 yep, He just posted yesterday(ノ◕ヮ◕)ノ*.✧

  • @maxxpellowski2916
    @maxxpellowski2916 2 ปีที่แล้ว +190

    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 ปีที่แล้ว +5

      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.

    • @mio9525
      @mio9525 3 หลายเดือนก่อน

      Typical CS student lol
      I don't see why you guys hate desinging and planning a system before rushing to code
      Most of you hate testing too

  • @americaneagle2073
    @americaneagle2073 10 หลายเดือนก่อน +2

    3 years ago and still helping !! Thank you for giving up your time to help others learn for free!!

  • @lorenzangeles9626
    @lorenzangeles9626 3 ปีที่แล้ว +48

    such an underrated channel. We need more people like you

  • @mechasmoke
    @mechasmoke 2 ปีที่แล้ว +39

    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!

  • @colekrause5882
    @colekrause5882 3 ปีที่แล้ว +24

    This may be one of the most underrated coding tutorial/learning youtube channels with out a doubt

    • @-_--le3zk
      @-_--le3zk 2 ปีที่แล้ว

      Indeed

    • @jacobwall8066
      @jacobwall8066 2 ปีที่แล้ว

      thanks man took awhile to make

  • @saleharja9538
    @saleharja9538 3 ปีที่แล้ว +5

    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!

  • @janmail8018
    @janmail8018 3 ปีที่แล้ว +423

    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 ปีที่แล้ว +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. 5 หลายเดือนก่อน

      @@aspidinton lol

    • @aspidinton
      @aspidinton 5 หลายเดือนก่อน +1

      @@itachu. Truly a programmer moment

  • @belalehner3937
    @belalehner3937 11 หลายเดือนก่อน +37

    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.*

  • @justinbanza4751
    @justinbanza4751 2 ปีที่แล้ว +8

    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.

  • @TechSupportDave
    @TechSupportDave 2 ปีที่แล้ว +12

    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 2 ปีที่แล้ว

      help me bro, it says the selection cannot be launched and there are no recent launches.. I want a sol..

  • @theofficialyapsesh
    @theofficialyapsesh 3 ปีที่แล้ว +11

    Underated is the only word that describes you bro. Thanks

  • @cooler09b
    @cooler09b 3 ปีที่แล้ว +3

    Thank you very much for your help, this is my first massive JAVA project. You are a great teacher, good luck!

  • @yokisaku
    @yokisaku ปีที่แล้ว +1

    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!

  • @iyasugames
    @iyasugames 2 ปีที่แล้ว +3

    Very beginner friendly and straight forward. Thanks for posting!

  • @davyswanson7412
    @davyswanson7412 3 ปีที่แล้ว +9

    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.

  • @MananGandhi
    @MananGandhi 3 ปีที่แล้ว +5

    bro, your channel is truly underrated. u deserve more than at least 10,000,000 subs

  • @jisterl7485
    @jisterl7485 ปีที่แล้ว +1

    You create some of the best java tutorials I've ever come across thank you so much :)

  • @21kHzBANK21kHZ
    @21kHzBANK21kHZ ปีที่แล้ว +8

    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.

  • @famelitegamer3317
    @famelitegamer3317 3 ปีที่แล้ว +13

    I recently started watching your gui tutorial, and have learned so much about java thank you so much

  • @alexandrulolea4631
    @alexandrulolea4631 ปีที่แล้ว +5

    I'm preparing for uni mate, so these "learn through projects" videos are helping a lot. Keep it up and thank you!

    • @frcjiang7654
      @frcjiang7654 11 หลายเดือนก่อน

      same bro, you keep it up too and good luck

  • @johnnymooney7652
    @johnnymooney7652 ปีที่แล้ว

    Had a lot of fun building this! Thanks for the video!

  • @Phougat
    @Phougat 7 หลายเดือนก่อน +1

    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.

  • @bruce9067
    @bruce9067 3 ปีที่แล้ว +36

    This is so amazing!!!! Thankyou!!!!!!

    • @BroCodez
      @BroCodez  3 ปีที่แล้ว +7

      thanks for watching!

  • @allamtajusarof5649
    @allamtajusarof5649 3 ปีที่แล้ว +9

    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?

  • @Antarikkolay
    @Antarikkolay 3 ปีที่แล้ว

    Excellent tutorial of a simple snake game project with proper explanation. Thank you.

  • @Szymon1862
    @Szymon1862 2 ปีที่แล้ว

    Thanks for this game... Your code is clean and tidy. Easy to read. Now I feel I understand swing much better. Thanks!!!

  • @wasifali6169
    @wasifali6169 3 ปีที่แล้ว +10

    Man, you are good at explaining. Please continue to build more game projects.

  • @ewoutlagendijk7385
    @ewoutlagendijk7385 3 ปีที่แล้ว +7

    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 2 ปีที่แล้ว +4

      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 9 หลายเดือนก่อน

      @@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.

  • @hieunguyenvan6356
    @hieunguyenvan6356 2 ปีที่แล้ว

    This is a wonderful lesson because your guide absolutely understands. Thank you so much for your lesson.

  • @julesssssssss
    @julesssssssss 2 ปีที่แล้ว +2

    good job bro! as a programmer in other languages, this helped me learn the basic syntax of java.

  • @dahoyasmine2248
    @dahoyasmine2248 2 ปีที่แล้ว +5

    I could never thank you enough! I learned a lot! Thank you so much.

    • @safaidansari9623
      @safaidansari9623 2 ปีที่แล้ว +1

      MY CODE IS NOT RUNNING PROPERLY THROW THE EXCEPTION INDEX OUT OF BOUNDS PLEASE HELP

  • @Zechey
    @Zechey 3 ปีที่แล้ว +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

  • @jawnaw2000
    @jawnaw2000 ปีที่แล้ว +1

    Thanks. I coded along as a new learner. Your explanations were top notch!

  • @gabrielcapone4332
    @gabrielcapone4332 2 ปีที่แล้ว

    This is great...all your videos are great...you rock dude!

  • @SumbaSlice
    @SumbaSlice 2 ปีที่แล้ว +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 2 ปีที่แล้ว

      help me bro, it says the selection cannot be launched and there are no recent launches.. I want a sol..

  • @carrotlemon2665
    @carrotlemon2665 2 ปีที่แล้ว +14

    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!

  • @saimhafeez4240
    @saimhafeez4240 3 ปีที่แล้ว

    Awesome...Thanks for the Tutorial.. Keep it up Bro Code !!!

  • @leofreiitas
    @leofreiitas 2 ปีที่แล้ว

    This tutorial was awesome, so much fun, thanks for teaching this.

  • @thekontuli2828
    @thekontuli2828 2 ปีที่แล้ว +9

    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.

  • @alexb2773
    @alexb2773 3 ปีที่แล้ว +3

    nice, found my weekend project

  • @premkarki2
    @premkarki2 3 หลายเดือนก่อน +1

    Thank you 🙏 Bro code. My instructor cited your video sometimes and I learned a lot from your video. It’s cool. Appreciate your work.❤

  • @robertkeiko
    @robertkeiko 9 หลายเดือนก่อน +1

    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.

  • @sergeyb6071
    @sergeyb6071 4 ปีที่แล้ว +18

    This is going to be #1 Java channel on TH-cam

  • @keanjaycox7959
    @keanjaycox7959 3 ปีที่แล้ว +52

    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 ปีที่แล้ว

      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

    • @RadikatMLG
      @RadikatMLG 3 หลายเดือนก่อน

      Or you can just add = after > like this
      if(x[0] >= SCREEN_WIDTH) {
      running = false;
      }
      if(y[0] >= SCREEN_HEIGHT) {
      running = false;
      }
      this is simpler

  • @sadasd7518
    @sadasd7518 3 ปีที่แล้ว +1

    Thanks Bro for all tutorials, live long and prosper !!

  • @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

  • @favillc583
    @favillc583 3 ปีที่แล้ว +4

    Your voice totally remember me of Professor Akali's voice. Thanks for the tutorials :D

    • @satsuki-rin
      @satsuki-rin 3 ปีที่แล้ว +2

      what a strange thing to think about here

  • @jasonclair5046
    @jasonclair5046 2 ปีที่แล้ว +3

    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?

  • @snakepink8153
    @snakepink8153 ปีที่แล้ว

    yeah,the color change is pretty cool,makes the game to the next level,you are a natural.

  • @robertoa.tarazona2708
    @robertoa.tarazona2708 3 ปีที่แล้ว

    Thank you so much! I learned a lot from watching and pausing every second! Happy New Year's!

  • @davidjuhasz5179
    @davidjuhasz5179 3 ปีที่แล้ว +6

    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 ปีที่แล้ว +1

      same profile picture lol

  • @justtheone8544
    @justtheone8544 2 ปีที่แล้ว +4

    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?

  • @julchni3189
    @julchni3189 2 ปีที่แล้ว +1

    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 TH-cam videos than from school lol

    • @yeartwothousandfive
      @yeartwothousandfive ปีที่แล้ว

      School only teach us the basics things in coding..

  • @TheSoprah
    @TheSoprah 3 ปีที่แล้ว

    I came for the game, I stayed for the amazing guitar song at the end. Wow, amazing song. I will watch the tutorial later! :)

  • @leaf56448
    @leaf56448 3 ปีที่แล้ว +4

    What eclipse theme are you using? Btw really nice explanation 🔥👍

  • @subhendumandal7218
    @subhendumandal7218 3 ปีที่แล้ว +6

    This was extremely helpful and the first tutorial that actually helped me. Thank you so much

    • @BroCodez
      @BroCodez  3 ปีที่แล้ว

      thanks for watching Subhendu!

  • @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!!

  • @niclorenzo2603
    @niclorenzo2603 3 ปีที่แล้ว +1

    This is awesome bro.
    Thank you so much.
    I love Java programming.

  • @henryle3925
    @henryle3925 3 ปีที่แล้ว +6

    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

  • @njcreationskrgproduction8219
    @njcreationskrgproduction8219 3 ปีที่แล้ว +16

    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 ปีที่แล้ว +25

      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 ปีที่แล้ว +1

      @@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.

  • @amanagarwal8887
    @amanagarwal8887 2 ปีที่แล้ว +1

    WoW ! Thanks for such a great tutorial.

  • @fixiple2722
    @fixiple2722 3 หลายเดือนก่อน

    Thank you, I followed your tutorial. Everything went perfectly fine

  • @diegoaristizabalElDiego22
    @diegoaristizabalElDiego22 3 ปีที่แล้ว +4

    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

  • @kemann3815
    @kemann3815 2 ปีที่แล้ว +15

    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

  • @vank91
    @vank91 3 ปีที่แล้ว

    Hey cool tutorial for java beginners

  • @prajnap9394
    @prajnap9394 ปีที่แล้ว

    This is really a good game... where I learned lot of graphics...
    Thank you buddy......

  • @pranavigoud1667
    @pranavigoud1667 7 หลายเดือนก่อน +7

    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 6 หลายเดือนก่อน

      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?

  • @aaronfeys9570
    @aaronfeys9570 3 ปีที่แล้ว +10

    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
      @giovannimarcon7980 ปีที่แล้ว

      thank you, I also had this problem. This fixed it.

    • @Toeterrr
      @Toeterrr 10 หลายเดือนก่อน

      Game is so much more responsive with this propert. Thanks!

  • @abhishek-gu6qt
    @abhishek-gu6qt ปีที่แล้ว +1

    amazing code with simplified understanding thanks buddy

  • @blackepreto
    @blackepreto 3 ปีที่แล้ว

    amazing content man, just found ur channel and im amazed! keep with the good work!

  • @nestam6844
    @nestam6844 3 ปีที่แล้ว +16

    This is a full tutorial to my school exercise lol. But I already finished it unfortunately

    • @creepercheater0148
      @creepercheater0148 3 ปีที่แล้ว +2

      I wish I would be allowed to use java in school. We have to use pascal (shit lang)...

    • @gigo3795
      @gigo3795 3 ปีที่แล้ว +2

      @@creepercheater0148 me too (pascal is the biggest shit ever)

    • @creepercheater0148
      @creepercheater0148 3 ปีที่แล้ว +1

      @@gigo3795 ohh yess

  • @foysalkhan2879
    @foysalkhan2879 วันที่ผ่านมา

    I have completed this project. It was amazing. Give us more project like this.

  • @fatimaadreeta
    @fatimaadreeta 2 ปีที่แล้ว +1

    That was super fun to watch! GUI is an absolute nightmare to me but definitely will try this.

  • @juanpablocuellar8506
    @juanpablocuellar8506 2 ปีที่แล้ว +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 2 ปีที่แล้ว +1

      help me bro, it says the selection cannot be launched and there are no recent launches.. I want a sol..

    • @the_iq_sniper9761
      @the_iq_sniper9761 ปีที่แล้ว

      @@mahisai4186I have the same thing happening idk what to do

    • @roddy2015
      @roddy2015 2 หลายเดือนก่อน +1

      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;
      }

  • @mr.fakeman4718
    @mr.fakeman4718 4 ปีที่แล้ว +6

    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 ปีที่แล้ว +3

      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 ปีที่แล้ว +2

      @@BroCodez Yeah.:/ I did it with .wav instead of .mp3.
      Now I will know this too.
      Thank you for your response.:D

  • @marcosalbuquerque2971
    @marcosalbuquerque2971 2 ปีที่แล้ว

    It's a great channel! I learn a lot with you. Thank you so much.

  • @ezequielsanchez3638
    @ezequielsanchez3638 2 ปีที่แล้ว

    Great practice and great video, congratulations Bro Code!!!

  • @faizurrahmankhan8717
    @faizurrahmankhan8717 3 ปีที่แล้ว +3

    This is amazing. Thank you for showing simple straight code.
    I have implemented this and its working good.
    Also i have have added steps to restart the game by pressing the ENTER button once the game is over.
    Keep posting lot of java videos.

    • @BroCodez
      @BroCodez  3 ปีที่แล้ว +2

      awesome! A restart button would be a good addition

    • @nivikr
      @nivikr 3 ปีที่แล้ว

      hey brother, can you help me with the code to restart? im trying to do the same, kind of stuck in THAT particular program

    • @ScienceDayYT
      @ScienceDayYT 3 ปีที่แล้ว +2

      @@nivikr case KeyEvent.VK_ENTER:
      if(!running){
      new GameFrame();

    • @aryanjuyal6169
      @aryanjuyal6169 2 ปีที่แล้ว

      @@ScienceDayYT where exactly does this fit in the code of the program

    • @constantinemacris9047
      @constantinemacris9047 2 ปีที่แล้ว +1

      @@aryanjuyal6169 i appended it to the switch statement that takes input from the D-pad. and it works.

  • @ChaperoneDad
    @ChaperoneDad 2 ปีที่แล้ว +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!

  • @karlie7
    @karlie7 ปีที่แล้ว

    Thanks so much for making this video! I find it so fun to learn Java this way :)

  • @BlackMark3tBaby
    @BlackMark3tBaby หลายเดือนก่อน

    Beautifully concise and easy to follow. Thanks for this! SUBBED!!

  • @divyanshibhardwaj4544
    @divyanshibhardwaj4544 2 ปีที่แล้ว +3

    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?

  • @mennaeldamaty5269
    @mennaeldamaty5269 3 ปีที่แล้ว +5

    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 ปีที่แล้ว +5

      most likely you are forgetting to run the draw(); method in the paintComponent(Graphics g) method

  • @zbigniewsak7045
    @zbigniewsak7045 2 ปีที่แล้ว

    An excellent example for game's developers. And I really like it.

  • @rajankumar_37
    @rajankumar_37 2 ปีที่แล้ว

    what a great explaination i will do it by self thank you

  • @husein_alfil
    @husein_alfil 3 ปีที่แล้ว +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 2 ปีที่แล้ว +1

      Im having the same problem

  • @HaziqSeru
    @HaziqSeru 11 หลายเดือนก่อน +7

    can i run this code in visual studio code

    • @architech5940
      @architech5940 2 หลายเดือนก่อน +2

      Try it and see

    • @ghost-qp6yh
      @ghost-qp6yh หลายเดือนก่อน

      yes

  • @drewbhardwaj
    @drewbhardwaj 3 ปีที่แล้ว

    very helpful for beginners.
    THANKS BRO🙏🧡

  • @giuseppe7695
    @giuseppe7695 2 ปีที่แล้ว

    I learned a lot of new things with this video. Thanks

  • @kiernanparkman
    @kiernanparkman 3 ปีที่แล้ว +3

    Nice video, however, I can’t seem to get the draw method to work at all (I have been trying to do some research on it, and it may have something to do with performing this on a Mac). I can only get the frame to appear (changing background color works but nothing related to graphics does). Any ideas of how this can be resolved by any chance?

    • @kiernanparkman
      @kiernanparkman 3 ปีที่แล้ว

      To add, I wanted to see if the code was working so I added a print statement after finishing the key presses for moving the snake. I am able to tell that the program detects the objects made on screen since I added a “not playing” string once it detects it is not running from a collision. However, it looks like it just will not draw my graphics at all. Any suggestion/input would be greatly appreciated.

    • @BroCodez
      @BroCodez  3 ปีที่แล้ว

      hmmmm. Would you be able to post your curent code? I'll copy it into a new project and try running it and see what is going on

    • @kiernanparkman
      @kiernanparkman 3 ปีที่แล้ว

      @@BroCodez Yes sir, thanks for being open to assisting! It's super appreciated! Here's the code from the panel class (running on Mac OS in Eclipse):
      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 = 600;
      static final int SCREEN_HEIGHT = 600;
      static final int UNIT_SIZE = 50;
      static final int GAME_UNITS = (SCREEN_WIDTH*SCREEN_HEIGHT)/UNIT_SIZE;
      static final int DELAY = 75;
      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);
      }
      public void draw(Graphics g) {
      for(int i=0; i 0; 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() {
      //Java Snake Game Bro Code 32:50 (TH-cam) stopped
      }
      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();
      System.out.print("Not Playing");
      }
      }
      public void gameOver(Graphics g) {
      }
      @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;
      }
      }
      }
      }

    • @kiernanparkman
      @kiernanparkman 3 ปีที่แล้ว

      Also to re-iterate, the only outcome I receive from the above code along with the two other classes is a black background with my string output after a collision is detected.

    • @kiernanparkman
      @kiernanparkman 3 ปีที่แล้ว

      You're gonna hate me.... lol I found what I did wrong. Thank you in advance though, I guess I missed the "draw(g)" method. Working perfectly now.

  • @justprem4215
    @justprem4215 2 ปีที่แล้ว +4

    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 ปีที่แล้ว +1

      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

  • @avi_2014
    @avi_2014 2 ปีที่แล้ว

    I Love it!!! I am done with my code too. Superb!!!

  • @kasulejuma3314
    @kasulejuma3314 3 ปีที่แล้ว

    Always doubted my java, but this tutorual has inspired me and given me a very strong foundation, nice tutorial bro, thank you
    BIG UP!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  • @MisterWealth
    @MisterWealth 3 ปีที่แล้ว +8

    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.

  • @SalmanYU
    @SalmanYU 3 ปีที่แล้ว +3

    How would I make a button to restart the game?

    • @SalmanYU
      @SalmanYU 3 ปีที่แล้ว +1

      nvm i figured it out

    • @SalmanYU
      @SalmanYU 3 ปีที่แล้ว

      @@aproe610 I just made a JButton with an actionlistener that sets running = true and resets all of the variables back to their original values

    • @SalmanYU
      @SalmanYU 3 ปีที่แล้ว +3

      @@aproe610 import java.awt.*;
      import java.awt.event.*;
      import javax.swing.*;
      import java.util.Random;
      import java.util.Scanner;
      public class GamePanel extends JPanel implements ActionListener{

      static final int SCREEN_WIDTH = 600;
      static final int SCREEN_HEIGHT = 600;
      static final int UNIT_SIZE = 25;
      static final int GAME_UNITS = (SCREEN_WIDTH*SCREEN_HEIGHT)/UNIT_SIZE;
      static int DELAY = 75;
      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;
      boolean text = true;
      JButton easy;
      JButton medium;
      JButton hard;
      JButton insane;



      GamePanel(){
      random = new Random();
      this.setPreferredSize(new Dimension(SCREEN_WIDTH,SCREEN_HEIGHT));
      this.setBackground(Color.BLACK);
      this.setFocusable(true);
      this.addKeyListener(new MyKeyAdapter());
      easy = new JButton("Easy");
      medium = new JButton("Medium");
      hard = new JButton("Hard");
      insane = new JButton("Insane");
      this.add(easy);
      this.add(medium);
      this.add(hard);
      this.add(insane);
      easy.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
      DELAY = 100;
      text = false;
      running = true;
      startGame();
      easy.hide();
      medium.hide();
      hard.hide();
      insane.hide();
      }
      });
      medium.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
      DELAY = 75;
      text = false;
      running = true;
      startGame();
      easy.hide();
      medium.hide();
      hard.hide();
      insane.hide();

      }
      });
      hard.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
      DELAY = 50;
      text = false;
      running = true;
      startGame();
      easy.hide();
      medium.hide();
      hard.hide();
      insane.hide();

      }
      });

      insane.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
      DELAY = 25;
      text = false;
      running = true;
      startGame();
      easy.hide();
      medium.hide();
      hard.hide();
      insane.hide();

      }
      });

      }
      public void startGame() {
      newApple();
      running = true;
      timer = new Timer(DELAY,this);
      timer.start();
      direction = 'R';
      bodyParts = 6;
      repaint();

      }
      public void paintComponent(Graphics g) {
      super.paintComponent(g);
      draw(g);
      }
      public void draw(Graphics g) {

      if(running) {
      for(int i = 0; i0;i--) {
      if((x[0])==x[i]&&(y[0]==y[i])) {
      running = false;
      }
      //checks if head touches left border
      if(x[0]< 0) {
      running = false;
      }
      //checks if head touches right border
      if(x[0]> SCREEN_WIDTH) {
      running = false;
      }
      //checks if head touches top border
      if(y[0]< 0) {
      running = false;
      }
      //checks if head touched bottom border
      if(y[0]> SCREEN_HEIGHT) {
      running = false;
      }
      if (!running&&!text) {
      timer.stop();
      }
      }


      }
      public void gameOver(Graphics g) {
      g.setColor(Color.red);
      g.setFont(new Font("Ink Free",Font.BOLD, 40));
      FontMetrics metrics = getFontMetrics(g.getFont());
      g.drawString("Score: "+applesEaten, (SCREEN_WIDTH - metrics.stringWidth("Score: "+applesEaten))/2, g.getFont().getSize()/2 +10);

      g.setColor(Color.red);
      g.setFont(new Font("Ink Free",Font.BOLD, 75));
      FontMetrics metrics1 = getFontMetrics(g.getFont());
      g.drawString("Game Over", (SCREEN_WIDTH - metrics1.stringWidth("Game Over"))/2, SCREEN_HEIGHT/3);
      g.setFont(new Font("Ink Free",Font.BOLD, 45));
      FontMetrics metrics2 = getFontMetrics(g.getFont());
      g.drawString("Press Space to Restart", (SCREEN_WIDTH - metrics2.stringWidth("Press Space to Restart"))/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;
      }
      if(!running&&!text) {
      if(e.getKeyChar()==KeyEvent.VK_SPACE) {
      startGame();
      for(int i=bodyParts;i>0;i--) {
      x[i] = bodyParts*-1;
      y[i] = 0;
      }
      x[0] = 0;
      y[0] = 0;
      repaint();
      applesEaten = 0;

      }

      }

      }
      }
      }

    • @SalmanYU
      @SalmanYU 3 ปีที่แล้ว

      @@aproe610 np

    • @246rs246
      @246rs246 2 ปีที่แล้ว +1

      @@aproe610 Add new case in MyKeyAdapter class like this:
      case KeyEvent.VK_SPCACE:
      if (!runinng){
      new GameFrame();

  • @playtoy_cardi_7201
    @playtoy_cardi_7201 2 ปีที่แล้ว

    The best code "learning" vídeo,THANK YOU!!!

  • @iljavitohins8729
    @iljavitohins8729 3 ปีที่แล้ว

    Great Job! Helped a lot. Definitely worth subscribing and like!

  • @fatimaagouzoul8261
    @fatimaagouzoul8261 2 ปีที่แล้ว

    Woooow .. so well organised!!