Problem solution · Python

Design Snake Game

Design Snake Game: a Python solution using sliding window or two pointers. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Sliding window or two pointers
Source
walkccc LeetCode Solutions
Length
73 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Sliding window or two pointers

For Design Snake Game, the implementation maintains a moving interval and updates only the information that enters or leaves the window.

  1. Choose the invariant that makes a window valid or useful.
  2. Advance the right boundary and add the new element.
  3. Move the left boundary only as needed while maintaining the invariant and updating the answer.

Code notes

  • 73 lines of Python from the credited upstream file 353.py.
  • The implementation visibly relies on sequence storage, ordered lookup, work queue.
  • No explicit loop blocks detected.

Complexity

Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeDesign Snake Game · PythonPython
Use this to learn the idea, then write your own version.
class SnakeGame:  def __init__(self, width: int, height: int, food: list[list[int]]):    """    Initialize your data structure here.    @param width - screen width    @param height - screen height    @param food - A list of food positions    E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].    """    self.width = width    self.height = height    self.food = food    self.score = 0    self.k = 0  # food's index    self.lookup = set([self.getId(0, 0)])    self.body = collections.deque([self.getId(0, 0)])  # snake's body   def move(self, direction: str) -> int:    """    Moves the snake.    @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down    @return The game's score after the move. Return -1 if game over.    Game over when snake crosses the screen boundary or bites its body.    """    # the old head's position    i = self.body[0] // self.width    j = self.body[0] % self.width     # Update the head's position and check if it's out-of-bounds.    if direction == "U":      i -= 1      if i < 0:        return -1    if direction == "L":      j -= 1      if j < 0:        return -1    if direction == "R":      j += 1      if j == self.width:        return -1    if direction == "D":      i += 1      if i == self.height:        return -1     newHead = self.getId(i, j)     # 1. Eat food and increase the size by 1.    if self.k < len(self.food) and i == self.food[self.k][0] and j == self.food[self.k][1]:      self.lookup.add(newHead)      self.body.appendleft(newHead)      self.k += 1      self.score += 1      return self.score     # 2. new head != old tail and eat body!    if newHead != self.body[-1] and newHead in self.lookup:      return -1     # 3. normal case    # Remove the old tail first, then add new head because new head may be in    # old tail's position.    self.lookup.remove(self.body[-1])    self.lookup.add(newHead)    self.body.pop()    self.body.appendleft(newHead)     return self.score   def getId(self, i: int, j: int) -> int:    return i * self.width + j 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