353. Design Snake Game

Problem

Design the snake game. Move the snake and return the current score, or -1 if the snake hits a wall or itself.

Design the classic Snake game with:

  • SnakeGame(width, height, food): Initialize the game on a width x height grid. food is an ordered list of [row, col] cells. Only the next uneaten food cell is active. Food appears in order and is not on a cell occupied by the snake when it appears; coordinates need not be distinct if the snake has vacated a cell before that later food appears.
  • move(direction): Move the snake one cell in the given direction ("U", "D", "L", "R"). Return the score after the move, or -1 if the game ends.

Rules:

  • The snake starts as a single cell at the top-left corner (0, 0).
  • The snake moves one cell at a time.
  • Eating food increases the score by 1 and grows the snake by one cell (the tail does not move that turn).
  • The game ends if the snake hits a wall or its own body. After game over, every later move call returns -1.
  • On a move that does not eat food, the tail vacates its cell before self-collision is decided, so the head may enter that cell. On a move that eats food, the tail does not move and remains part of the body for collision checking.
Examples
Input: [["SnakeGame","move","move","move","move","move","move"],[[3,2,[[1,2],[0,1]]],["R"],["D"],["R"],["U"],["L"],["U"]]]
Output: [null,0,0,1,1,2,-1]
Hints
Related Problems

353. Design Snake Game

Design the snake game. Move the snake and return the current score, or -1 if the snake hits a wall or itself.