Snake
A project that was originally created as a game for developers to compete on writing a heuristic function to complete the game of snake in the most efficient way possible.
const adjacentes = (a, xMax, yMax) => [[a[0], a[1] - 1], [a[0] + 1, a[1]], [a[0], a[1] + 1], [a[0] - 1, a[1]]].filter(b => b[0] >= 0 && b[1] >= 0 && b[0] <= xMax && b[1] <= yMax);
const equals = ([x1, y1], [x2, y2]) => x1 === x2 && y1 === y2;
const includes = (a, b) => a.some((a) => equals(a, b));
const difference = (a, b) => a.filter((a) => !includes(b, a));
const shift = (a, b, collect) => b.concat(a).slice(0, b.length + (a.length - b.length + (collect ? 1 : 0)));
const tail = (a) => a[a.length - 1];
const search = (start, end, xMax, yMax, snake) => {
const queue = [start];
const paths = { [start]: [start] };
while (queue.length) {
const current = queue.shift();
const snakeShifted = shift(snake, paths[current] = paths[current] || [start]);
if (equals(current, end)) {
return paths[current];
}
for (const next of difference(adjacentes(current, xMax, yMax), snakeShifted)) {
if (!(next in paths)) {
queue.push(next);
paths[next] = [next].concat(paths[current]);
}
}
}
};
/**
* The heuristic function will be run on every cell, and should return a number. The number that is returned will be used to determine the path of the snake.
*
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
0 Points
0 Average
0 Score
Step Backward
Play
Pause
Step forward
Refresh values