Java snake game 🐍

แชร์
ฝัง
  • เผยแพร่เมื่อ 27 พ.ย. 2024

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

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

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

      I- THANK YOU!!!

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

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

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

      Is this code is correct

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

      @@divakarkumarjha1171 put the keylistener in under GameFrame class

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

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

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

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

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

      @@covid-21delta99 ☹

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

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

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

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

      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.

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

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

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

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

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

      Indeed

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

      thanks man took awhile to make

  • @janmail8018
    @janmail8018 4 ปีที่แล้ว +425

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

      Thanks man took awhile to make

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

      bruh you even added ; at the end

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

      @@aspidinton lol

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

      @@itachu. Truly a programmer moment

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

      @@aspidinton truly a ";" moment

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

    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!

  • @allamtajusarof5649
    @allamtajusarof5649 4 ปีที่แล้ว +10

    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?

  • @belalehner3937
    @belalehner3937 ปีที่แล้ว +46

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

      ı think it could be like this for x SCREEN_WIDTH/UNIT_SIZE = 600/25 =24 for y screenHeight/ unitSize =600/25 =24

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

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

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

      @@moshezechariah3705 i think if snakehead doesnot move body doesnot move either

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

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

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

    Underated is the only word that describes you bro. Thanks

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

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

      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?

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

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

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

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

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

    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.

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

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

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

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

      ​@@Cyber_Boy101 i did write (running = false) and not (!running)

  • @davyswanson7412
    @davyswanson7412 4 ปีที่แล้ว +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.

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

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

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

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

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

      same bro, you keep it up too and good luck

    • @zOmaRz1
      @zOmaRz1 6 วันที่ผ่านมา

      Im also preparing for uni next year can you tell me if these videos actually help or if you have some tips,advice or videos you can share i would appreciate it so much and good luck throughout your journey bro

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

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

  • @premkarki2
    @premkarki2 8 หลายเดือนก่อน +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.❤

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

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

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

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

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

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

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

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

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

      thanks for watching!

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

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

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

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

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

    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

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

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

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

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

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

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

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

  • @njcreationskrgproduction8219
    @njcreationskrgproduction8219 4 ปีที่แล้ว +17

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

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

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

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

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

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

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

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

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

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

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

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

    This is the best channel of java on TH-cam

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

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

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

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

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

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

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

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

      thanks for watching Subhendu!

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

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

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

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

    I like that this isn't one of those videos where they explain what a variable is every time

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

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

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

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

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

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

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

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

    Excellent dude. Expecting more java projects for beginners. keep rocking.

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

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

    very clear and simple to understand. I had no experince and I could add something to the code! Really good video, I suggest it.

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

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

    Hey cool tutorial for java beginners

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

    nice, found my weekend project

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

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

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

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

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

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

    amazing code with simplified understanding thanks buddy

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

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

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

    Big Fan of you bro. Make these games more. A new subscriber ❤️ is here.

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

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

    Sir! I am from Pakistan. Amazing Explanation of Snake Game working. Keep it up, sir! Please make some more projects using Graphics in Java or can you please make tutorials on how to use Graphics class in java. I shall be thankful to you. Love from Pakistan. ♥♥♥

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

      Im having the same problem

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

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

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

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

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

    I found the best Coding teacher, I'm sure that I will master java soon

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

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

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

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

    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?

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

      i dont know this - but my guess is that it is part of the import settings (at the very top you have the imports =)

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

      By default the initial value is zero

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

    Bro casually shows us that he is a snake god

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

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

    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!

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

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

    Woooow .. so well organised!!

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

    can i run this code in visual studio code

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

      Try it and see

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

      yes

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

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

      @@fabianzbranski2061 that is true but i'm getting an error when I type .start() and Timer(DELAY,this); i have not syntax erros tho

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

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

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

  • @polorio2083
    @polorio2083 21 วันที่ผ่านมา

    wow... I learn more here....!

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

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

    WoW ! Thanks for such a great tutorial.

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

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

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

    You are really good making videos .
    Well done!!

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

    This seriously reminds me of the meme "Do you ever look at someone and wonder... What is going ON inside their head??"

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

    Really easy to understand. It was a really good video.

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

    A good channel with good English and gives source code in the comments. Am I dreaming?!?!

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

    You are the best Sir. Keep it up

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

    Very complicated but very good👍👍

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

    Good to know java still exists

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

    thanks for this tutorial, I hope you can make more of these kind of videos in the future!

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

    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?