← 返回 amazon 的题目列表Design and Implement a Simplified Snake Game on Grid
类型:online_judge
amazon
Please design a simplified Snake Game. The game is played on a n x n grid, and the snake starts from the top-left corner (0, 0) with an initial length of 1, heading right. Random pieces of food are placed on the grid. When the snake eats the food, its length increases, and the food disappears. The snake cannot collide with the wall or itself, otherwise, the game ends. Implement the following functionalities:
move(direction: str) -> int: Takes a direction ('U', 'L', 'R', 'D') as input representing the snake's movement direction and returns the current score (i.e., the length of the snake).
Input
Each call to the move function takes a string representing the direction.
Output
An integer represents the current length of the snake.
Initial Conditions
The grid size n is given at the game initialization, and the food positions are predefined.
Initially, the snake's length is 1, starting at position (0, 0).
Test Cases
n = 3
food = [[1, 1], [2, 2], [0, 1]]
game = SnakeGame(n, food)
print(game.move('R')) # Returns 1, snake moves to (0, 1) and eats food, length becomes 2
print(game.move('D')) # Returns 2, snake moves to (1, 1)
print(game.move('R')) # Returns 2, snake moves to (1, 2)
print(game.move('U')) # Returns 2, snake moves to (0, 2), no food
print(game.move('L')) # Returns 3, snake moves to (0, 1), and eats food, length becomes 3
Data Size
The range of n is [3, 100].
The number of foods is between [0, 10^3].
Example
Input
3
[[1, 1], [2, 2], [0, 1]]
R