Monday 8 June 2015

0

Snake Game written in JAVA (Full Source Code)

  • Monday 8 June 2015
  • Share
  • 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:
     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;  
       }  
     } 
     
     

    0 Responses to “Snake Game written in JAVA (Full Source Code) ”

    Post a Comment

    Subscribe