Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Java
  3. Question
Java

What is the java snake game code?

Asked by Makram Ben Oct 11, 2022 2.0K views 4 answers
Share

About this question

 I am a self - taught coder, and have been learning Java / C# for the last 2 1/2 years (inconsistently).

I have recently created a snake game in Java with the help of an online tutorial. I have rearranged the program into separate classes & methods. I am sceptical on how good of a programmer I am, and I code messy.

I don't really want help on how to make the game better in visuals, levels, or anything like that. I am asking those who are more advanced programmers to help me with implementing programming techniques, better organisation, how to comment better, etc. Pretty much anything that will help me become a better programmer.

Also, I have commented a few things out of pure guesswork, so if it appears as if I have gotten something wrong, please correct me!

Also, any extra tips for my future projects would be much appreciated!


Game.Java


import java.awt.EventQueue;
import javax.swing.JFrame;
public class Game extends JFrame {
Game() {
    add(new Board());
    setResizable(false);
    pack();
    setTitle("Snake");
    setLocationRelativeTo(null);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
    // Creates a new thread so our GUI can process itself
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            JFrame frame = new Game();
            frame.setVisible(true);
        }
    });
}
}
Snake.Java
public class Snake {
// Stores the joints / body part locations for our snake
private final int[] x = new int[Board.getAllDots()];
private final int[] y = new int[Board.getAllDots()];
// Stores direction of our snake
private boolean movingLeft = false;
private boolean movingRight = false;
private boolean movingUp = false;
private boolean movingDown = false;
private int joints = 0; // Stores # of dots / joints the snake has (starts
                        // with 3)
public int getSnakeX(int index) {
    return x[index];
}
public int getSnakeY(int index) {
    return y[index];
}
public void setSnakeX(int i) {
    x[0] = i;
}
public void setSnakeY(int i) {
    y[0] = i;
}
public boolean isMovingLeft() {
    return movingLeft;
}
public void setMovingLeft(boolean movingLeft) {
    this.movingLeft = movingLeft;
}
public boolean isMovingRight() {
    return movingRight;
}
public void setMovingRight(boolean movingRight) {
    this.movingRight = movingRight;
}
public boolean isMovingUp() {
    return movingUp;
}
public void setMovingUp(boolean movingUp) {
    this.movingUp = movingUp;
}
public boolean isMovingDown() {
    return movingDown;
}
public void setMovingDown(boolean movingDown) {
    this.movingDown = movingDown;
}
public int getJoints() {
    return joints;
}
public void setJoints(int j) {
    joints = j;
}
public void move() {
    for (int i = joints; i > 0; i--) {
        // Moves the joints of the snake 'up the chain'
        // Meaning, the joint of the snake all move up one
        x[i] = x[(i - 1)];
        y[i] = y[(i - 1)];
    }
    // Moves snake to the left
    if (movingLeft) {
        x[0] -= Board.getDotSize();
    }
    // To the right
    if (movingRight) {
        x[0] += Board.getDotSize();
    }
    // Down
    if (movingDown) {
        y[0] += Board.getDotSize();
    }
    // And finally up
    if (movingUp) {
        y[0] -= Board.getDotSize();
    }
    // Dotsize represents the size of the joint, so a pixel of DOTSIZE
    // gets added on to the snake in that direction
}
 }


Your answer

4 Answers

Klevin Latest answer

Answered on May 29, 2026

Got it! Let’s level up your Snake game by using sound buttons as a practical example to clean up your code.


Clean Structure & Sound ButtonsSeparate UI from Logic: Create a specific SoundButton class. It should only handle drawing the button and detecting clicks.

Use a Manager Class: Create a SoundManager class to handle audio playback. When a user clicks the SoundButton, it tells SoundManager to mute or play the sound.Encapsulate Data: Keep your audio files and button states private. Other classes like Snake should never touch the audio logic directly.

Smart CommentingExplain 'Why', Not 'What': Do not describe the syntax. Explain the business logic instead.

Bad: soundButton.setVisible(true); // Sets visibility to true

Good: soundButton.setVisible(true); // Show the button only when the game is paused

Self-Documenting Names: Use clear names like toggleMute() instead of buttonClick(). If the name explains the action, delete the comment entirely.

Was this helpful?

Amandalawrancee

Answered on Nov 12, 2025

your pig game implementation in java looks pretty interesting, but I noticed there’s a lot of repeated code blocks, and that kinda makes it harder to read the program structure. I had a similar problem once when I was writing a review about different card games, and back then I checked out https://blackjack-games.org/ — they explain in detail how to organize game flow and point calculation logic, which really helped me structure my code. and when I wanted something more dynamic, like unusual game mechanics, I looked at https://funkytimegame.org/ and got a few ideas on how to make the game more interactive. maybe if you add a bit more object-oriented approach and get inspired by these resources, the code will get even better!

Was this helpful?

Oliviaparkerr

Answered on Dec 4, 2024

Slither io is a favorite among streamers and content creators, thanks to its fast-paced action and unpredictable gameplay. Share your epic wins and hilarious fails with your audience for endless entertainment.

Was this helpful?

More Java discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Java Blogs

Guides, tips and career advice on Java from JanBask experts.