123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- export const generateNewGrid = (grid: boolean[][]) => {
- return [...grid].map((row, y) => {
- const newRow = [...row].map((cell, x) => {
- const isAlive = cell;
- const livingNeighbors = countLivingNeighbors(grid, x, y);
-
- if (isAlive) {
- if (livingNeighbors === 2 || livingNeighbors === 3) {
- return true;
- } else {
- return false;
- }
- } else {
- if (livingNeighbors === 3) {
- return true;
- }
- }
-
- return isAlive;
- });
-
- return newRow;
- });
- };
-
- export const countLivingNeighbors = (
- grid: boolean[][],
- x: number,
- y: number,
- ): number => {
- return getNeighbors(grid, x, y).filter((el) => el).length;
- };
-
- export const getNeighbors = (
- grid: boolean[][],
- x: number,
- y: number,
- ): boolean[] => {
- const neighbors = [];
- const height = grid.length;
- const width = grid[0].length;
-
- const isNotOnTopRow = y > 0;
- const isNotOnFarLeftRow = x > 0;
- const isNotOnBottomRow = y < height - 1;
- const isNotOnFarRightRow = x < width - 1;
-
- if (isNotOnTopRow) {
- neighbors.push(grid[y - 1][x]); // N
- if (isNotOnFarLeftRow) neighbors.push(grid[y - 1][x - 1]); // NW
- if (isNotOnFarRightRow) neighbors.push(grid[y - 1][x + 1]); // NE
- }
-
- if (isNotOnFarLeftRow) neighbors.push(grid[y][x - 1]); // W
- if (isNotOnFarRightRow) neighbors.push(grid[y][x + 1]); // E
-
- if (isNotOnBottomRow) {
- neighbors.push(grid[y + 1][x]); // S
- if (isNotOnTopRow) neighbors.push(grid[y + 1][x - 1]); // SW
- if (isNotOnFarRightRow) neighbors.push(grid[y + 1][x + 1]); // SE
- }
-
- return neighbors;
- };
-
- export const updateGridDimensions = (
- oldDimensions: {
- width: number;
- height: number;
- },
- newDimensions: { width?: number; height?: number },
- grid: boolean[][],
- ): boolean[][] => {
- const width = newDimensions.width ?? oldDimensions.width;
- const height = newDimensions.height ?? oldDimensions.height;
-
- grid = [...grid];
-
- if (height > oldDimensions.height) {
- while (grid.length < height) {
- grid.push(Array(width).fill(false));
- }
- } else if (height < oldDimensions.height) {
- while (grid.length > height) {
- if (grid.length <= 1) break;
- grid.pop();
- }
- }
-
- if (width > oldDimensions.width) {
- grid = grid.map((row) => {
- while (row.length < width) {
- row.push(false);
- }
-
- return row;
- });
- } else if (width < oldDimensions.width) {
- grid = grid.map((row) => {
- while (row.length > width) {
- if (row.length <= 1) break;
- row.pop();
- }
-
- return row;
- });
- }
-
- return grid;
- };
|