353. Design Snake Game #349
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Resolves: #85
Algorithm:
The thing that we can notice is that the snake is just a linked list of points on the grid that we are playing the game on. Using this intuition, we can easily represent the snake using a linked list of points, for which we can create a simple auxiliary class.
To move in any given input direction, we can peek the head of the snake and increment it in the given direction. If this new head of the snake intersects any of the points of the snake besides its moving tail, this means that the game should be over.
If this new head tried to move outside the bounds of the grid, this means that the game should be over.
Since all food does not appear on the screen at once, rather one-by-one, we can keep track of which food is on the screen through the score. If we the new head is in some food tile, then we increment the score counter and return the new score, with the incremented score also operating to make the new food "appear" on the grid.
If snake doesn't eat food, that means its length stays constant and its tail should be removed.
After doing all these, we return the score if possible.