How To Design A Snake Game? Explained SNAKE 🐍 GAMES

0
209
Snake Game

There’s no denying the fact that the snake game is one of the most popular games of all time. In fact, this game occupies a central place in gamer’s hearts. Over the years, many people have made their own versions of this game and succeeded a lot. So, fans may like to know that there are easy ways to make this game. 

If you are curious about how you can code your own version of this critically acclaimed video game, then you are at the right place. As we mentioned earlier, it’s very easy to design this game. So, now’s the time to go through this article, and find out how to design this snake video game. 

Designing A Snake Game

So, as mentioned previously, designing a snake game has become extremely easy nowadays with a couple of easy-to-follow steps. Let’s take a look at how to design a basic snake video game that provides key functionalities. This game will be able to do the following things: 

  • The snake can move in a particular direction and when it eats the good, the length of the snake will increase. 
  • If the snake crosses itself, the game will end. 
  • The game will generate the food at a particular interval. 

So, now that we know the objectives, it’s time to take a look at how we can make this game. First of all, there are four classes behind this game that one should know about: Snake, Cell, Board, and Game. According to the reports, the class game represents the entire body of the program. In fact, it stores info about the snake as well as the board. 

The cell class also represents the one point of the display or board. In other words, it contains the row number, column number, and also the information about it: as such, whether it’s empty, there’s food, or whether it’s part of the snake’s body. 

Java Code To Represent The Cell Of Display Board

// To represent a cell of display board

public class Cell {

private final int row, col;

private CellType cellType;

public Cell(int row, int col)

{

this.row = row;

this.col = col;

}

public CellType getCellType() { return cellType; }

public void setCellType(CellType cellType)

{

this.cellType = cellType;

}

public int getRow() { return row; }

public int getCol() { return col; }

}

Moroever, 

// Enum for different cell types

public enum CellType {

EMPTY,

FOOD,

SNAKE_NODE;

}

Furthermore, one should also know that the snake class contains the body and head. So, there’s also a linked list to store the body because one can still add a cell in O(1). The “Grow Method” will be called when the snake eats the food. On the other hand, the other methods are quite self-explanatory. 

How To Represent Snake Using Java 

// To represent a snake

import java.util.LinkedList;

public class Snake {

private LinkedList<Cell> snakePartList

= new LinkedList<>();

private Cell head;

public Snake(Cell initPos)

{

head = initPos;

snakePartList.add(head);

head.setCellType(CellType.SNAKE_NODE);

}

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

public void move(Cell nextCell)

{

System.out.println(“Snake is moving to “

+ nextCell.getRow() + ” “

+ nextCell.getCol());

Cell tail = snakePartList.removeLast();

tail.setCellType(CellType.EMPTY);

head = nextCell;

head.setCellType(CellType.SNAKE_NODE);

snakePartList.addFirst(head);

}

public boolean checkCrash(Cell nextCell)

{

System.out.println(“Going to check for Crash”);

for (Cell cell : snakePartList) {

if (cell == nextCell) {

return true;

}

}

return false;

}

public LinkedList<Cell> getSnakePartList()

{

return snakePartList;

}

public void

setSnakePartList(LinkedList<Cell> snakePartList)

{

this.snakePartList = snakePartList;

}

public Cell getHead() { return head; }

public void setHead(Cell head) { this.head = head; }

}

Next, the Board class will represent the display part of the game. Readers may like to know that it’s a matrix of Cells, and it has a method to generate Food which generates at a random position. 

Board Class codes

public class Board {

final int ROW_COUNT, COL_COUNT;

private 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 Cell[][] getCells() { return cells; }

public void setCells(Cell[][] cells)

{

this.cells = cells;

}

public void generateFood()

{

System.out.println(“Going to generate food”);

int row = 0, column = 0;

while (true) {

row = (int)(Math.random() * ROW_COUNT);

column = (int)(Math.random() * COL_COUNT);

if (cells[row][column].getCellType()

!= CellType.SNAKE_NODE)

break;

}

cells[row][column].setCellType(CellType.FOOD);

System.out.println(“Food is generated at: ” + row

+ ” ” + column);

}

}

On the other hand, the Main Class or the Game that keeps the instance of the board and the snake is also important to note. It’s a method update that you need to call at a fixed interval, with the help of user input. 

Codes To Represent The Snake Game

// To represent Snake Game

