working 2D CA functions + canvas draws in one go

This commit is contained in:
Ali Gator 2022-01-02 14:47:27 +01:00
parent 09afd29624
commit 1a14e2d028
4 changed files with 197 additions and 181 deletions

View File

@ -4,8 +4,9 @@
<link rel="stylesheet" href="./style.css" >
</head>
<body>
<h1>Cellular Automata Explorer</h1>
<div id="container">
<sidebar>
<h1>Cellular Automaton Explorer</h1>
<div class="menu-row">
<h2>Elementary Cellular Automata</h2>
<div class="menu-row-content">
@ -70,7 +71,7 @@
</div>
<div class="form-field">
<label for="dead">Dead cell color</label>
<input name="dead" type="color" id="dead" value="#99FF00"/>
<input name="dead" type="color" id="dead" value="#AA78E8"/>
</div>
<div class="form-field">
<label>Cell size</label>
@ -104,6 +105,7 @@
<main id="main">
<canvas width="500" height="500" id="canvas"></canvas>
</main>
</div>
<script type="module" src="./js/main.js"></script>
</body>
</html>

View File

@ -1,43 +1,45 @@
// get the next evolution of a 1D CA
// handles negative index and index bigger than its array length
function guard(index, array) {
if (index > (array.length - 1)) return 0;
if (index < 0) return (array.length - 1);
return index;
}
// get the next evolution of a 1D CA initial state
function evolve(state, rules) {
function evolveAcc(s, acc) {
const [x, y, z, ...xs] = s;
if (!xs.length) {
return acc[acc.length - 1] + acc + acc[0];
function getCell(index) {
const safeIndex = guard(index, state);
return state[safeIndex];
}
const newState = state.map((_, x) => {
const cells = [
getCell(x - 1),
getCell(x),
getCell(x + 1)];
return rules[cells.join('')];
});
return newState.map(Number);
}
const rule = x + y + z;
const newAcc = acc.concat(rules[rule]);
return evolveAcc(y + z + xs.join(''), newAcc);
}
return evolveAcc(state, '');
}
// create a 2D board from a 1D initial state
// 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 = evolve(state, rules);
const newAcc = acc.concat(state);
const newState = evolve(s, rules);
const newAcc = acc.concat([s]);
return createBoardAcc(newState, h - 1, newAcc);
}
return createBoardAcc(state, height, []).map(
(row) => row.split(''))
return createBoardAcc(state, height, []);
}
// Find the neighbor of a given cell in a 2D CA board
function getCellNeighbors(board, cellCoordinates) {
const [x, y] = cellCoordinates;
const rowLength = board[0].length; // caca?
// handles board edges where the cell is missing neighbors
function getCell(xx, yy) {
// handles negative index and index bigger than its array length
function guard(index, array) {
if (index > array.length - 1) return 0;
if (index < 0) return array.length - 1;
return index;
}
const safeX = guard(xx, board);
const safeY = guard(yy, rowLength);
return board[safeX][safeY];
@ -52,10 +54,13 @@ function getCellNeighbors(board, cellCoordinates) {
];
}
// Sums the value of a cell's neighbors
function getNeighborsSum(cells) {
return cells.reduce((cell, acc) => cell + acc, 0);
}
// Get the next evolution of a cell according to
// Conway's game of life rules
function conwayRules(cell, neighbors) {
// loneliness rule
if (cell === 1 && neighbors < 2) return 0;
@ -67,6 +72,7 @@ function conwayRules(cell, neighbors) {
return cell;
}
// get the next evolution of a 2D CA initial state
function evolve2d(board, rulesFn) {
return board.map((row, x) => row.map((cell, y) => {
const neighbors = getCellNeighbors(board, [x, y]);
@ -93,15 +99,21 @@ function getDrawingValues(state, acc, cell) {
);
}
// Populates the first state of a 1D CA with cells returned
// by initFn
function initialState1d(width, initFn, args) {
return [...Array(width)].map(
() => initFn(...args).toString(),
).join('');
() => initFn(...args),
);
}
// Populates the first state of a 2D CA with cells returned
// by initFn
function initialState2d(width, height, initFn, args) {
return [...Array(height)].map(
() => [...Array(width)].map(() => initFn(...args)),
() => [...Array(width)].map(
() => initFn(...args),
),
);
}

View File

@ -1,6 +1,7 @@
import { getRandomInt, sleep, hexToRgb } from './common.js';
// TODO : Change board resolution according to the set cell dimensions
import { getRandomInt, sleep } from './common.js';
import {
evolve, evolve2d, getDrawingValues, initialState1d, conwayRules, createBoard,
evolve, evolve2d, getDrawingValues, initialState1d, initialState2d, conwayRules, createBoard,
} from './automata.js';
let drawing = 1;
@ -42,70 +43,59 @@ function reset() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
// TODO: Hide accumulator inside maybe?
async function draw(state, acc) {
async function draw(dimension) {
if (drawing === 0) {
return;
}
const rules = getRules();
const cellProperties = {
dimensions: cellSize.value,
liveColor: live.value,
deadColor: dead.value,
};
// const position = acc * cell.dimension;
// if (position >= canvas.height && !loop.checked) return;
const initialState = (
() => {
if (dimension === '1d') {
return initialState1d(
Math.floor(canvas.width / cellProperties.dimensions),
getRandomInt,
[0, 2],
);
}
return evolve2d(initialState2d(
Math.floor(canvas.width / cellProperties.dimensions),
Math.floor(canvas.height / cellProperties.dimensions),
getRandomInt,
[0, 2]), conwayRules);
})();
const rules = getRules();
const board = createBoard(state, rules, canvas.height);
// const newState = evolve(state, rules);
// const line = getDrawingValues(newState, acc, cell);
const board = (
() => {
if (dimension === '1d') return createBoard(initialState, rules, Math.floor(canvas.height / cellProperties.dimensions));
return initialState;
})();
board.reduce((row, prevRow, x) => {
board.map((row, y) => {
const d = cellProperties.dimensions;
row.reduce((cell) => {
ctx.moveTo(x * d, y * d);
ctx.fillRect(x * d, x * d, d, d);
ctx.fillStyle = (() => {
if (cell === '1') return cellProperties.liveColor;
return row.map(
(cell, x) => {
ctx.fillStyle = (
() => {
if (cell === 1) return cellProperties.liveColor;
return cellProperties.deadColor;
})();
})
ctx.fillRect(x * d, y * d, d, d);
return cell;
},
);
});
// await sleep(40);
// const newAcc = (() => {
// if (position >= canvas.height && loop.checked) return 0;
// return acc;
// })();
// await draw(newState, newAcc + 1);
}
async function draw2d(board, acc) {
if (drawing === 0) {
}
}
// Listeners
startBtn2d.addEventListener('click', async () => {
reset();
await sleep(60);
drawing = 1;
const initialState = initialState2d(canvas.width, canvas.height, getRandomInt, [0, 2]);
const nextState = evolve2d(initialState, conwayRules);
draw2d(initialState, 0);
});
startBtn.addEventListener('click', async () => {
reset();
@ -113,9 +103,17 @@ startBtn.addEventListener('click', async () => {
drawing = 1;
const initialState = initialState1d(canvas.width, getRandomInt, [0, 2]);
draw('1d');
});
draw(initialState, 0);
startBtn2d.addEventListener('click', async () => {
reset();
await sleep(60);
drawing = 1;
draw('2d');
});
resetBtn.addEventListener('click', async () => {

View File

@ -6,13 +6,11 @@
body {
background: black;
color: white;
display: flex;
font-family: Courier New;
}
canvas {
background: #110812;
margin: 20px 0 0 0;
}
h1, h2 {
@ -20,7 +18,9 @@ h1, h2 {
}
h1 {
font-size: large;
margin : 10px auto;
font-size: larger;
text-align: center;
}
.menu-row h2 {
@ -28,11 +28,12 @@ h1 {
padding: 10px;
cursor: pointer;
border: 2px solid darkgrey;
margin: 0 0 10px 0;
}
sidebar {
flex: auto;
padding: 10px;
padding: 0 10px;
}
input[type="button"] {
@ -48,7 +49,6 @@ input[type="button"] {
.menu-row {
flex: 1;
margin: 10px 0;
}
label, .form-field label {
@ -59,3 +59,7 @@ label, .form-field label {
#main {
flex: 4;
}
#container {
display: flex;
}