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 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:
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?
Now, the Snake class, which 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.
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.
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).
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.