示例自动移动代码
function autoMoveSnake() {
const head = snake[0];
// 1. 朝食物移动
if (food.x > head.x && velocity.x === 0) {
velocity = { x: 1, y: 0 }; // 向右
} else if (food.x < head.x && velocity.x === 0) {
velocity = { x: -1, y: 0 }; // 向左
} else if (food.y > head.y && velocity.y === 0) {
velocity = { x: 0, y: 1 }; // 向下
} else if (food.y < head.y && velocity.y === 0) {
velocity = { x: 0, y: -1 }; // 向上
}
// 2. 规避碰撞
const nextX = head.x + velocity.x;
const nextY = head.y + velocity.y;
if (
nextX < 0 || nextX >= tileCount || nextY < 0 || nextY >= tileCount ||
snake.slice(1).some(segment => segment.x === nextX && segment.y === nextY)
) {
if (velocity.x !== 0) {
if (head.y > 0 && !snake.some(segment => segment.x === head.x && segment.y === head.y - 1)) {
velocity = { x: 0, y: -1 };
} else {
velocity = { x: 0, y: 1 };
}
} else if (velocity.y !== 0) {
if (head.x > 0 && !snake.some(segment => segment.x === head.x - 1 && segment.y === head.y)) {
velocity = { x: -1, y: 0 };
} else {
velocity = { x: 1, y: 0 };
}
}
}
}
setInterval(autoMoveSnake, 100);