explorata/src/modules/board.js

66 lines
1.7 KiB
JavaScript

import {
evolve1d,
create2dState,
create1dStateOneCell,
create1dState,
} from "./core.js";
import { getRandomInt } from "./common.js";
import { Cell } from "./cell.js";
export class Board {
constructor(width, height) {
this.width = width;
this.height = height;
this.grid;
this.cellProperties = {
size: 3,
liveColor: "#000000",
deadColor: "#F5F5F5",
};
}
}
// create a 2D board from a 1D CA initial state
// function createBoard(state, rules, height) {
// function createBoardAcc(s, h, acc) {
// if (h === 0) return acc;
// const newState = evolve1d(s, rules);
// const newAcc = acc.concat([s]);
// return createBoardAcc(newState, h - 1, newAcc);
// }
// return createBoardAcc(state, height, []);
// }
// performance "choke point" in full imperative
export function createBoard(state, rules, max) {
var board = [];
let prevState = [];
for (let i = 0; i < max; i++) {
let nextState = [];
// use the passed initial step during first iteration
if (i == 0) {
nextState = evolve1d(state, rules);
} else {
nextState = evolve1d(prevState, rules);
}
// flat array
board = board.concat(nextState.map((s) => new Cell(s)));
prevState = nextState;
}
return board;
}
// create a first state, either a single living cell
// at the center or random ones
export const create1dInitialState = (width, type = "onecell") => {
if (type === "onecell") return create1dStateOneCell(width);
return create1dState(width, getRandomInt, [0, 2]);
};
// initialize 2d board with random cells
export const create2dRandomGrid = (width, height) => {
return create2dState(width, height, getRandomInt, [0, 2]);
};