Let us see how to design a basic Snake Game which provides the following functionalities:
• Snake can move in a given direction and when it eats the food, the length of snake increases.
• When snake crosses itself, the game will over.
• Food will be generated at 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:
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 a food on it or is it a part of snake body?
Now, the Snake class, which contains the body and head.
We have used LinkedList 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.
The Board class represents the display. It is a matrix of Cells. It has a method generateFood which generates the
food at random position.
The main class (Game) which keeps the instance of Snake and Board. It’s method “update” needs to be called at a fixed intervals (with the help of user input).
- Design a Chess Game
- Is the future with snake(Python) or Coffee(Java) ?
- RTL (Register Transfer Level) design vs Sequential logic design
- Variation in Nim Game
- Check if the game is valid or not
- The prisoner's dilemma in Game theory
- Guess Game using rand() and srand() in C
- Python | Program to implement simple FLAMES game
- Design a Hit Counter
- HTML | Design Form
- Design a Logistics System
- Design a data structure for LRU Cache
- Design an online book reader system
- Compiler Design | Syntax Directed Definition
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.