Design Snake Game
Description
null
Solution(javascript)
/**
* 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].
* @param {number} width
* @param {number} height
* @param {number[][]} food
*/
const SnakeGame = function (width, height, food) {
this.body = [[0, 0]]
this.foodIndex = 0
this.width = width
this.height = height
this.score = 0
this.food = food
}
/**
* 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.
* @param {string} direction
* @return {number}
*/
SnakeGame.prototype.move = function (direction) {
let [row, column] = this.body[this.body.length - 1]
if (direction === 'U') { // 需要考虑上下移动么
row -= 1
} else if (direction === 'D') {
row += 1
} else if (direction === 'R') {
column += 1
} else {
column -= 1
}
if (row < 0 || row > this.height - 1 || column < 0 || column > this.width - 1) {
return -1
}
const index = this.body.findIndex(([x, y]) => x === row && y === column)
if (index > 0) {
return -1
}
this.body.push([row, column])
if (this.food[this.foodIndex]
&& this.food[this.foodIndex][0] === row
&& this.food[this.foodIndex][1] === column) {
this.foodIndex++
return ++this.score
}
this.body.shift()
return this.score
}
/**
* Your SnakeGame object will be instantiated and called as such:
* var obj = new SnakeGame(width, height, food)
* var param_1 = obj.move(direction)
*/