:roclet: improve algorithm, add an intermediate phase to clean up residual cell from previous layer, before grabing the free ones
This commit is contained in:
12
packages/compute/__tests__/getPathTo.spec.ts
Normal file
12
packages/compute/__tests__/getPathTo.spec.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { createEmptyGrid } from "@snk/types/grid";
|
||||
import { getHeadX, getHeadY } from "@snk/types/snake";
|
||||
import { snake3 } from "@snk/types/__fixtures__/snake";
|
||||
import { getPathTo } from "../getPathTo";
|
||||
|
||||
it("should find it's way in vaccum", () => {
|
||||
const grid = createEmptyGrid(5, 0);
|
||||
|
||||
const path = getPathTo(grid, snake3, 5, -1)!;
|
||||
|
||||
expect([getHeadX(path[0]), getHeadY(path[0])]).toEqual([5, -1]);
|
||||
});
|
||||
131
packages/compute/cleanIntermediateLayer.ts
Normal file
131
packages/compute/cleanIntermediateLayer.ts
Normal file
@@ -0,0 +1,131 @@
|
||||
import { getColor, isEmpty, setColorEmpty } from "@snk/types/grid";
|
||||
import {
|
||||
getHeadX,
|
||||
getHeadY,
|
||||
getSnakeLength,
|
||||
nextSnake,
|
||||
} from "@snk/types/snake";
|
||||
import { getPathTo } from "./getPathTo";
|
||||
import { getBestTunnel, trimTunnelEnd, trimTunnelStart } from "./getBestTunnel";
|
||||
import type { Snake } from "@snk/types/snake";
|
||||
import type { Color, Grid } from "@snk/types/grid";
|
||||
import type { Point } from "@snk/types/point";
|
||||
|
||||
/**
|
||||
* - list the cells lesser than <color> that are reachable going through <color>
|
||||
* - for each cell of the list
|
||||
* compute the best tunnel to get to the cell and back to the outside ( best = less usage of <color> )
|
||||
* - for each tunnel*
|
||||
* make the snake go to the start of the tunnel from where it was, traverse the tunnel
|
||||
* repeat
|
||||
*
|
||||
* *sort the tunnel:
|
||||
* - first one to go is the tunnel with the longest line on less than <color>
|
||||
* - then the ones with the best ratio ( N of less than <color> ) / ( N of <color> )
|
||||
*/
|
||||
export const cleanIntermediateLayer = (
|
||||
grid: Grid,
|
||||
color: Color,
|
||||
snake0: Snake
|
||||
) => {
|
||||
const tunnels: Point[][] = [];
|
||||
const chain: Snake[] = [snake0];
|
||||
|
||||
for (let x = grid.width; x--; )
|
||||
for (let y = grid.height; y--; ) {
|
||||
const c = getColor(grid, x, y);
|
||||
|
||||
if (!isEmpty(c) && c < color) {
|
||||
const tunnel = getBestTunnel(grid, x, y, color, getSnakeLength(snake0));
|
||||
if (tunnel) tunnels.push(tunnel);
|
||||
}
|
||||
}
|
||||
|
||||
// find the best first tunnel
|
||||
let i = -1;
|
||||
for (let j = tunnels.length; j--; )
|
||||
if (
|
||||
i === -1 ||
|
||||
scoreFirst(grid, color, tunnels[i]) < scoreFirst(grid, color, tunnels[j])
|
||||
)
|
||||
i = j;
|
||||
|
||||
while (i >= 0) {
|
||||
const [tunnel] = tunnels.splice(i, 1);
|
||||
|
||||
// push to chain
|
||||
// 1\ the path to the start on the tunnel
|
||||
const path = getPathTo(grid, chain[0], tunnel[0].x, tunnel[0].y)!;
|
||||
chain.unshift(...path);
|
||||
// 2\ the path into the tunnel
|
||||
for (let i = 1; i < tunnel.length; i++) {
|
||||
const dx = tunnel[i].x - getHeadX(chain[0]);
|
||||
const dy = tunnel[i].y - getHeadY(chain[0]);
|
||||
const snake = nextSnake(chain[0], dx, dy);
|
||||
chain.unshift(snake);
|
||||
}
|
||||
|
||||
// mutate grid
|
||||
for (const { x, y } of tunnel) setColorEmpty(grid, x, y);
|
||||
|
||||
// remove the cell that we eat
|
||||
for (let j = tunnels.length; j--; ) {
|
||||
updateTunnel(grid, tunnels[j], tunnel);
|
||||
if (!tunnels[j].length) tunnels.splice(j, 1);
|
||||
}
|
||||
|
||||
// select the next one
|
||||
i = -1;
|
||||
for (let j = tunnels.length; j--; )
|
||||
if (
|
||||
i === -1 ||
|
||||
score(grid, color, tunnels[i]) < score(grid, color, tunnels[j])
|
||||
)
|
||||
i = j;
|
||||
}
|
||||
|
||||
return chain;
|
||||
};
|
||||
|
||||
const scoreFirst = (grid: Grid, color: Color, tunnel: Point[]) =>
|
||||
tunnel.findIndex(({ x, y }) => getColor(grid, x, y) === color);
|
||||
|
||||
const score = (grid: Grid, color: Color, tunnel: Point[]) => {
|
||||
let nColor = 0;
|
||||
let nLessColor = 0;
|
||||
|
||||
for (let i = 0; i < tunnel.length; i++) {
|
||||
const { x, y } = tunnel[i];
|
||||
|
||||
const j = tunnel.findIndex((u) => x === u.x && y === u.y);
|
||||
|
||||
if (i !== j) {
|
||||
const c = getColor(grid, x, y);
|
||||
if (c === color) nColor++;
|
||||
else if (!isEmpty(c)) nLessColor++;
|
||||
}
|
||||
}
|
||||
|
||||
return nLessColor / nColor;
|
||||
};
|
||||
|
||||
/**
|
||||
* assuming the grid change and the colors got deleted, update the tunnel
|
||||
*/
|
||||
const updateTunnel = (grid: Grid, tunnel: Point[], toDelete: Point[]) => {
|
||||
while (tunnel.length) {
|
||||
const { x, y } = tunnel[0];
|
||||
if (toDelete.some((p) => p.x === x && p.y === y)) {
|
||||
tunnel.shift();
|
||||
trimTunnelStart(grid, tunnel);
|
||||
} else break;
|
||||
}
|
||||
|
||||
while (tunnel.length) {
|
||||
const { x, y } = tunnel[tunnel.length - 1];
|
||||
if (toDelete.some((p) => p.x === x && p.y === y)) {
|
||||
tunnel.pop();
|
||||
trimTunnelEnd(grid, tunnel);
|
||||
} else break;
|
||||
}
|
||||
};
|
||||
@@ -1,30 +1,34 @@
|
||||
import { copyGrid, isEmpty } from "@snk/types/grid";
|
||||
import { copyGrid } from "@snk/types/grid";
|
||||
import { pruneLayer } from "./pruneLayer";
|
||||
import { cleanLayer } from "./cleanLayer-monobranch";
|
||||
import type { Snake } from "@snk/types/snake";
|
||||
import { getSnakeLength, Snake } from "@snk/types/snake";
|
||||
import { cleanIntermediateLayer } from "./cleanIntermediateLayer";
|
||||
import type { Color, Grid } from "@snk/types/grid";
|
||||
|
||||
export const getBestRoute = (grid0: Grid, snake0: Snake) => {
|
||||
const grid = copyGrid(grid0);
|
||||
const colors = extractColors(grid0);
|
||||
const snakeN = snake0.length / 2;
|
||||
const snakeN = getSnakeLength(snake0);
|
||||
|
||||
const chain: Snake[] = [snake0];
|
||||
|
||||
for (const color of colors) {
|
||||
const gridN = copyGrid(grid);
|
||||
|
||||
// clear the free colors
|
||||
const chunk = pruneLayer(grid, color, snakeN);
|
||||
const c = cleanLayer(gridN, chain[0], chunk);
|
||||
chain.unshift(...c);
|
||||
chain.unshift(...cleanLayer(gridN, chain[0], chunk));
|
||||
|
||||
// clear the remaining colors, allowing to eat color+1
|
||||
const nextColor = (color + 1) as Color;
|
||||
chain.unshift(...cleanIntermediateLayer(grid, nextColor, chain[0]));
|
||||
}
|
||||
|
||||
return chain.reverse().slice(1);
|
||||
};
|
||||
|
||||
const extractColors = (grid: Grid): Color[] => {
|
||||
const colors = new Set<Color>();
|
||||
grid.data.forEach((c: any) => {
|
||||
if (!isEmpty(c)) colors.add(c);
|
||||
});
|
||||
return Array.from(colors.keys()).sort();
|
||||
// @ts-ignore
|
||||
let maxColor = Math.max(...grid.data);
|
||||
return Array.from({ length: maxColor }, (_, i) => (i + 1) as Color);
|
||||
};
|
||||
|
||||
159
packages/compute/getBestTunnel.ts
Normal file
159
packages/compute/getBestTunnel.ts
Normal file
@@ -0,0 +1,159 @@
|
||||
import {
|
||||
copyGrid,
|
||||
getColor,
|
||||
isEmpty,
|
||||
isInside,
|
||||
setColorEmpty,
|
||||
} from "@snk/types/grid";
|
||||
import { around4 } from "@snk/types/point";
|
||||
import { sortPush } from "./utils/sortPush";
|
||||
import {
|
||||
createSnakeFromCells,
|
||||
getHeadX,
|
||||
getHeadY,
|
||||
nextSnake,
|
||||
snakeEquals,
|
||||
snakeWillSelfCollide,
|
||||
} from "@snk/types/snake";
|
||||
import type { Snake } from "@snk/types/snake";
|
||||
import type { Color, Grid } from "@snk/types/grid";
|
||||
import type { Point } from "@snk/types/point";
|
||||
|
||||
type M = {
|
||||
snake: Snake;
|
||||
grid: Grid;
|
||||
parent: M | null;
|
||||
w: number;
|
||||
h: number;
|
||||
f: number;
|
||||
};
|
||||
|
||||
const unwrap = (m: M | null): Snake[] =>
|
||||
m ? [m.snake, ...unwrap(m.parent)] : [];
|
||||
|
||||
/**
|
||||
* returns the path to reach the outside which contains the least color cell
|
||||
*/
|
||||
const getSnakeEscapePath = (grid0: Grid, snake0: Snake, color: Color) => {
|
||||
const openList: M[] = [
|
||||
{ snake: snake0, grid: grid0, w: 0, h: 0, f: 0, parent: null },
|
||||
];
|
||||
const closeList: Snake[] = [];
|
||||
|
||||
while (openList.length) {
|
||||
const o = openList.shift()!;
|
||||
|
||||
for (const a of around4) {
|
||||
if (!snakeWillSelfCollide(o.snake, a.x, a.y)) {
|
||||
const y = getHeadY(o.snake) + a.y;
|
||||
const x = getHeadX(o.snake) + a.x;
|
||||
|
||||
if (!isInside(grid0, x, y)) {
|
||||
// unwrap and return
|
||||
const points: Point[] = [];
|
||||
|
||||
points.push({ x, y });
|
||||
let e: M["parent"] = o;
|
||||
while (e) {
|
||||
points.unshift({
|
||||
y: getHeadY(e.snake),
|
||||
x: getHeadX(e.snake),
|
||||
});
|
||||
e = e.parent;
|
||||
}
|
||||
|
||||
return points;
|
||||
}
|
||||
|
||||
const u = getColor(grid0, x, y);
|
||||
|
||||
if (isEmpty(u) || u <= color) {
|
||||
const snake = nextSnake(o.snake, a.x, a.y);
|
||||
|
||||
if (!closeList.some((s0) => snakeEquals(s0, snake))) {
|
||||
let grid = o.grid;
|
||||
if (!isEmpty(u)) {
|
||||
grid = copyGrid(grid);
|
||||
setColorEmpty(grid, x, y);
|
||||
}
|
||||
|
||||
const h = Math.abs(grid.height / 2 - y);
|
||||
const w = o.w + (u === color ? 1 : 0);
|
||||
const f = w * 1000 - h;
|
||||
sortPush(
|
||||
openList,
|
||||
{ snake, grid, parent: o, h, w, f },
|
||||
(a, b) => a.f - b.f
|
||||
);
|
||||
closeList.push(snake);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* compute the best tunnel to get to the cell and back to the outside ( best = less usage of <color> )
|
||||
*/
|
||||
export const getBestTunnel = (
|
||||
grid: Grid,
|
||||
x: number,
|
||||
y: number,
|
||||
color: Color,
|
||||
snakeN: number
|
||||
) => {
|
||||
const c = { x, y };
|
||||
const snake = createSnakeFromCells(Array.from({ length: snakeN }, () => c));
|
||||
|
||||
const one = getSnakeEscapePath(grid, snake, color);
|
||||
|
||||
if (!one) return null;
|
||||
|
||||
// get the position of the snake if it was going to leave the x,y cell
|
||||
const snakeICells = one.slice(0, snakeN);
|
||||
while (snakeICells.length < snakeN)
|
||||
snakeICells.push(snakeICells[snakeICells.length - 1]);
|
||||
const snakeI = createSnakeFromCells(snakeICells);
|
||||
|
||||
// remove from the grid the colors that one eat
|
||||
const gridI = copyGrid(grid);
|
||||
for (const { x, y } of one) setColorEmpty(gridI, x, y);
|
||||
|
||||
const two = getSnakeEscapePath(gridI, snakeI, color);
|
||||
|
||||
if (!two) return null;
|
||||
|
||||
one.reverse();
|
||||
one.pop();
|
||||
|
||||
trimTunnelStart(grid, one);
|
||||
trimTunnelEnd(grid, two);
|
||||
one.push(...two);
|
||||
|
||||
return one;
|
||||
};
|
||||
|
||||
/**
|
||||
* remove empty cell from start
|
||||
*/
|
||||
export const trimTunnelStart = (grid: Grid, tunnel: Point[]) => {
|
||||
while (tunnel.length) {
|
||||
const { x, y } = tunnel[0];
|
||||
if (!isInside(grid, x, y) || isEmpty(getColor(grid, x, y))) tunnel.shift();
|
||||
else break;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* remove empty cell from end
|
||||
*/
|
||||
export const trimTunnelEnd = (grid: Grid, tunnel: Point[]) => {
|
||||
while (tunnel.length) {
|
||||
const { x, y } = tunnel[tunnel.length - 1];
|
||||
if (!isInside(grid, x, y) || isEmpty(getColor(grid, x, y))) tunnel.pop();
|
||||
else break;
|
||||
}
|
||||
};
|
||||
66
packages/compute/getPathTo.ts
Normal file
66
packages/compute/getPathTo.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import { isInsideLarge, getColor, isInside, isEmpty } from "@snk/types/grid";
|
||||
import { around4 } from "@snk/types/point";
|
||||
import {
|
||||
getHeadX,
|
||||
getHeadY,
|
||||
nextSnake,
|
||||
snakeEquals,
|
||||
snakeWillSelfCollide,
|
||||
} from "@snk/types/snake";
|
||||
import { sortPush } from "./utils/sortPush";
|
||||
import type { Snake } from "@snk/types/snake";
|
||||
import type { Grid } from "@snk/types/grid";
|
||||
|
||||
type M = { parent: M | null; snake: Snake; w: number; h: number; f: number };
|
||||
|
||||
/**
|
||||
* starting from snake0, get to the cell x,y
|
||||
* return the snake chain (reversed)
|
||||
*/
|
||||
export const getPathTo = (grid: Grid, snake0: Snake, x: number, y: number) => {
|
||||
const openList: M[] = [{ snake: snake0, w: 0 } as any];
|
||||
const closeList: Snake[] = [];
|
||||
|
||||
while (openList.length) {
|
||||
const c = openList.shift()!;
|
||||
|
||||
const cx = getHeadX(c.snake);
|
||||
const cy = getHeadY(c.snake);
|
||||
|
||||
for (let i = 0; i < around4.length; i++) {
|
||||
const { x: dx, y: dy } = around4[i];
|
||||
|
||||
const nx = cx + dx;
|
||||
const ny = cy + dy;
|
||||
|
||||
if (nx === x && ny === y) {
|
||||
// unwrap
|
||||
const path = [nextSnake(c.snake, dx, dy)];
|
||||
let e: M["parent"] = c;
|
||||
while (e.parent) {
|
||||
path.push(e.snake);
|
||||
e = e.parent;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
if (
|
||||
isInsideLarge(grid, 2, nx, ny) &&
|
||||
!snakeWillSelfCollide(c.snake, dx, dy) &&
|
||||
(!isInside(grid, nx, ny) || isEmpty(getColor(grid, nx, ny)))
|
||||
) {
|
||||
const nsnake = nextSnake(c.snake, dx, dy);
|
||||
|
||||
if (!closeList.some((s) => snakeEquals(nsnake, s))) {
|
||||
const w = c.w + 1;
|
||||
const h = Math.abs(nx - x) + Math.abs(ny - y);
|
||||
const f = w + h;
|
||||
const o = { snake: nsnake, parent: c, w, h, f };
|
||||
|
||||
sortPush(openList, o, (a, b) => a.f - b.f);
|
||||
closeList.push(nsnake);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -15,8 +15,7 @@ import {
|
||||
|
||||
type M = Point & { parent: M | null; h: number };
|
||||
|
||||
const unwrap = (grid: Grid, m: M | null): Point[] =>
|
||||
m ? [...unwrap(grid, m.parent), m] : [];
|
||||
const unwrap = (m: M | null): Point[] => (m ? [...unwrap(m.parent), m] : []);
|
||||
|
||||
const getEscapePath = (grid: Grid, x: number, y: number, color: Color) => {
|
||||
const openList: M[] = [{ x, y, h: 0, parent: null }];
|
||||
@@ -25,14 +24,13 @@ const getEscapePath = (grid: Grid, x: number, y: number, color: Color) => {
|
||||
while (openList.length) {
|
||||
const c = openList.shift()!;
|
||||
|
||||
if (c.y === -1 || c.y === grid.height) return unwrap(grid, c);
|
||||
if (c.y === -1 || c.y === grid.height) return unwrap(c);
|
||||
|
||||
for (const a of around4) {
|
||||
const x = c.x + a.x;
|
||||
const y = c.y + a.y;
|
||||
|
||||
if (!isInside(grid, x, y))
|
||||
return unwrap(grid, { x, y, parent: c } as any);
|
||||
if (!isInside(grid, x, y)) return unwrap({ x, y, parent: c } as any);
|
||||
|
||||
const u = getColor(grid, x, y);
|
||||
|
||||
@@ -63,10 +61,10 @@ const snakeCanEscape = (grid: Grid, snake: Snake, color: Color) => {
|
||||
const s = openList.shift()!;
|
||||
|
||||
for (const a of around4) {
|
||||
const x = getHeadX(s) + a.x;
|
||||
const y = getHeadY(s) + a.y;
|
||||
|
||||
if (!snakeWillSelfCollide(s, a.x, a.y)) {
|
||||
const x = getHeadX(s) + a.x;
|
||||
const y = getHeadY(s) + a.y;
|
||||
|
||||
if (!isInside(grid, x, y)) return true;
|
||||
|
||||
const u = getColor(grid, x, y);
|
||||
|
||||
Reference in New Issue
Block a user