# \*353. Design Snake Game

<https://leetcode.com/problems/design-snake-game/>

## solution

```python
import collections

class SnakeGame:
    def __init__(self, width: int, height: int, food: List[List[int]]):
        self.width = width
        self.height = height

        self.food = collections.deque(food)
        self.score = 0

        self.snake = collections.deque([(0, 0)])
        self.snake_positions = set([(0, 0)])

    def move(self, direction: str) -> int:
        head_row, head_col = self.snake[0]

        if direction == 'U':
            head_row -= 1
        elif direction == 'D':
            head_row += 1
        elif direction == 'L':
            head_col -= 1
        elif direction == 'R':
            head_col += 1

        if head_row < 0 or head_row >= self.height or head_col < 0 or head_col >= self.width:
            return -1

        if self.food and [head_row, head_col] == self.food[0]:
            self.food.popleft()  # Eat the food
            self.score += 1  # Increase the score
        else:
            tail = self.snake.pop()
            self.snake_positions.remove(tail)

        if (head_row, head_col) in self.snake_positions:
            return -1

        self.snake.appendleft((head_row, head_col))
        self.snake_positions.add((head_row, head_col))
        return self.score
```

时间复杂度：O()\
空间复杂度：O()


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://longxingtan.gitbook.io/mle-interview/01_leetcode/17_design/353.-design-snake-game.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
