The Wayback Machine - https://web.archive.org/web/20241128000639/https://www.geeksforgeeks.org/design-snake-game/
Open In App

Design Snake Game

Last Updated : 24 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Let us see how to design a basic Snake Game that provides the following functionalities:

  • Snake can move in a given direction and when it eats the food, the length of snake increases. 
  • When the snake crosses itself, the game will be over. 
  • Food will be generated at a given interval.

Asked In: Amazon, Microsoft, and many more interviews.

This question is asked in interviews to Judge the Object-Oriented Design skill of a candidate. So, first of all, we should think about the classes. 

The main classes will be:

  1. Snake 
  2. Cell 
  3. Board 
  4. Game 

The class Game represents the body of our program. It stores information about the snake and the board. The Cell class represents the one point of display/board. It contains the row no, column no and the information about it i.e. it is empty or there is food on it or is it a part of snake body?

Java




// 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; }
}


Java




// Enum for different cell types
 
public enum CellType {
 
    EMPTY,
    FOOD,
    SNAKE_NODE;
}


Now, the Snake class, contains the body and head. We have used Linked List to store the body because we can add a cell in O(1). 

Grow method will be called when it eats the food. Other methods are self-explanatory.

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; }
}


The Board class represents the display. It is a matrix of Cells. It has a method generate Food which generates the 
the food at a random position.

Java




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);
    }
}


The main class (Game) which keeps the instance of Snake and Board. It’s method “update” needs to be called at a fixed interval (with the help of user input).

Java




// 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;
        }
    }
}


Code Explanation:

  1. The code in this class represents a snake game.
  2. The Snake object stores the information about the snake and the Board object stores the information about the board.
  3. The direction variable keeps track of which direction the player is moving in (left, right, up, or down).
  4. The isGameOver() method checks to see if there is a game over condition.
  5. If there is a game over condition, then setGameOver() sets the gameOver flag to true so that it will stop playing when there is a game over.
  6. The getDirection() method returns an integer value that indicates which direction the player is currently moving in (0 for left, 1 for right, 2 for up, and -2 for down).
  7. The code is responsible for managing the game play of the Snake Game.
  8. The class has a number of properties and methods that are relevant to game play.
  9. The first property is the snake object which references the actual Snake Game character.
  10. The snake object has a number of properties including direction, board and gameOver.
  11. The next property is the Board object which references the playing surface on which the Snake Game takes place.
  12. The Board object also has a direction property which indicates where in space the player is located relative to the playing surface.
  13. The last two properties are used to keep track of whether or not the game is currently over.
  14. gameOver will be set to true if the player loses, whileisGameOver will be set to false if
  15. The code starts by printing out “Going to update the game.”
  16. This is a message that will be displayed every time the code executes.
  17. Next, the code checks to see if gameOver has been set to true.
  18. If it hasn’t, then the code sets direction to DIRECTION_NONE and sets gameOver to true.
  19. The next part of the code determines which cell in the snake’s head is being used as a reference point.
  20. The getNextCell() method uses row and col variables to determine this information.
  21. Then, it returns the Cell object for use in other parts of the program.
  22. The next section of code updates various aspects of the game based on user input from keyboard keys.
  23. First, it checks whether any key presses have been made.
  24. If so, it uses those key presses as inputs for moving or growing cells in the snake’s body.
  25. Finally, it updates various elements onscreen based on what was done with those cells (e.g., generating food).
  26. The code updates the game at regular intervals and accepts user input from the Keyboard.
  27. If the user inputs a direction other than DIRECTION_NONE, then the code sets the direction to that chosen input.
  28. If the user inputs a cell that is not on the snake’s path, then the code moves the snake to that cell and checks if it crashes into anything along its way.
  29. If it does, then set Direction to DIRECTION_NONE.
  30. Otherwise, if the cell is a food item, then the code will grow the snake and call generateFood() on board .
  31. The code starts by creating a new instance of the Snake class.
  32. This object will represent the player’s snake in the game.
  33. The initPos variable stores the location of this snake at any given time.
  34. Next, a new Board object is created and initialized with the size of the playing area (10×10).
  35. This board will be used to track where the snake has moved and what obstacles it has encountered along its way.
  36. A new Game object is then created, which contains information about the game itself as well as our snake instance.
  37. The gameOver property is set to false so that we can keep track of whether or not there is currently a game being played.
  38. The direction property is set to DIRECTION_RIGHT so that users can control their snake’s movement using their keyboard input.
  39. The code then periodically updates both the Game object and Board objects based on user input received from the Keyboard class.
  40. Whenever a keystroke is detected, an event handler for that particular key is called.
  41. In this case, we simply print out “Press left arrow to move left” onscreen whenever Left Arrow keystrokes are detected by our code.
  42. The code creates a new instance of the Snake game, initializes it to the given position (0, 0), and creates a new Board object.
  43. The code then creates a new Game object and sets its properties to match those of the Snake object.
  44. Next, the code declares two variables: initSnake and board.
  45. initSnake is an instance of the Snake class, while board is an instance of the Board class.
  46. The next line of code sets up a timer that will update the game at regular intervals.
  47. This will allow us to react to user input from the keyboard.
  48. Finally, the code declares two variables: gameOver and direction.
  49. gameOver is set to false so that the game can continue even if it reaches its end condition.

