Java snake game 🐍 - playproduction.de

Java snake game 🐍

Bro Code
Views: 576154
Like: 15205
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.

500 Comments

  1. i dont know why but this doesnt work for me. I've copied all the code multiple times now but when youre testing the move() method and the snake just moves right, for me the snakes body parts are like 5 "chunks" apart from another. So the snake moves by the screen in line 1 ms and is not connected at all. Can anyone help? I could provide the code if anyone does, maybe I've messed up or smth idk.

  2. Thank you for the tutorial. How can I deploy this game and maybe send it to my friend? Is it possible?

  3. bro you talk too fast for beginners like me

  4. i like the way this guy plays his own game

  5. Aweosome, seriously. I enjoyed using the help of this tutorial to create my first game…But I have a problem, the game only appears on Game over menu…I tried to look what error caused that, and when I changed the "char direction" to D, it appars the snake moving but I cant controll it… Idk what makes it here is the code of the GamePanel, buecuase the other ones are good:

    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; i<SCREEN_HEIGHT/UNIT_SIZE; i++) {

    g.drawLine(i*UNIT_SIZE, 0, i*UNIT_SIZE, SCREEN_HEIGHT);

    g.drawLine(0, i*UNIT_SIZE, SCREEN_WIDTH, i*UNIT_SIZE);

    }

    */

    g.setColor(Color.red);

    g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE);

    for(int i = 0; i < bodyParts; i++) {

    if(i == 0) {

    g.setColor(Color.green);

    g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);

    }

    else {

    g.setColor(new Color(45, 180, 0));

    //g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));

    g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);

    }

    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());

    }

    }

    else {

    gameOver(g);

    }

    }

    public void newApple() {

    appleX =random.nextInt((int)(SCREEN_WIDTH/UNIT_SIZE))*UNIT_SIZE;

    appleY =random.nextInt((int)(SCREEN_WIDTH/UNIT_SIZE))*UNIT_SIZE;

    }

    public void move() {

    for(int i = bodyParts; 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() {

    if((x[0] == appleX) && (y[0] == appleY)) {

    bodyParts++;

    applesEaten++;

    newApple();

    }

    }

    public void checkCollisions() {

    //Cuando la cabeza se choca con el cuerpo

    for(int i = bodyParts; i>0; i–) {

    if(x[0] == x[i] && (y[0] == y[i])) {

    running = false;

    }

    }

    //Cuando la cabeza toca los bordes DERECHA

    if(x[0] < 0) {

    running = false;

    }

    //Cuando la cabeza toca los bordes IZQUIERDA

    if(x[0] > SCREEN_WIDTH) {

    running = false;

    }

    //Cuando la cabeza toca los bordes ARRIBA

    if(y[0] < 0) {

    running = false;

    }

    //Cuando la cabeza toca los bordes ABAJO

    if(y[0] > SCREEN_WIDTH) {

    running = false;

    }

    if(!running) {

    timer.stop();

    }

    }

    public void gameOver(Graphics g) {

    //Puntuacion

    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 texto

    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;

    }

    }

    }

    }

  6. Is there anyway to make the snake continuous from one side to the other? I keep trying to mess with it, but the game just breaks instead of letting the snake loop around 🙁

  7. Good job, learned a lot, but the apple could appear on the snake, i think it's better if the apple could appear in a position not included in position of snake

  8. What's the name of the background music of the video. (In the end of the video, outro).

  9. How do you make it so that it restarts after?

  10. Hey Bro Code. I know you probably won't see this but I have reached the about using the for loop to draw gridlines, and I keep running into the same problem. I just get a black screen. Even all the way up to the snake color itself I get nothing but a black screen when I run the program. Do you know why this would happen?

  11. idk if you're still responding to questions, and this might be the dumbest question ever, but how do you make the thing that allows you to run the game pop up? cause it keeps wanting to pop up in the Console part and it's not appearing when I try to run it.

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

  13. gread vid but im curious what happens when snake eats itself

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

  15. I am using Intellij IDEA but the Intellij not showing me the ready program
    What should I do?

  16. Caramba ficou show de bola, estou começando agora na programação, curso na Udemy. Um dia serei facha preta em Java.

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

  18. I'm not sure if this is the case, but isn't there a possibility that the apple can spawn on the snake. It will be weirder during the end game where the apple keeps on spawning on the snakes body. I've fixed it but I though it was worth mentioning

  19. Why i can't succeed to move the snake with the arrow button?

  20. Very beginner friendly and straight forward. Thanks for posting!

  21. Please help I want to create 16 soldier game in java please help I will give you double like

  22. Thank you so much, you really helped me learn java better🙏🙏🙏

  23. Hey Bro,please make a video about pacman game in java

  24. 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;i<SCREEN_HEIGHT/UNIT_SIZE;i++) {

    g.drawLine(i*UNIT_SIZE, 0, i*UNIT_SIZE, SCREEN_HEIGHT);

    g.drawLine(0, i*UNIT_SIZE, SCREEN_WIDTH, i*UNIT_SIZE);

    }

    */

    g.setColor(Color.red);

    g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE);

    for(int i = 0; i< bodyParts;i++) {

    if(i == 0) {

    g.setColor(Color.green);

    g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);

    }

    else {

    g.setColor(new Color(45,180,0));

    //g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));

    g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);

    }

    }

    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());

    }

    else {

    gameOver(g);

    }

    }

    public void newApple(){

    appleX = random.nextInt((int)(SCREEN_WIDTH/UNIT_SIZE))*UNIT_SIZE;

    appleY = random.nextInt((int)(SCREEN_HEIGHT/UNIT_SIZE))*UNIT_SIZE;

    }

    public void move(){

    for(int i = bodyParts;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() {

    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;

    }

    }

    }

    }
    //*****************************************

Leave a Reply

Your email address will not be published.