1 Şubat 2014 Cumartesi

Snake Game written in JAVA (Full Source Code)

In this article, I'll re-write a simplified version of the very famous game "Snake" in JAVA programming language. You can easily find dozens of similar source code by googling around, however, a majority of them are far from being simple that the game requires, containing complex scripts and hard to read and to understand. Especially, the examples in JAVA are written by unskilled programmers who are anaware of what Object Oriented Programming is ... (more)

In this article, I'll try to make the source code easily readable and understandable by dividing the whole code into small JAVA classes and by using the flexibility that JAVA provides. At the end of this article, the overall appearance of our project will be as follows:

JAVA sınıf yapısı


 Now, we can start writing our classes. Let's name our first class Cell.java:

public class Cell {

    final static int CELL_TYPE_EMPTY = 0, CELL_TYPE_FOOD = 10, CELL_TYPE_SNAKE_NODE = 20;
    final int row, col;
    int type;

    public Cell(int row, int col) {
        this.row = row;
        this.col = col;
    }
}

This class only keeps row and column numbers. Also some constant integers to determine the types of cells.

Our second class is Board.java. This class will allow us to identify the area where snake navigates (like a chessboard). Our class is as follows:

public class Board {

    final int ROW_COUNT, COL_COUNT;
    Cell[][] cells;

    public Board(int rowCount, int columnCount) {
        ROW_COUNT = rowCount;
        COL_COUNT = columnCount;

        cells = new Cell[ROW_COUNT][COL_COUNT];
        for (int row = 0; row < ROW_COUNT; row++) {
            for (int column = 0; column < COL_COUNT; column++) {
                cells[row][column] = new Cell(row, column);
            }
        }
    }

    public void generateFood() {
        int row = (int) (Math.random() * ROW_COUNT);
        int column = (int) (Math.random() * COL_COUNT);

        cells[row][column].type = Cell.CELL_TYPE_FOOD;
    }
}

In this class, we are creating a two-dimensional array of the class "Cell" sized by rowCount * columnCount.
generatefood() is assigning the type of a random Cell to CELL_TYPE_FOOD.

Our third class is Snake.java. 

public class Snake {

    LinkedList<Cell> snakePartList = new LinkedList<>();
    Cell head;

    public Snake(Cell initPos) {
        head = initPos;
        snakePartList.add(head);
    }

    public void grow() {
        snakePartList.add(head);
    }

    public void move(Cell nextCell) {
        Cell tail = snakePartList.removeLast();
        tail.type = Cell.CELL_TYPE_EMPTY;

        head = nextCell;
        snakePartList.addFirst(head);
    }

    public boolean checkCrash(Cell nextCell) {
        for (Cell cell : snakePartList) {
            if (cell == nextCell) {
                return true;
            }
        }

        return false;
    }
}

Finally, our last class Router.java:

public class Router {

    public static final int DIRECTION_NONE = 0, DIRECTION_RIGHT = 1, DIRECTION_LEFT = -1, DIRECTION_UP = 2, DIRECTION_DOWN = -2;
    private Snake snake;
    private Board board;
    private int direction;
    private boolean gameOver;

    public Router(Snake snake, Board board) {
        this.snake = snake;
        this.board = board;
    }

    public void setDirection(int direction) {
        this.direction = direction;
    }

    public void update() {
        if (!gameOver) {
            if (direction != DIRECTION_NONE) {
                Cell nextCell = getNextCell(snake.head);

                if (snake.checkCrash(nextCell)) {
                    setDirection(DIRECTION_NONE);
                    gameOver = true;
                } else {
                    snake.move(nextCell);
                    if (nextCell.type == Cell.CELL_TYPE_FOOD) {
                        snake.grow();
                        board.generateFood();
                    }
                }
            }
        }
    }

    private Cell getNextCell(Cell currentPosition) {
        int row = currentPosition.row;
        int col = currentPosition.col;

        if (direction == DIRECTION_RIGHT) {
            col++;
        } else if (direction == DIRECTION_LEFT) {
            col--;
        } else if (direction == DIRECTION_UP) {
            row--;
        } else if (direction == DIRECTION_DOWN) {
            row++;
        }

        Cell nextCell = board.cells[row][col];

        return nextCell;
    }
}

Here are the base JAVA classes of our snake game project. If we look into the source code deeply, we realize that, these codes may not fulfill some of the advanced features of the game. 

It is up to you to enhance this project to fulfill the requirements of your imagination. I played around the code to make it seem like the screenshot below:

JAVA Yılan Oyunu


19 yorum:

  1. Hi,
    thanks dude for your article.
    classes for snake game are so simple and useful, but i couldnt find jframe and applet for complete the game please help me. thanks for your attention. see u later.

    YanıtlaSil
  2. I have been searching for a guide to start my snake project and no one made it so clear and simple as you! Thanks for the help!

    YanıtlaSil
  3. how to run this pls teach me

    YanıtlaSil
  4. Which one is the main class of the project?

    YanıtlaSil
    Yanıtlar
    1. Which one is the main class of the project?

      Sil
    2. Bu yorum bir blog yöneticisi tarafından silindi.

      Sil
  5. How to run this project? There is no main method or no applet in this project

    YanıtlaSil
    Yanıtlar
    1. How to run this project? There is no main method or no applet in this project

      Sil
    2. HOW CAN RUN THIS PROJECT

      Sil
  6. Hii Sir,

    Your Provided Java projects helped me to get good score in engineering. thank you for providing java projects with source code.

    YanıtlaSil
  7. ashok chavan Oh great, so you managed to cheat basically.

    YanıtlaSil
  8. ashok chavan Oh great, so you managed to cheat basically.

    YanıtlaSil
  9. where is the main class of this whole code bro

    YanıtlaSil
  10. what is the error on snake java code... part on LinkedList
    ?

    YanıtlaSil
    Yanıtlar
    1. you need to add a line to the top of that class:
      import java.util.*;

      Sil
  11. how to run this project ?

    YanıtlaSil
  12. I have a project to submit tomorrow I’m quite confused so I’ve decided to use your work I pray I pass ����

    YanıtlaSil