🚀 refactor demo
This commit is contained in:
@@ -1,48 +1,20 @@
|
||||
import { Grid, Color, getColor, isInside, setColor } from "./grid";
|
||||
import { Point } from "./point";
|
||||
import {
|
||||
Color,
|
||||
getColor,
|
||||
Grid,
|
||||
isEmpty,
|
||||
isInside,
|
||||
setColorEmpty,
|
||||
} from "./grid";
|
||||
import { getHeadX, getHeadY, Snake } from "./snake";
|
||||
|
||||
export const moveSnake = (snake: Point[], headx: number, heady: number) => {
|
||||
for (let k = snake.length - 1; k > 0; k--) {
|
||||
snake[k].x = snake[k - 1].x;
|
||||
snake[k].y = snake[k - 1].y;
|
||||
}
|
||||
snake[0].x = headx;
|
||||
snake[0].y = heady;
|
||||
};
|
||||
export const step = (grid: Grid, stack: Color[], snake: Snake) => {
|
||||
const x = getHeadX(snake);
|
||||
const y = getHeadY(snake);
|
||||
const color = getColor(grid, x, y);
|
||||
|
||||
export const stepSnake = (
|
||||
snake: Point[],
|
||||
direction: Point,
|
||||
options: { maxSnakeLength: number }
|
||||
) => {
|
||||
const headx = snake[0].x + direction.x;
|
||||
const heady = snake[0].y + direction.y;
|
||||
|
||||
if (snake.length === options.maxSnakeLength) {
|
||||
moveSnake(snake, headx, heady);
|
||||
} else {
|
||||
snake.unshift({ x: headx, y: heady });
|
||||
if (isInside(grid, x, y) && !isEmpty(color)) {
|
||||
stack.push(color);
|
||||
setColorEmpty(grid, x, y);
|
||||
}
|
||||
};
|
||||
|
||||
export const stepPicking = (grid: Grid, snake: Point[], stack: Color[]) => {
|
||||
if (isInside(grid, snake[0].x, snake[0].y)) {
|
||||
const c = getColor(grid, snake[0].x, snake[0].y);
|
||||
|
||||
if (c) {
|
||||
setColor(grid, snake[0].x, snake[0].y, null);
|
||||
stack.push(c);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const step = (
|
||||
grid: Grid,
|
||||
snake: Point[],
|
||||
stack: Color[],
|
||||
direction: Point,
|
||||
options: { maxSnakeLength: number }
|
||||
) => {
|
||||
stepSnake(snake, direction, options);
|
||||
stepPicking(grid, snake, stack);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user