Reference: 
http://massivetechinterview.blogspot.com/2015/10/snake-game-design.html
 



Previous Article
Next Article

Similar Reads

Design Snake and Ladder Game using Python OOPS
This article covers designing a complete Snake and Ladder game using object-oriented programming (Python OOP) principles with the following rules and requirements. Below we will discuss the rules of the game: Here we create a board of size 10 and dice of side 6.Each player puts their counter on the board at starting position at 1 and takes turns to
13 min read
Game Theory (Normal form game) | Set 2 (Game with Pure Strategy)
Game Theory (Normal – form game) | Set 1 (Introduction) Please go through the above article before proceeding. Given a payoff matrix. The task is to find the optimum strategies of the players. Solution: Player A is having 3 strategies - 1, 2 and 3, and player B is also having 3 strategies - 1, 2 and 3. Step 1: Find row minimum values for each row a
2 min read
Game Theory (Normal-form game) | Set 3 (Game with Mixed Strategy)
Consider the following payoff matrix with respect to player A and solve it optimally. Solution: If a game has no saddle point then the game is said to have mixed strategy. Step 1: Find out the row minimum and column maximum. Step 2: Find out the minimax and maximin values. Since minimax and maximin value of this game are not equal, this game has no
4 min read
Game Theory (Normal-form Game) | Set 7 (Graphical Method [M X 2] Game)
The payoff matrix of an M * 2 game consists of M rows and two columns. This article will discuss how to solve an M * 2 game by graphical method. Also, this article will discuss if more than two lines intersect the same point in the graph then how can a 2 * 2 payoff matrix be formed. Consider the below problem: Solution: First check whether the prob
3 min read
Game Theory (Normal-form Game) | Set 6 (Graphical Method [2 X N] Game)
The payoff matrix of a 2 * N game consists of 2 rows and N columns . This article will discuss how to solve a 2 * N game by graphical method. Consider the below 2 * 5 game: Solution: First check the saddle point of the game. This game has no saddle point. Step 1: Reduce the size of the payoff matrix by applying dominance property, if it exists. Thi
3 min read
PyQt5 - Snake Game
In this article, we will see how we can design a simple snake game using PyQt5. Snake is the common name for a video game concept where the player maneuvers a line that grows in length, with the line itself being a primary obstacle. The concept originated in the 1976 arcade game Blockade, and the ease of implementing Snake has led to hundreds of ve
14 min read
Snake Water Gun game using Python and C
Snake Water Gun is one of the famous two-player game played by many people. It is a hand game in which the player randomly chooses any of the three forms i.e. snake, water, and gun. Here, we are going to implement this game using python. This python project is to build a game for a single player that plays with the computer Following are the rules
8 min read
Snake Game Using Tkinter - Python
For many years, players all across the world have cherished the iconic video game Snake. The player controls a snake that crawls around the screen while attempting to consume food, avoiding obstacles or running into its own tail. It is a straightforward but addictive game. The snake lengthens each time it consumes food, and the player must control
12 min read
Snake and Ladder Game in C
Snake and Ladder game is a traditional game that involves two or more players and the winner is the guy who reaches the final square on the game board at the earliest. Components of the GameA square board with a series of numbered squares arranged in m x m grid.A dice to be rolled usually uses a six-faced die.Each player uses different color tokens
5 min read
AI Driven Snake Game using Deep Q Learning
Content has been removed from this Article
1 min read
Create a Snake Game in React
Snake Game using ReactJS project implements functional components and manages the state accordingly. The developed Game allows users to control a snake using arrow keys or touch the buttons displayed on the screen to collect food and grow in length. The goal of the game is to eat as much food as possible without colliding with the walls or the snak
7 min read
Create a snake game using HTML, CSS and JavaScript
Snake Game is a single-player game where the snake gets bigger by eating the food and tries to save itself from the boundary of the rectangle and if the snake eats their own body the game will be over. Game Rules:If the snake goes out of the boundary or eats its own body the game will be over.Prerequisites:HTMLCSSJavaScriptApproachSelect the board
4 min read
Snake Game using Angular
Snake game is one of the most popular software games ever made for computers as well as mobile devices. It is a simple game where player has to control the snake and eat food which are randomly spawned in order to score points. In this article, we will be creating the snake game using the Angular framework. Note that this tutorial uses Angular vers
4 min read
Snake Game in Python - Using Pygame module
Snake game is one of the most popular arcade games of all time. In this game, the main objective of the player is to catch the maximum number of fruits without hitting the wall or itself. Creating a snake game can be taken as a challenge while learning Python or Pygame. It is one of the best beginner-friendly projects that every novice programmer s
15+ min read
Create a Snake-Game using Turtle in Python
A snake game is an arcade maze game which has been developed by Gremlin Industries and published by Sega in October 1976. It is considered to be a skillful game and has been popularized among people for generations. The snake in the Snake game is controlled using the four direction buttons relative to the direction it is headed in. The player's obj
8 min read
Figma for Game Design: Tips for Designing Game Interfaces
Game designing is an integral part of designing on Figma. It involves creating multiple creative & interactive user interfaces which help in building of popular games such as Chess, Ludo, fighting games etc. In this article, we will learn a few tips to design gaming interfaces, in particular, Chess. Step-by-Step Process to Design a Game UI1. De
4 min read
Game Theory (Normal - form game) | Set 1 (Introduction)
Game theory is a mathematical model used for decision making. It has applications in all fields of social science, as well as in logic and computer science. Game theory has come to play an increasingly important role in logic and in computer science. To be fully defined, a game must specify the following elements: the players of the game, the infor
4 min read
Game Theory (Normal-form Game) | Set 5 (Dominance Property-Mixed Strategy)
This article discusses how to solve a game by the dominance property with mixed strategy. Consider the below game: Solution: Find out the row minimum and column maximum values. Here Minimax value is not equal to Maximin so this game has no saddle point. Now proceed with dominance property to reduce the rows and the columns. Reducing the row and the
2 min read
Combinatorial Game Theory | Set 2 (Game of Nim)
We strongly recommend to refer below article as a prerequisite of this. Combinatorial Game Theory | Set 1 (Introduction) In this post, Game of Nim is discussed. The Game of Nim is described by the following rules- “ Given a number of piles in which each pile contains some numbers of stones/coins. In each turn, a player can choose only one pile and
15+ min read
Game Theory (Normal-form Game) | Set 4 (Dominance Property-Pure Strategy)
In some of the games, it is possible to reduce the size of the payoff matrix by eliminating rows (or columns) that are dominated by other rows (or columns) respectively. Dominance property for rows: X ≤ Y i.e. if all the elements of a particular row X are less than or equal to the corresponding elements of another row Y then delete row X (row X is
4 min read
Play Battleships Game with AI: Insights into Algorithmic Strategies and Game Mastery
Battleships, a popular game of naval strategy, have long been a testbed for developing sophisticated algorithmic and AI approaches. This article explores the evolution and application of these technologies in mastering Battleships, offering insights into the integration of AI in-game strategy. Table of Content Understanding the Basics of Battleship
10 min read
Winning Game by replacing numbers with factors (Brain Game)
Given 2 players A and B take turns alternatively to play a game in which they have N numbers on a paper. In one turn, a player can replace one of the numbers by any of its factors (except for 1 & the number itself). The player who is unable to make a move loses the game. Find the winner of the game if A starts the game and both play optimally.
15+ min read
Sony Junior Game Developer to Game Developer
Starting your career in the video game industry is the dream of many young developers, and Sony Interactive Entertainment, or SIE, is one of the benchmarks in this industry. Thus, Sony, as a global brand that has a long experience in game console development and prominent game titles, targets promising junior developers to foster new talent in the
13 min read
Game of Chocolates | Wythoff's Game
Bunty and Dolly are playing a game, described as follows:There are two boxes having A and B number of chocolates respectively. Both can eat L (L >= 1) chocolates from any one box or L chocolates from both boxes in one move. They play the game alternatively and the last one to eat the chocolate will be the winner. You have to help Bunty in decidi
13 min read
Xbox Game Pass vs. Xbox Game Pass Ultimate: Which is Right for You?
Xbox Game Pass and Xbox Game Pass Ultimate are two popular subscription services offered by Microsoft, designed to provide gamers with access to a vast library of games for a monthly fee. However, there are key differences between the two services that can impact your choice depending on your gaming needs. Here’s a detailed comparison of Xbox Game
4 min read
Transitioning from Game Designer to Game Developer
In the ever-evolving world of game development, transitioning from a Game Designer to a Game Developer can open up significant opportunities. While both roles are integral to creating games, they involve different skill sets, responsibilities, and tools. In this article, we'll explore the differences between these profiles(Game Designer and Game De
9 min read
Print matrix in snake pattern from the last column
Given a matrix of 2-Dimensional array of n rows and n columns. Print this matrix in snake fashion starting from column n-1 as shown in the figure below . Examples: Input : mat[][] = 1 2 3 4 5 6 7 8 9 Output: 3 2 1 4 5 6 9 8 7 Input: mat[][] = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 4 3 2 1 5 6 7 8 12 11 10 9 13 14 15 16 Algorithm: Start trav
6 min read
Python - Convert Snake case to Pascal case
Sometimes, while working with Python Strings, we have problem in which we need to perform a case conversion of String. This a very common problem. This can have application in many domains such as web development. Lets discuss certain ways in which this task can be performed. Input : geeks_for_geeks Output : GeeksforGeeks Input : left_index Output
7 min read
Converting all keys into snake case in multidimensional array in PHP
In the Snake case, we need to convert a given sentence or a word to a style of writing where all upper case characters will be replaced with lower case and all the gaps will be replaced with an underscore(_). In this article, we will see how to find the snake case of the all keys of a given array. Here, we need to check each of the elements present
4 min read
How to convert camel case to snake case in JSON response implicitly using Node.js ?
Camel case and snake case are two common conventions for naming variables and properties in programming languages. In camel case, compound words are written with the first word in lowercase and the subsequent words capitalized, with no spaces or underscore between them. For example, firstName is written in camel case. In snake case, compound words
5 min read
Article Tags :
three90RightbarBannerImg