贪吃蛇移动核心可以使用链表来表示,那么移动的时候就只是调整结点
/**
* @param {Point[]} snake, the snake is an array of points
* @param {string} direction, 'left', 'right', 'up' or 'down'
* @param {Point} foodPosition, the food position in the grid
*/
function move(snake, direction, foodPosition) {
// 判断是不是吃到食物了
// 没有吃到的话需要丢弃掉尾巴,然后头部进行调整
// 吃到的话只有头需要调整
// 所以区别是是否要丢弃掉尾巴
// 更新后的头
const newHead = new Point(snake[0].x, snake[0].y)
if(direction === 'left') {
newHead.x -= 1
} else if(direction === 'right') {
newHead.x += 1
} else if(direction === 'up') {
newHead.y += 1
} else {
newHead.y -= 1
}
// 更新头部
snake.unshift(newHead)
// 是否吃了食物
const isEatFood = newHead.x === foodPosition.x && newHead.y === foodPosition.y
// 如果没吃食物,删除尾部
if (!isEatFood) {
snake.pop()
}
}