Java Program To Make A Snake Game

Chapter: Miscellaneous Last Updated: 15-08-2023 14:29:28 UTC

Program:

            /* ............... START ............... */
                

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

public class SnakeGame extends JPanel implements ActionListener, KeyListener {
    private static final int WIDTH = 640;
    private static final int HEIGHT = 480;
    private static final int UNIT_SIZE = 20;
    private static final int GAME_UNITS = (WIDTH * HEIGHT) / (UNIT_SIZE * UNIT_SIZE);
    private static final int DELAY = 100;

    private final int[] snakeX = new int[GAME_UNITS];
    private final int[] snakeY = new int[GAME_UNITS];
    private int snakeLength = 1;

    private int foodX;
    private int foodY;

    private char direction = 'R';
    private boolean isRunning = false;

    private final Random random;

    public SnakeGame() {
        random = new Random();
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        setBackground(Color.black);
        setFocusable(true);
        addKeyListener(this);
        startGame();
    }

    public void startGame() {
        isRunning = true;
        newFood();
        snakeX[0] = WIDTH / 2;
        snakeY[0] = HEIGHT / 2;
        Timer timer = new Timer(DELAY, this);
        timer.start();
    }

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

    public void draw(Graphics g) {
        if (isRunning) {
            for (int i = 0; i < snakeLength; i++) {
                if (i == 0) {
                    g.setColor(Color.green);
                    g.fillRect(snakeX[i], snakeY[i], UNIT_SIZE, UNIT_SIZE);
                } else {
                    g.setColor(Color.yellow);
                    g.fillRect(snakeX[i], snakeY[i], UNIT_SIZE, UNIT_SIZE);
                }
            }

            g.setColor(Color.red);
            g.fillRect(foodX, foodY, UNIT_SIZE, UNIT_SIZE);
        } else {
            gameOver(g);
        }
    }

    public void newFood() {
        foodX = random.nextInt((int) (WIDTH / UNIT_SIZE)) * UNIT_SIZE;
        foodY = random.nextInt((int) (HEIGHT / UNIT_SIZE)) * UNIT_SIZE;
    }

    public void move() {
        for (int i = snakeLength; i > 0; i--) {
            snakeX[i] = snakeX[i - 1];
            snakeY[i] = snakeY[i - 1];
        }

        switch (direction) {
            case 'U':
                snakeY[0] -= UNIT_SIZE;
                break;
            case 'D':
                snakeY[0] += UNIT_SIZE;
                break;
            case 'L':
                snakeX[0] -= UNIT_SIZE;
                break;
            case 'R':
                snakeX[0] += UNIT_SIZE;
                break;
        }
    }

    public void checkFoodCollision() {
        if (snakeX[0] == foodX && snakeY[0] == foodY) {
            snakeLength++;
            newFood();
        }
    }

    public void checkCollision() {
        for (int i = snakeLength; i > 0; i--) {
            if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]) {
                isRunning = false;
            }
        }

        if (snakeX[0] < 0 || snakeX[0] >= WIDTH || snakeY[0] < 0 || snakeY[0] >= HEIGHT) {
            isRunning = false;
        }

        if (!isRunning) {
            // Game over
        }
    }

    public void gameOver(Graphics g) {
        // Game over message
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (isRunning) {
            move();
            checkFoodCollision();
            checkCollision();
        }
        repaint();
    }

    @Override
    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();
        if (key == KeyEvent.VK_LEFT && direction != 'R') {
            direction = 'L';
        } else if (key == KeyEvent.VK_RIGHT && direction != 'L') {
            direction = 'R';
        } else if (key == KeyEvent.VK_UP && direction != 'D') {
            direction = 'U';
        } else if (key == KeyEvent.VK_DOWN && direction != 'U') {
            direction = 'D';
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Snake Game");
        SnakeGame game = new SnakeGame();
        frame.add(game);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

                /* ............... END ............... */
        

Notes:

  • Please note that this code provides a basic foundation for a console-based Snake game. You'll need to implement the missing parts, like the game over message and better collision detection. Additionally, this code may not include advanced features such as levels or scores, which you can implement as you further develop the game.
  • Steps for Running the Game:
  • You need to compile and run the program using a Java compiler and runtime environment.
  • The game runs in the terminal/console window, and you control the snake using arrow keys.
  • The snake grows when it consumes food, and the game ends if the snake collides with itself or the screen boundaries.
  • Remember that this is a basic implementation. You can enhance the game by adding features like scoring, levels, obstacles, and a graphical user interface using libraries like Java Swing or JavaFX.
Similar Programs Chapter Last Updated
Find Unique Elements In List Java Miscellaneous 07-10-2023
Java Program To Implement A Custom equals() and hashcode() In Java Miscellaneous 07-10-2023
Java Program To Find The Intersection Of Two HashSets Miscellaneous 07-10-2023
Java Program To Remove Duplicate Elements From List Miscellaneous 07-10-2023
Java program to parse a date and time string from a log file and store it in a database Miscellaneous 19-09-2023
Java Program To Print All The Dates In A Month That Fall On A Weekend Miscellaneous 19-09-2023
Java Program To Find Number Of Working Days In A Month Miscellaneous 19-09-2023
Java Program To Calculate Age From Year Of Birth Miscellaneous 16-09-2023
How To Check If Two Strings Are Anagrams In Java Miscellaneous 22-08-2023
Java Program To Find Repeated Characters Of String Miscellaneous 15-08-2023
String To Array In Java Miscellaneous 11-08-2023
Java Program To Convert Date To String Miscellaneous 11-08-2023
Java Program To Convert String To Date Object Miscellaneous 11-08-2023
Java Program To Find Number Of Days In A Month Miscellaneous 11-08-2023
Java Program To Print First And Last Day Of Month Miscellaneous 11-08-2023
Java Program To Find Leap Year Between Two Dates Miscellaneous 11-08-2023
Java Code To Find Difference Between Two Dates In Years Months And Days Miscellaneous 11-08-2023
Java program to calculate age from year of birth Miscellaneous 29-06-2023
Swap Two Numbers Without Using Third Variable In Java Miscellaneous 02-06-2023
Java Program To Find The Average Of An Array Of Numbers Miscellaneous 02-06-2023
How Do You Find The Factorial Of A Number In Java Miscellaneous 02-06-2023
Java Program That Takes Two Numbers As Input And Prints Their Sum Miscellaneous 27-05-2023
How To Get The Length Of An Array In Java Miscellaneous 27-05-2023
Java Add Element To List Example Miscellaneous 19-05-2023
Java Program To Square All Items In List Miscellaneous 17-05-2023
Java Program To Merge Two Lists Miscellaneous 17-05-2023
How To Reverse A List In Java Miscellaneous 17-05-2023
Java Program To Find Unique Elements In An Array Miscellaneous 14-05-2023
Java Program To List All Elements In List Miscellaneous 30-04-2023
Java Program To Create XML File Miscellaneous 23-04-2023

1 2