Design Snake Game

Problem: Design Snake Game

class SnakeGame(object):

    def __init__(self, width,height,food):
        """
        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].
        :type width: int
        :type height: int
        :type food: List[List[int]]
        """
        self.food = food
        self.width = width
        self.height = height
        self.score = 0
        self.snake = [[0, 0]]
        self.directions = {'U':(-1,0), 'L':(0,-1), 'R':(0,1), 'D':(1,0)}

    def move(self, direction):
        """
        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.
        :type direction: str
        :rtype: int
        """
        mx, my = self.directions[direction]
        hx, hy = self.snake[0]
        if len(self.food) > 0 and self.food[0] == [hx+mx, hy+my]:
            self.score += 1
            self.snake = [[hx+mx, hy+my]] + self.snake
            self.food = self.food[1:]
        else:
            if hx+mx < 0 or hx+mx >= self.height or hy+my < 0 or hy+my >= self.width or [hx+mx, hy+my] in self.snake[:-1]:
                return -1
            self.snake = [[hx+mx, hy+my]] + self.snake[:-1]
        return self.score

# Your SnakeGame object will be instantiated and called as such:
# obj = SnakeGame(width, height, food)
# param_1 = obj.move(direction)

results matching ""

    No results matching ""