Implement a stripped‑down version of the classic Snake game that runs on a 2D grid. The snake starts in the top‑left cell and grows automatically every five moves – there is no food. Collision logic is the same as the original: the game is over the moment the snake’s head leaves the board or enters a cell already occupied by its body.
Design a class SnakeGame:
SnakeGame(int width, int height)
width and height.(0, 0) with a starting length of 1.int move(String direction)
direction, which is "W" (up), "S" (down), "A" (left) or "D" (right).1 ≤ width, height ≤ 10⁴move.Input:
["SnakeGame", "move", "move", "move", "move", "move", "move", "move", "move", "move", "move", "move"]
[[3, 2], ["D"], ["S"], ["D"], ["W"], ["A"], ["A"], ["S"], ["D"], ["D"], ["W"], ["W"]]
Output:
[null, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, -1]
Explanation:
SnakeGame game = new SnakeGame(3, 2); – A 3×2 board is created; the snake occupies (0, 0).game.move("D"); → returns 1. Head moves right to (0, 1); length remains 1.game.move("S"); → returns 1. Head moves down to (1, 1); length remains 1.game.move("D"); → returns 1. Head moves right to (1, 2); length remains 1.game.move("W"); → returns 1. Head moves up to (0, 2); length remains 1.game.move("A"); → returns 2. This is the 5th move: the head shifts left to (0, 1), the tail does not move, so length grows to 2.game.move("A"); → returns 2. Head moves left to (0, 0); length remains 2.game.move("S"); → returns 2. Head moves down to (1, 0); length remains 2.game.move("D"); → returns 2. Head moves right to (1, 1); length remains 2.game.move("D"); → returns 2. Head moves right to (1, 2); length remains 2.game.move("W"); → returns 3. The 10th move: head goes up to (0, 2) and the tail stays still, so length becomes 3.game.move("W"); → returns ‑1. Head moves up to (-1, 2), leaving the grid, so the game terminates.