🚀 imrpove algorithm

This commit is contained in:
platane
2020-10-31 17:23:19 +01:00
parent d81ecec836
commit b595e7de53
22 changed files with 707 additions and 451 deletions

View File

@@ -11,7 +11,6 @@ export const generateContributionSnake = async (userName: string) => {
const grid0 = userContributionToGrid(cells);
const snake0 = createSnakeFromCells([
{ x: 4, y: -1 },
{ x: 3, y: -1 },
{ x: 2, y: -1 },
{ x: 1, y: -1 },

View File

@@ -1,34 +1,40 @@
import { getBestRoute } from "../getBestRoute";
import { snake3 } from "@snk/types/__fixtures__/snake";
import { snake3, snake4 } from "@snk/types/__fixtures__/snake";
import {
getHeadX,
getHeadY,
getSnakeLength,
Snake,
snakeWillSelfCollide,
} from "@snk/types/snake";
import { createFromSeed } from "@snk/types/__fixtures__/createFromSeed";
const n = 1000;
const width = 5;
const height = 5;
it(`should find solution for ${n} ${width}x${height} generated grids`, () => {
const results = Array.from({ length: n }, (_, seed) => {
const grid = createFromSeed(seed, width, height);
try {
const chain = getBestRoute(grid, snake3);
for (const { width, height, snake } of [
{ width: 5, height: 5, snake: snake3 },
{ width: 5, height: 5, snake: snake4 },
])
it(`should find solution for ${n} ${width}x${height} generated grids for ${getSnakeLength(
snake
)} length snake`, () => {
const results = Array.from({ length: n }, (_, seed) => {
const grid = createFromSeed(seed, width, height);
assertValidPath(chain);
try {
const chain = getBestRoute(grid, snake);
return { seed };
} catch (error) {
return { seed, error };
}
assertValidPath(chain);
return { seed };
} catch (error) {
return { seed, error };
}
});
expect(results.filter((x) => x.error)).toEqual([]);
});
expect(results.filter((x) => x.error)).toEqual([]);
});
const assertValidPath = (chain: Snake[]) => {
for (let i = 0; i < chain.length - 1; i++) {
const dx = getHeadX(chain[i + 1]) - getHeadX(chain[i]);

View File

@@ -1,147 +0,0 @@
import { Color, getColor, isEmpty, setColorEmpty } from "@snk/types/grid";
import {
getHeadX,
getHeadY,
getSnakeLength,
nextSnake,
} from "@snk/types/snake";
import type { Snake } from "@snk/types/snake";
import type { Grid } from "@snk/types/grid";
import type { Point } from "@snk/types/point";
import { getBestTunnel, trimTunnelEnd, trimTunnelStart } from "./getBestTunnel";
import { getPathTo } from "./getPathTo";
import { getTunnels } from "./getTunnels";
/**
* eat all the cell for which the color is smaller or equals to color and are reachable without going though cells with color+1 or higher
* attempt to eat the smaller color first
*/
export const cleanColoredLayer = (grid: Grid, snake0: Snake, color: Color) => {
const chain: Snake[] = [snake0];
const snakeN = getSnakeLength(snake0);
const tunnels = getTunnels(grid, getSnakeLength(snake0), color)
.map((tunnel) => ({ tunnel, f: tunnelScore(grid, color, tunnel) }))
.sort((a, b) => a.f - b.f);
while (tunnels.length) {
// get the best candidates
const candidates = tunnels.filter((a, _, [a0]) => a.f === a0.f);
// get the closest one
{
const x = getHeadX(chain[0]);
const y = getHeadY(chain[0]);
candidates.sort(
({ tunnel: [a] }, { tunnel: [b] }) =>
distanceSq(x, y, a.x, a.y) - distanceSq(x, y, b.x, b.y)
);
}
// pick tunnel and recompute it
// it might not be relevant since the grid changes
// in some edge case, it could lead to the snake reaching the first cell from the initial exit side
// causing it to self collide when on it's way through the tunnel
const { tunnel: tunnelCandidate } = candidates[0];
const tunnel = getBestTunnel(
grid,
tunnelCandidate[0].x,
tunnelCandidate[0].y,
color,
snakeN
)!;
// move to the start of the tunnel
chain.unshift(...getPathTo(grid, chain[0], tunnel[0].x, tunnel[0].y)!);
// move into the tunnel
chain.unshift(...getTunnelPath(chain[0], tunnel));
// update grid
for (const { x, y } of tunnel) setColorEmpty(grid, x, y);
// update other tunnels
// eventually remove the ones made empty
for (let i = tunnels.length; i--; ) {
updateTunnel(grid, tunnels[i].tunnel, tunnel);
if (tunnels[i].tunnel.length === 0) tunnels.splice(i, 1);
else tunnels[i].f = tunnelScore(grid, color, tunnels[i].tunnel);
}
tunnels.sort((a, b) => a.f - b.f);
}
return chain.slice(0, -1);
};
/**
* get the score of the tunnel
* prioritize tunnel with maximum color smaller than <color> and with minimum <color>
* with some tweaks
*/
const tunnelScore = (grid: Grid, color: Color, tunnel: Point[]) => {
let nColor = 0;
let nLess = 0;
let nLessLead = -1;
for (const { x, y } of tunnel) {
const c = getColor(grid, x, y);
if (!isEmpty(c)) {
if (c === color) {
nColor++;
if (nLessLead === -1) nLessLead = nLess;
} else nLess += color - c;
}
}
if (nLess === 0) return 999999;
return -nLessLead * 100 + (1 - nLess / nColor);
};
const distanceSq = (ax: number, ay: number, bx: number, by: number) =>
(ax - bx) ** 2 + (ay - by) ** 2;
/**
* get the sequence of snake to cross the tunnel
*/
const getTunnelPath = (snake0: Snake, tunnel: Point[]) => {
const chain: Snake[] = [];
let snake = snake0;
for (let i = 1; i < tunnel.length; i++) {
const dx = tunnel[i].x - getHeadX(snake);
const dy = tunnel[i].y - getHeadY(snake);
snake = nextSnake(snake, dx, dy);
chain.unshift(snake);
}
return chain;
};
/**
* assuming the grid change and the colors got deleted, update the tunnel
*/
const updateTunnel = (grid: Grid, tunnel: Point[], toDelete: Point[]) => {
trimTunnelStart(grid, tunnel);
trimTunnelEnd(grid, tunnel);
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;
}
};

View File

@@ -0,0 +1,130 @@
import {
getColor,
isEmpty,
isInside,
isInsideLarge,
setColorEmpty,
} from "@snk/types/grid";
import {
getHeadX,
getHeadY,
getSnakeLength,
nextSnake,
snakeEquals,
snakeWillSelfCollide,
} from "@snk/types/snake";
import { around4, Point } from "@snk/types/point";
import { getBestTunnel } from "./getBestTunnel";
import { fillOutside } from "./outside";
import type { Outside } from "./outside";
import type { Snake } from "@snk/types/snake";
import type { Color, Empty, Grid } from "@snk/types/grid";
export const clearCleanColoredLayer = (
grid: Grid,
outside: Outside,
snake0: Snake,
color: Color
) => {
const snakeN = getSnakeLength(snake0);
const points = getTunnellablePoints(grid, outside, snakeN, color);
const chain: Snake[] = [snake0];
while (points.length) {
const path = getPathToNextPoint(grid, chain[0], color, points)!;
path.pop();
for (const snake of path)
setEmptySafe(grid, getHeadX(snake), getHeadY(snake));
chain.unshift(...path);
}
fillOutside(outside, grid);
chain.pop();
return chain;
};
type M = { snake: Snake; parent: M | null };
const unwrap = (m: M | null): Snake[] =>
!m ? [] : [m.snake, ...unwrap(m.parent)];
const getPathToNextPoint = (
grid: Grid,
snake0: Snake,
color: Color,
points: Point[]
) => {
const closeList: Snake[] = [];
const openList: M[] = [{ snake: snake0 } as any];
while (openList.length) {
const o = openList.shift()!;
const x = getHeadX(o.snake);
const y = getHeadY(o.snake);
const i = points.findIndex((p) => p.x === x && p.y === y);
if (i >= 0) {
points.splice(i, 1);
return unwrap(o);
}
for (const { x: dx, y: dy } of around4) {
if (
isInsideLarge(grid, 2, x + dx, y + dy) &&
!snakeWillSelfCollide(o.snake, dx, dy) &&
getColorSafe(grid, x + dx, y + dy) <= color
) {
const snake = nextSnake(o.snake, dx, dy);
if (!closeList.some((s0) => snakeEquals(s0, snake))) {
closeList.push(snake);
openList.push({ snake, parent: o });
}
}
}
}
};
/**
* get all cells that are tunnellable
*/
export const getTunnellablePoints = (
grid: Grid,
outside: Outside,
snakeN: number,
color: Color
) => {
const points: Point[] = [];
for (let x = grid.width; x--; )
for (let y = grid.height; y--; ) {
const c = getColor(grid, x, y);
if (
!isEmpty(c) &&
c <= color &&
!points.some((p) => p.x === x && p.y === y)
) {
const tunnel = getBestTunnel(grid, outside, x, y, color, snakeN);
if (tunnel)
for (const p of tunnel)
if (!isEmptySafe(grid, p.x, p.y)) points.push(p);
}
}
return points;
};
const getColorSafe = (grid: Grid, x: number, y: number) =>
isInside(grid, x, y) ? getColor(grid, x, y) : (0 as Empty);
const setEmptySafe = (grid: Grid, x: number, y: number) => {
if (isInside(grid, x, y)) setColorEmpty(grid, x, y);
};
const isEmptySafe = (grid: Grid, x: number, y: number) =>
!isInside(grid, x, y) && isEmpty(getColor(grid, x, y));

View File

@@ -0,0 +1,152 @@
import {
Empty,
getColor,
isEmpty,
isInside,
setColorEmpty,
} from "@snk/types/grid";
import { getHeadX, getHeadY, getSnakeLength } from "@snk/types/snake";
import { getBestTunnel } from "./getBestTunnel";
import { fillOutside, Outside } from "./outside";
import { getTunnelPath } from "./tunnel";
import { getPathTo } from "./getPathTo";
import type { Snake } from "@snk/types/snake";
import type { Color, Grid } from "@snk/types/grid";
import type { Point } from "@snk/types/point";
type T = Point & { tunnel: Point[]; priority: number };
export const clearResidualColoredLayer = (
grid: Grid,
outside: Outside,
snake0: Snake,
color: Color
) => {
const snakeN = getSnakeLength(snake0);
const tunnels = getTunnellablePoints(grid, outside, snakeN, color);
// sort
tunnels.sort((a, b) => a.priority - b.priority);
const chain: Snake[] = [snake0];
while (tunnels.length) {
// get the best next tunnel
let t = getNextTunnel(tunnels, chain[0]);
// goes to the start of the tunnel
chain.unshift(...getPathTo(grid, chain[0], t[0].x, t[0].y)!);
// goes to the end of the tunnel
chain.unshift(...getTunnelPath(chain[0], t));
// update grid
for (const { x, y } of t) setEmptySafe(grid, x, y);
// update outside
fillOutside(outside, grid);
// update tunnels
for (let i = tunnels.length; i--; )
if (isEmpty(getColor(grid, tunnels[i].x, tunnels[i].y)))
tunnels.splice(i, 1);
else {
const t = tunnels[i];
const tunnel = getBestTunnel(grid, outside, t.x, t.y, color, snakeN);
if (!tunnel) tunnels.splice(i, 1);
else {
t.tunnel = tunnel;
t.priority = getPriority(grid, color, tunnel);
}
}
// re-sort
tunnels.sort((a, b) => a.priority - b.priority);
}
chain.pop();
return chain;
};
const getNextTunnel = (ts: T[], snake: Snake) => {
let minDistance = Infinity;
let closestTunnel: Point[] | null = null;
const x = getHeadX(snake);
const y = getHeadY(snake);
const priority = ts[0].priority;
for (let i = 0; ts[i] && ts[i].priority <= priority; i++) {
const t = ts[i].tunnel;
const d = distanceSq(t[0].x, t[0].y, x, y);
if (d < minDistance) {
minDistance = d;
closestTunnel = t;
}
}
return closestTunnel!;
};
/**
* get all the tunnels for all the cells accessible
*/
export const getTunnellablePoints = (
grid: Grid,
outside: Outside,
snakeN: number,
color: Color
) => {
const points: T[] = [];
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, outside, x, y, color, snakeN);
if (tunnel) {
const priority = getPriority(grid, color, tunnel);
points.push({ x, y, priority, tunnel });
}
}
}
return points;
};
/**
* get the score of the tunnel
* prioritize tunnel with maximum color smaller than <color> and with minimum <color>
* with some tweaks
*/
export const getPriority = (grid: Grid, color: Color, tunnel: Point[]) => {
let nColor = 0;
let nLess = 0;
for (let i = 0; i < tunnel.length; i++) {
const { x, y } = tunnel[i];
const c = getColorSafe(grid, x, y);
if (!isEmpty(c) && i === tunnel.findIndex((p) => p.x === x && p.y === y)) {
if (c === color) nColor += 1;
else nLess += color - c;
}
}
if (nColor === 0) return 99999;
return nLess / nColor;
};
const distanceSq = (ax: number, ay: number, bx: number, by: number) =>
(ax - bx) ** 2 + (ay - by) ** 2;
const getColorSafe = (grid: Grid, x: number, y: number) =>
isInside(grid, x, y) ? getColor(grid, x, y) : (0 as Empty);
const setEmptySafe = (grid: Grid, x: number, y: number) => {
if (isInside(grid, x, y)) setColorEmpty(grid, x, y);
};

View File

@@ -1,14 +1,22 @@
import { Color, copyGrid } from "@snk/types/grid";
import type { Grid } from "@snk/types/grid";
import { cleanColoredLayer } from "./cleanColoredLayer";
import { copyGrid } from "@snk/types/grid";
import { createOutside } from "./outside";
import { clearResidualColoredLayer } from "./clearResidualColoredLayer";
import { clearCleanColoredLayer } from "./clearCleanColoredLayer";
import type { Color, Grid } from "@snk/types/grid";
import type { Snake } from "@snk/types/snake";
export const getBestRoute = (grid0: Grid, snake0: Snake) => {
const grid = copyGrid(grid0);
const outside = createOutside(grid);
const chain: Snake[] = [snake0];
for (const color of extractColors(grid))
chain.unshift(...cleanColoredLayer(grid, chain[0], color));
for (const color of extractColors(grid)) {
if (color > 1)
chain.unshift(
...clearResidualColoredLayer(grid, outside, chain[0], color)
);
chain.unshift(...clearCleanColoredLayer(grid, outside, chain[0], color));
}
return chain.reverse();
};

View File

@@ -1,10 +1,4 @@
import {
copyGrid,
getColor,
isEmpty,
isInside,
setColorEmpty,
} from "@snk/types/grid";
import { copyGrid, getColor, isInside, setColorEmpty } from "@snk/types/grid";
import { around4 } from "@snk/types/point";
import { sortPush } from "./utils/sortPush";
import {
@@ -15,75 +9,57 @@ import {
snakeEquals,
snakeWillSelfCollide,
} from "@snk/types/snake";
import { isOutside } from "./outside";
import { trimTunnelEnd, trimTunnelStart } from "./tunnel";
import type { Outside } from "./outside";
import type { Snake } from "@snk/types/snake";
import type { Color, Grid } from "@snk/types/grid";
import type { Empty, 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 getColorSafe = (grid: Grid, x: number, y: number) =>
isInside(grid, x, y) ? getColor(grid, x, y) : (0 as Empty);
const setEmptySafe = (grid: Grid, x: number, y: number) => {
if (isInside(grid, x, y)) setColorEmpty(grid, x, y);
};
type M = { snake: Snake; parent: M | null; w: number };
const unwrap = (m: M | null): Point[] =>
!m
? []
: [...unwrap(m.parent), { x: getHeadX(m.snake), y: getHeadY(m.snake) }];
/**
* 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 getSnakeEscapePath = (
grid: Grid,
outside: Outside,
snake0: Snake,
color: Color
) => {
const openList: M[] = [{ snake: snake0, w: 0 } as any];
const closeList: Snake[] = [];
while (openList.length) {
while (openList[0]) {
const o = openList.shift()!;
const x = getHeadX(o.snake);
const y = getHeadY(o.snake);
if (isOutside(outside, x, y)) return unwrap(o);
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;
const c = getColorSafe(grid, x + a.x, y + a.y);
if (!isInside(grid0, x, y)) {
// unwrap and return
const points: Point[] = [];
if (c <= color && !snakeWillSelfCollide(o.snake, a.x, a.y)) {
const snake = nextSnake(o.snake, a.x, a.y);
points.push({ x, y });
let e: M["parent"] = o;
while (e) {
points.unshift({
x: getHeadX(e.snake),
y: getHeadY(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);
}
if (!closeList.some((s0) => snakeEquals(s0, snake))) {
const w = o.w + 1 + +(c === color) * 1000;
sortPush(openList, { snake, w, parent: o }, (a, b) => a.w - b.w);
closeList.push(snake);
}
}
}
@@ -99,15 +75,16 @@ const getSnakeEscapePath = (grid0: Grid, snake0: Snake, color: Color) => {
*/
export const getBestTunnel = (
grid: Grid,
outside: Outside,
x: number,
y: number,
color: Color,
snakeN: number
) => {
const c = { x, y };
const snake = createSnakeFromCells(Array.from({ length: snakeN }, () => c));
const snake0 = createSnakeFromCells(Array.from({ length: snakeN }, () => c));
const one = getSnakeEscapePath(grid, snake, color);
const one = getSnakeEscapePath(grid, outside, snake0, color);
if (!one) return null;
@@ -119,46 +96,18 @@ export const getBestTunnel = (
// remove from the grid the colors that one eat
const gridI = copyGrid(grid);
for (const { x, y } of one)
if (isInside(grid, x, y)) setColorEmpty(gridI, x, y);
for (const { x, y } of one) setEmptySafe(gridI, x, y);
const two = getSnakeEscapePath(gridI, snakeI, color);
const two = getSnakeEscapePath(gridI, outside, snakeI, color);
if (!two) return null;
one.shift();
one.reverse();
one.push(...two);
trimTunnelStart(grid, one);
trimTunnelEnd(grid, one);
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 i = tunnel.length - 1;
const { x, y } = tunnel[i];
if (
!isInside(grid, x, y) ||
isEmpty(getColor(grid, x, y)) ||
tunnel.findIndex((p) => p.x === x && p.y === y) < i
)
tunnel.pop();
else break;
}
};

View File

@@ -1,21 +0,0 @@
import { Color, getColor, isEmpty } from "@snk/types/grid";
import type { Grid } from "@snk/types/grid";
import type { Point } from "@snk/types/point";
import { getBestTunnel } from "./getBestTunnel";
/**
* get all the tunnels for all the cells accessible
*/
export const getTunnels = (grid: Grid, snakeN: number, color: Color) => {
const tunnels: Point[][] = [];
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, snakeN);
if (tunnel) tunnels.push(tunnel);
}
}
return tunnels;
};

View File

@@ -0,0 +1,48 @@
import {
createEmptyGrid,
getColor,
isEmpty,
isInside,
setColor,
setColorEmpty,
} from "@snk/types/grid";
import { around4 } from "@snk/types/point";
import type { Color, Grid } from "@snk/types/grid";
export type Outside = Grid & { __outside: true };
export const createOutside = (grid: Grid, color: Color = 0 as Color) => {
const outside = createEmptyGrid(grid.width, grid.height) as Outside;
for (let x = outside.width; x--; )
for (let y = outside.height; y--; ) setColor(outside, x, y, 1 as Color);
fillOutside(outside, grid, color);
return outside;
};
export const fillOutside = (
outside: Outside,
grid: Grid,
color: Color = 0 as Color
) => {
let changed = true;
while (changed) {
changed = false;
for (let x = outside.width; x--; )
for (let y = outside.height; y--; )
if (
getColor(grid, x, y) <= color &&
!isOutside(outside, x, y) &&
around4.some((a) => isOutside(outside, x + a.x, y + a.y))
) {
changed = true;
setColorEmpty(outside, x, y);
}
}
return outside;
};
export const isOutside = (outside: Outside, x: number, y: number) =>
!isInside(outside, x, y) || isEmpty(getColor(outside, x, y));

View File

@@ -0,0 +1,81 @@
import { getColor, isEmpty, isInside } from "@snk/types/grid";
import { getHeadX, getHeadY, nextSnake } from "@snk/types/snake";
import type { Snake } from "@snk/types/snake";
import type { Grid } from "@snk/types/grid";
import type { Point } from "@snk/types/point";
/**
* get the sequence of snake to cross the tunnel
*/
export const getTunnelPath = (snake0: Snake, tunnel: Point[]) => {
const chain: Snake[] = [];
let snake = snake0;
for (let i = 1; i < tunnel.length; i++) {
const dx = tunnel[i].x - getHeadX(snake);
const dy = tunnel[i].y - getHeadY(snake);
snake = nextSnake(snake, dx, dy);
chain.unshift(snake);
}
return chain;
};
/**
* assuming the grid change and the colors got deleted, update the tunnel
*/
export const updateTunnel = (
grid: Grid,
tunnel: Point[],
toDelete: Point[]
) => {
while (tunnel.length) {
const { x, y } = tunnel[0];
if (
isEmptySafe(grid, x, y) ||
toDelete.some((p) => p.x === x && p.y === y)
) {
tunnel.shift();
} else break;
}
while (tunnel.length) {
const { x, y } = tunnel[tunnel.length - 1];
if (
isEmptySafe(grid, x, y) ||
toDelete.some((p) => p.x === x && p.y === y)
) {
tunnel.pop();
} else break;
}
};
const isEmptySafe = (grid: Grid, x: number, y: number) =>
!isInside(grid, x, y) || isEmpty(getColor(grid, x, y));
/**
* remove empty cell from start
*/
export const trimTunnelStart = (grid: Grid, tunnel: Point[]) => {
while (tunnel.length) {
const { x, y } = tunnel[0];
if (isEmptySafe(grid, x, y)) tunnel.shift();
else break;
}
};
/**
* remove empty cell from end
*/
export const trimTunnelEnd = (grid: Grid, tunnel: Point[]) => {
while (tunnel.length) {
const i = tunnel.length - 1;
const { x, y } = tunnel[i];
if (
isEmptySafe(grid, x, y) ||
tunnel.findIndex((p) => p.x === x && p.y === y) < i
)
tunnel.pop();
else break;
}
};

View File

@@ -18,6 +18,18 @@ export const drawOptions = {
colorSnake: "purple",
};
const getPointedCell = (canvas: HTMLCanvasElement) => ({
pageX,
pageY,
}: MouseEvent) => {
const { left, top } = canvas.getBoundingClientRect();
const x = Math.floor((pageX - left) / drawOptions.sizeCell) - 1;
const y = Math.floor((pageY - top) / drawOptions.sizeCell) - 2;
return { x, y };
};
export const createCanvas = ({
width,
height,
@@ -34,9 +46,19 @@ export const createCanvas = ({
canvas.style.width = w + "px";
canvas.style.height = h + "px";
canvas.style.display = "block";
canvas.style.pointerEvents = "none";
// canvas.style.pointerEvents = "none";
const cellInfo = document.createElement("div");
cellInfo.style.height = "20px";
document.body.appendChild(cellInfo);
document.body.appendChild(canvas);
canvas.addEventListener("mousemove", (e) => {
const { x, y } = getPointedCell(canvas)(e);
cellInfo.innerText = [x, y]
.map((u) => u.toString().padStart(2, " "))
.join(" / ");
});
const ctx = canvas.getContext("2d")!;
ctx.scale(upscale, upscale);
@@ -63,5 +85,12 @@ export const createCanvas = ({
ctx.fillRect((1 + x + 0.5) * 16 - 2, (2 + y + 0.5) * 16 - 2, 4, 4);
};
return { draw, drawLerp, highlightCell, canvas, ctx };
return {
draw,
drawLerp,
highlightCell,
canvas,
getPointedCell: getPointedCell(canvas),
ctx,
};
};

View File

@@ -4,6 +4,7 @@ import { getSnakeLength } from "@snk/types/snake";
import { grid, snake } from "./sample";
import { getColor } from "@snk/types/grid";
import { getBestTunnel } from "@snk/compute/getBestTunnel";
import { createOutside } from "@snk/compute/outside";
import type { Color } from "@snk/types/grid";
import type { Point } from "@snk/types/point";
@@ -16,39 +17,64 @@ for (let x = 0; x < grid.width; x++)
for (let y = 0; y < grid.height; y++)
if (getColor(grid, x, y) === 1) ones.push({ x, y });
const points = getBestTunnel(
grid,
ones[0].x,
ones[0].y,
3 as Color,
getSnakeLength(snake)
);
let k = 0;
const tunnels = ones.map(({ x, y }) => ({
x,
y,
tunnel: getBestTunnel(
grid,
createOutside(grid),
x,
y,
3 as Color,
getSnakeLength(snake)
),
}));
const onChange = () => {
const k = +inputK.value;
const i = +inputI.value;
ctx.clearRect(0, 0, 9999, 9999);
draw(grid, [] as any, []);
if (!tunnels[k]) return;
if (points) {
points.forEach(({ x, y }) => highlightCell(x, y));
highlightCell(points[k].x, points[k].y, "blue");
const { x, y, tunnel } = tunnels[k]!;
draw(grid, snake, []);
highlightCell(x, y, "red");
if (tunnel) {
tunnel.forEach(({ x, y }) => highlightCell(x, y));
highlightCell(x, y, "red");
highlightCell(tunnel[i].x, tunnel[i].y, "blue");
}
};
onChange();
const inputK = document.createElement("input") as any;
inputK.type = "range";
inputK.value = 0;
inputK.step = 1;
inputK.min = 0;
inputK.max = points ? points.length - 1 : 0;
inputK.max = tunnels ? tunnels.length - 1 : 0;
inputK.style.width = "90%";
inputK.style.padding = "20px 0";
inputK.addEventListener("input", () => {
k = +inputK.value;
inputI.value = 0;
inputI.max = (tunnels[+inputK.value]?.tunnel?.length || 1) - 1;
onChange();
});
document.body.append(inputK);
const inputI = document.createElement("input") as any;
inputI.type = "range";
inputI.value = 0;
inputI.step = 1;
inputI.min = 0;
inputI.max = (tunnels[+inputK.value]?.tunnel?.length || 1) - 1;
inputI.style.width = "90%";
inputI.style.padding = "20px 0";
inputI.addEventListener("input", onChange);
document.body.append(inputI);
onChange();

View File

@@ -1,64 +1,53 @@
import "./menu";
import { createCanvas } from "./canvas";
import { snakeToCells } from "@snk/types/snake";
import { grid, snake } from "./sample";
import { getColor } from "@snk/types/grid";
import { copySnake, snakeToCells } from "@snk/types/snake";
import { grid, snake as snake0 } from "./sample";
import { getPathTo } from "@snk/compute/getPathTo";
import type { Point } from "@snk/types/point";
const { canvas, ctx, draw, highlightCell } = createCanvas(grid);
document.body.appendChild(canvas);
const { canvas, ctx, draw, getPointedCell, highlightCell } = createCanvas(grid);
canvas.style.pointerEvents = "auto";
const ones: Point[] = [];
let snake = copySnake(snake0);
let chain = [snake];
for (let x = 0; x < grid.width; x++)
for (let y = 0; y < grid.height; y++)
if (getColor(grid, x, y) === 1) ones.push({ x, y });
canvas.addEventListener("mousemove", (e) => {
const { x, y } = getPointedCell(e);
const chains = ones.map((p) => {
const chain = getPathTo(grid, snake, p.x, p.y);
return chain && [...chain, snake];
chain = [...(getPathTo(grid, snake, x, y) || []), snake].reverse();
inputI.max = chain.length - 1;
i = inputI.value = chain.length - 1;
onChange();
});
let k = 0;
let i = 0;
canvas.addEventListener("click", () => {
snake = chain.slice(-1)[0];
chain = [snake];
inputI.max = chain.length - 1;
i = inputI.value = chain.length - 1;
onChange();
});
let i = 0;
const onChange = () => {
ctx.clearRect(0, 0, 9999, 9999);
const chain = chains[k];
if (chain) {
draw(grid, chain[i], []);
chain
.map(snakeToCells)
.flat()
.forEach(({ x, y }) => highlightCell(x, y));
} else draw(grid, snake, []);
draw(grid, chain[i], []);
chain
.map(snakeToCells)
.flat()
.forEach(({ x, y }) => highlightCell(x, y));
};
onChange();
const inputK = document.createElement("input") as any;
inputK.type = "range";
inputK.value = k;
inputK.step = 1;
inputK.min = 0;
inputK.max = chains.length - 1;
inputK.style.width = "90%";
inputK.style.padding = "20px 0";
inputK.addEventListener("input", () => {
k = +inputK.value;
i = inputI.value = 0;
inputI.max = chains[k] ? chains[k]!.length - 1 : 0;
onChange();
});
document.body.append(inputK);
const inputI = document.createElement("input") as any;
inputI.type = "range";
inputI.value = 0;
inputI.max = chains[k] ? chains[k]!.length - 1 : 0;
inputI.max = chain ? chain.length - 1 : 0;
inputI.step = 1;
inputI.min = 0;
inputI.style.width = "90%";
@@ -68,8 +57,3 @@ inputI.addEventListener("input", () => {
onChange();
});
document.body.append(inputI);
window.addEventListener("click", (e) => {
if (e.target === document.body || e.target === document.body.parentElement)
inputK.focus();
});

View File

@@ -10,7 +10,7 @@ import {
Options,
} from "@snk/draw/drawWorld";
import { userContributionToGrid } from "../action/userContributionToGrid";
import { snake3 } from "@snk/types/__fixtures__/snake";
import { snake4 as snake } from "@snk/types/__fixtures__/snake";
const createForm = ({
onSubmit,
@@ -204,7 +204,6 @@ const onSubmit = async (userName: string) => {
cells,
};
const snake = snake3;
const grid = userContributionToGrid(cells);
const chain = getBestRoute(grid, snake)!;
dispose();

View File

@@ -1 +1 @@
["interactive", "getBestTunnel", "getBestRoute", "getPathTo"]
["interactive", "getBestTunnel", "getBestRoute", "outside", "getPathTo"]

View File

@@ -0,0 +1,42 @@
import "./menu";
import { createCanvas } from "./canvas";
import { grid } from "./sample";
import type { Color } from "@snk/types/grid";
import { createOutside, isOutside } from "@snk/compute/outside";
const { canvas, ctx, draw, highlightCell } = createCanvas(grid);
document.body.appendChild(canvas);
let k = 0;
const onChange = () => {
ctx.clearRect(0, 0, 9999, 9999);
draw(grid, [] as any, []);
const outside = createOutside(grid, k as Color);
for (let x = outside.width; x--; )
for (let y = outside.height; y--; )
if (isOutside(outside, x, y)) highlightCell(x, y);
};
onChange();
const inputK = document.createElement("input") as any;
inputK.type = "range";
inputK.value = 0;
inputK.step = 1;
inputK.min = 0;
inputK.max = 4;
inputK.style.width = "90%";
inputK.style.padding = "20px 0";
inputK.addEventListener("input", () => {
k = +inputK.value;
onChange();
});
document.body.append(inputK);
window.addEventListener("click", (e) => {
if (e.target === document.body || e.target === document.body.parentElement)
inputK.focus();
});

12
packages/demo/demo.svg.ts Normal file
View File

@@ -0,0 +1,12 @@
import "./menu";
import { getBestRoute } from "@snk/compute/getBestRoute";
import { createSvg } from "../svg-creator";
import { grid, snake } from "./sample";
import { drawOptions } from "./canvas";
const chain = getBestRoute(grid, snake);
const svg = createSvg(grid, chain, drawOptions, { frameDuration: 200 });
const container = document.createElement("div");
container.innerHTML = svg;
document.body.appendChild(container);

View File

@@ -15,8 +15,8 @@ const config = {
demo: demos[0],
};
{
const d = window.location.pathname.match(/(\w+)\.html/)?.[1];
if (d && demos.includes(d)) config.demo = d;
const d = window.location.pathname.match(/(\w+)\.html/);
if (d && demos.includes(d[1])) config.demo = d[1];
}
const onChange = () => {

View File

@@ -25,7 +25,7 @@ const config: Configuration = {
transpileOnly: true,
compilerOptions: {
lib: ["dom", "es2020"],
target: "es5",
target: "es2019",
},
},
},

View File

@@ -4,7 +4,7 @@ import { realistic as grid } from "@snk/types/__fixtures__/grid";
import { createGif } from "..";
let snake = createSnakeFromCells(
Array.from({ length: 6 }, (_, i) => ({ x: i, y: -1 }))
Array.from({ length: 4 }, (_, i) => ({ x: i, y: -1 }))
);
const chain = [snake];

View File

@@ -33,7 +33,6 @@ for (const key of [
"corner",
"small",
"smallPacked",
"enclave",
] as const)
it(`should generate ${key} gif`, async () => {
const grid = grids[key];

View File

@@ -1,6 +1,7 @@
import ParkMiller from "park-miller";
import { Color, createEmptyGrid, setColor } from "../grid";
import { randomlyFillGrid } from "../randomlyFillGrid";
import { createFromAscii } from "./createFromAscii";
const colors = [1, 2, 3] as Color[];
@@ -18,106 +19,65 @@ setColor(corner, 4, 0, 1 as Color);
setColor(corner, 4, 4, 1 as Color);
setColor(corner, 0, 0, 1 as Color);
export const enclave = createEmptyGrid(7, 7);
setColor(enclave, 3, 4, 2 as Color);
setColor(enclave, 2, 3, 2 as Color);
setColor(enclave, 2, 4, 2 as Color);
setColor(enclave, 4, 4, 2 as Color);
setColor(enclave, 4, 3, 2 as Color);
setColor(enclave, 3, 3, 1 as Color);
setColor(enclave, 5, 5, 1 as Color);
export const enclaveN = createFromAscii(`
export const enclaveBorder = createEmptyGrid(7, 7);
setColor(enclaveBorder, 1, 0, 3 as Color);
setColor(enclaveBorder, 2, 1, 3 as Color);
setColor(enclaveBorder, 3, 0, 3 as Color);
setColor(enclaveBorder, 2, 0, 1 as Color);
#.#
#
export const enclaveM = createEmptyGrid(7, 7);
setColor(enclaveM, 1, 0, 3 as Color);
setColor(enclaveM, 2, 0, 3 as Color);
setColor(enclaveM, 3, 0, 3 as Color);
setColor(enclaveM, 1, 4, 3 as Color);
setColor(enclaveM, 3, 4, 3 as Color);
setColor(enclaveM, 4, 1, 3 as Color);
setColor(enclaveM, 4, 2, 3 as Color);
setColor(enclaveM, 4, 3, 3 as Color);
setColor(enclaveM, 0, 1, 3 as Color);
setColor(enclaveM, 0, 2, 3 as Color);
setColor(enclaveM, 0, 3, 3 as Color);
setColor(enclaveM, 2, 2, 1 as Color);
`);
export const enclaveBorder = createFromAscii(`
#.#
#
export const enclaveK = createEmptyGrid(7, 7);
setColor(enclaveK, 1, 1, 3 as Color);
setColor(enclaveK, 2, 1, 3 as Color);
setColor(enclaveK, 3, 1, 3 as Color);
setColor(enclaveK, 0, 1, 3 as Color);
setColor(enclaveK, 0, 2, 3 as Color);
setColor(enclaveK, 0, 3, 3 as Color);
setColor(enclaveK, 3, 1, 3 as Color);
setColor(enclaveK, 3, 2, 3 as Color);
setColor(enclaveK, 3, 3, 3 as Color);
setColor(enclaveK, 1, 4, 3 as Color);
setColor(enclaveK, 3, 4, 3 as Color);
setColor(enclaveK, 3, 5, 3 as Color);
setColor(enclaveK, 1, 5, 3 as Color);
setColor(enclaveK, 2, 2, 1 as Color);
`);
export const enclaveM = createFromAscii(`
export const enclaveU = createEmptyGrid(17, 9);
setColor(enclaveU, 1, 1, 3 as Color);
setColor(enclaveU, 2, 1, 3 as Color);
setColor(enclaveU, 3, 1, 3 as Color);
setColor(enclaveU, 0, 1, 3 as Color);
setColor(enclaveU, 0, 2, 3 as Color);
setColor(enclaveU, 0, 3, 3 as Color);
setColor(enclaveU, 3, 1, 3 as Color);
setColor(enclaveU, 3, 2, 3 as Color);
setColor(enclaveU, 3, 3, 3 as Color);
setColor(enclaveU, 1, 4, 3 as Color);
setColor(enclaveU, 3, 4, 3 as Color);
setColor(enclaveU, 3, 5, 3 as Color);
setColor(enclaveU, 1, 5, 3 as Color);
setColor(enclaveU, 2, 2, 1 as Color);
setColor(enclaveU, 1, 2, 1 as Color);
setColor(enclaveU, 2, 3, 1 as Color);
setColor(enclaveU, 1, 3, 1 as Color);
setColor(enclaveU, 2, 4, 1 as Color);
setColor(enclaveU, 16, 8, 1 as Color);
###
# #
# . #
# #
# #
`);
export const closed = createEmptyGrid(16, 16);
setColor(closed, 1 + 5, 1 + 5, 3 as Color);
setColor(closed, 2 + 5, 4 + 5, 3 as Color);
setColor(closed, 2 + 5, 1 + 5, 3 as Color);
setColor(closed, 0 + 5, 2 + 5, 3 as Color);
setColor(closed, 0 + 5, 3 + 5, 3 as Color);
setColor(closed, 1 + 5, 4 + 5, 3 as Color);
setColor(closed, 3 + 5, 1 + 5, 3 as Color);
setColor(closed, 3 + 5, 2 + 5, 3 as Color);
setColor(closed, 3 + 5, 3 + 5, 3 as Color);
setColor(closed, 1 + 5, 2 + 5, 3 as Color);
setColor(closed, 1 + 5, 3 + 5, 3 as Color);
setColor(closed, 2 + 5, 2 + 5, 1 as Color);
export const enclaveK = createFromAscii(`
export const closedU = createEmptyGrid(20, 20);
setColor(closedU, 1 + 10, 1 + 10, 3 as Color);
setColor(closedU, 2 + 10, 1 + 10, 3 as Color);
setColor(closedU, 3 + 10, 1 + 10, 3 as Color);
setColor(closedU, 0 + 10, 1 + 10, 3 as Color);
setColor(closedU, 0 + 10, 2 + 10, 3 as Color);
setColor(closedU, 0 + 10, 3 + 10, 3 as Color);
setColor(closedU, 3 + 10, 1 + 10, 3 as Color);
setColor(closedU, 3 + 10, 2 + 10, 3 as Color);
setColor(closedU, 3 + 10, 3 + 10, 3 as Color);
setColor(closedU, 1 + 10, 4 + 10, 3 as Color);
setColor(closedU, 3 + 10, 4 + 10, 3 as Color);
setColor(closedU, 3 + 10, 5 + 10, 3 as Color);
setColor(closedU, 1 + 10, 5 + 10, 3 as Color);
setColor(closedU, 2 + 10, 5 + 10, 3 as Color);
setColor(closedU, 2 + 10, 2 + 10, 1 as Color);
setColor(closedU, 1 + 10, 2 + 10, 1 as Color);
setColor(closedU, 2 + 10, 3 + 10, 1 as Color);
setColor(closedU, 1 + 10, 3 + 10, 1 as Color);
setColor(closedU, 2 + 10, 4 + 10, 1 as Color);
####
# .#
# #
# #
# #
`);
export const enclaveU = createFromAscii(`
####
#..#
#..#
#.#
# # .
`);
export const closedP = createFromAscii(`
###
##.#
## #
##
`);
export const closedU = createFromAscii(`
####
#..#
#..#
#.#
###
`);
export const closedO = createFromAscii(`
#######
# #
# . #
# #
#######
`);
const createRandom = (width: number, height: number, emptyP: number) => {
const grid = createEmptyGrid(width, height);