public class Game {

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 Game(Snake snake, Board board)

{

this.snake = snake;

this.board = board;

}

public Snake getSnake() { return snake; }

public void setSnake(Snake snake)

{

this.snake = snake;

}

 

public Board getBoard() { return board; }

 

public void setBoard(Board board)

{

this.board = board;

}

public boolean isGameOver() { return gameOver; }

public void setGameOver(boolean gameOver)

{

this.gameOver = gameOver;

}

public int getDirection() { return direction; }

public void setDirection(int direction)

{

this.direction = direction;

}

// We need to update the game at regular intervals,

// and accept user input from the Keyboard.

public void update()

{

System.out.println(“Going to update the game”);

if (!gameOver) {

if (direction != DIRECTION_NONE) {

Cell nextCell

= getNextCell(snake.getHead());

if (snake.checkCrash(nextCell)) {

setDirection(DIRECTION_NONE);

gameOver = true;

}

else {

snake.move(nextCell);

if (nextCell.getCellType()

== CellType.FOOD) {

snake.grow();

board.generateFood();

}

}

}

}

}

private Cell getNextCell(Cell currentPosition)

{

System.out.println(“Going to find next cell”);

int row = currentPosition.getRow();

int col = currentPosition.getCol();

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.getCells()[row][col];

return nextCell;

}

public static void main(String[] args)

{

System.out.println(“Going to start game”);

Cell initPos = new Cell(0, 0);

Snake initSnake = new Snake(initPos);

Board board = new Board(10, 10);

Game newGame = new Game(initSnake, board);

newGame.gameOver = false;

newGame.direction = DIRECTION_RIGHT;

// We need to update the game at regular intervals,

// and accept user input from the Keyboard.

// here I have just called the different methods

// to show the functionality

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

if (i == 2)

newGame.board.generateFood();

newGame.update();

if (i == 3)

newGame.direction = DIRECTION_RIGHT;

if (newGame.gameOver == true)

break;

}

}

}

Explanation Of The Codes

So, now that we have the codes ready for the game, it’s time to find out what these codes do. In other words, we will now provide an explanation of the codes as mentioned before. One can design the snake video game using the codes that we provided in this article. So, without further ado, it’s time to take a look at what these codes can do.

  • First of all, the code in this class represents a basic snake video game. According to the reports, the snake object stores all the details about the snake, and the board object, on the other hand, stores the information about the board. 
  • The direction variable part allows one to keep track of which direction the player is moving, i.e., left, right, up, and down. Moreover, the isGameOver() method would check if there’s a game-over condition. So, if there indeed is a gameover condition, then the code setGameOver() will set the gameOver flag to ‘true’ so that it will stop playing once there’s a gameover. 
  • On the other hand, the getDirection() method will return an integer value indicating which direction the player is currently moving in. For example, 0 for left, 1 for right, 2 for up, or -2 for down. These codes are responsible for managing the gameplay of the Snake video game. In fact, we should also note that the class has a number of properties and methods relevant enough for gameplay. 
  • The optimum priority of the snake object which references the actual Snake Video Game character is another thing you should know about. The snake object also has a lot of properties, including board, gameOver, and direction.
  • The next property of this is as we know, the Board Object. It references the playing surface on which the whole game takes place. According to the reports, the Board Object also has its own direction properties that indicate where in space the player is located relative to the playing area. The last two properties of the code let one keep track of whether or not the game is currently over. 
  • Next, gameOver will be set to true if the player loses the game, while isGameOver will make it to false if the code starts printing out ‘Going to update the game”. According to the reports, this message will be displayed every time the code executes according to its design. Moreover, the code will also check if the gameOver has been set to true or not. If it hasn’t, then the code will set the direction to DIRECTION_NONE and set the gameOver option to True. 
  • The next part of the code determines which cell in the head of the snake is being used as the reference point. Moreover, the getNextCell() method will use row and col variables to determine this information. It will then return to the Cell Object for use in the other parts of the program. 
  • So, readers would like to know that the next section updates various aspects of the game which is based on user input from the keys. Firstly, it will update various elements onscreen based on what was done with those previous cells, such as generating food. Next, the code will update the game at regular intervals and also accept inputs provided by the user. For example, if the user inputs a cell that’s not on the snake’s path, then the code will move the snake to that cell, and check if it crashes into anything along its way or not. 
  • If the snake crashes along its path, the code will set Direction to DIRECTION_NONE. Or else, if the cell is a food item, then the code will grow the snake and cell will become generateFood() on board. Moreover, the code starts by creating a new instance of the Snake class that we know of. This will represent the player’s snake in the game. 
  • Readers should know that the initPos variable stores the location of the snake at a particular time. Next, a new board object will be created and initialized with the size of the playing area, such as 10×10. According to the design, this board will be used to track where the snake has moved and what sort of obstacles it has encountered along its path. A new game object will also be created that contains info about the game itself and the snake. 
  • Moreover, the gameOver property will be set to false so that we can keep track of whether or not a game is being currently played. Readers should know that this code periodically updates both the game object and the board objects based on the inputs received from the user. 
  • Whenever it detects a keystroke, an event handler for that particular key will be called. So, in that case, we can simply print out “Press left arrow to move left” onscreen whenever we press Left Arrow keystrokes. Moreover, this code will also create a new Game object and set its properties to match those of the snake object that we know. The code will also declare its two variables such as initSnake and Board. So, according to the reports, the initSnake is an instance of the Snake’s class, whereas, the board is of the board class. 
  • The next code sets up a timer that will update the snake video game at regular intervals, allowing it to react to user input from the keyboard. Finally, the code will declare two variables, such as gameOver and direction. gameOver will be set to false for the game to continue even if it reaches its condition.

So, that’s how you can create a simple and easy snake video game. You just need to pay attention to the codes that you will be using. Overall, it’s an iconic game that deserves it be played by the masses.

Read Also: Joining a Blooket Game and Learn New Things about Codes