Compare commits

...

5 Commits

Author SHA1 Message Date
74e9667c51 2d logics fully ready (me think) 2022-01-02 16:45:03 +01:00
1a14e2d028 working 2D CA functions + canvas draws in one go 2022-01-02 14:47:27 +01:00
09afd29624 [wip] game of life, 1D to 2d 2022-01-01 23:11:38 +01:00
56566aa802 structuring shits up 2022-01-01 14:07:34 +01:00
a2e16a0fde hidable menu content 2021-12-31 13:17:37 +01:00
10 changed files with 441 additions and 222 deletions

11
.eslintrc.json Normal file
View File

@ -0,0 +1,11 @@
{
"env": {
"browser": true,
"es2015": true
},
"extends": [
"airbnb-base"
],
"rules": {
}
}

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
package-lock.json
node_modules

View File

@ -1,92 +0,0 @@
<html>
<head>
<title>Cellular Automaton Explorer</title>
<link rel="stylesheet" href="./style.css" >
</head>
<body>
<sidebar>
<h1>Cellular Automaton Explorer</h1>
<div class="menu-row">
<form name="rules">
<div class="form-field">
<label>Rules</label>
</div>
<div class="form-field">
<label>111
<input type="checkbox" name="111" checked>
</label>
</div>
<div class="form-field">
<label>110
<input type="checkbox" name="110">
</label>
</div>
<div class="form-field">
<label>101
<input type="checkbox" name="101" checked>
</label>
</div>
<div class="form-field">
<label>100
<input type="checkbox" name="100">
</label>
</div>
<div class="form-field">
<label>011
<input type="checkbox" name="011" checked>
</label>
</div>
<div class="form-field">
<label>010
<input type="checkbox" name="010">
</label>
</div>
<div class="form-field">
<label>001
<input type="checkbox" name="001">
</label>
</div>
<div class="form-field">
<label>000
<input type="checkbox" name="000" checked>
</label>
</div>
<div class="form-field">
<input type="button" name="start" id="start" value="start"/>
</div>
<div class="form-field">
<input type="button" name="stop" id="stop" value="stop"/>
</div>
<div class="form-field">
<input type="button" name="reset" id="reset" value="reset"/>
</div>
</form>
</div>
<div class="menu-row">
<form>
<div class="form-field">
<label for="live">Living cell color</label>
<input name="live" type="color" id="live" value="#000000"/>
</div>
<div class="form-field">
<label for="dead">Dead cell color</label>
<input name="dead" type="color" id="dead" value="#99FF00"/>
</div>
<div class="form-field">
<label>Cell size</label>
<input name="cellSize" type="number" id="cellSize" value="5"/>
</div>
<div class="form-field">
<label>Loop
<input name="loop" type="checkbox" id="loop"/>
</label>
</div>
</form>
</div>
</sidebar>
<main id="main">
<canvas width="500" height="500" id="canvas"></canvas>
</main>
<script src="main.js"></script>
</body>
</html>

125
main.js
View File

@ -1,125 +0,0 @@
let drawing = 1;
const form = Array.from(document.forms.rules.elements);
const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');
const main = document.querySelector('#main');
const dead = document.querySelector('#dead');
const live = document.querySelector('#live');
const startBtn = document.querySelector('#start');
const resetBtn = document.querySelector('#reset');
const stopBtn = document.querySelector('#stop');
const cellSize = document.querySelector('#cellSize');
const loop = document.querySelector('#loop');
canvas.width = main.offsetWidth * 0.9;
canvas.height = main.offsetHeight * 0.9;
// TODO: Hide iterator inside
function evolve(state, acc, rules) {
const [x, y, z, ...xs] = state;
if (!xs.length) {
return acc[acc.length - 1] + acc + acc[0];
}
const rule = x + y + z;
const newAcc = acc.concat(rules[rule]);
return evolve(y + z + xs.join(''), newAcc, rules);
}
function getRules() {
const rules = {};
form.reduce((_, i) => {
if (i !== undefined
&& i.type === 'checkbox') {
if (i.checked) rules[i.name] = '1';
else rules[i.name] = '0';
}
return rules;
}, rules);
return rules;
}
function getDrawingValues(state, acc) {
const cellDim = cellSize.value;
return Object.keys(state).map(
(key) => {
const fillStyle = state[key] === '1' ? live.value : dead.value;
return {
move: [key * cellDim, acc * cellDim],
fill: [key * cellDim, acc * cellDim, cellDim, cellDim],
fillStyle,
};
},
);
}
function getRandomInt(min, max) {
const minVal = Math.ceil(min);
const maxVal = Math.floor(max);
// The maximum is exclusive and the minimum is inclusive
return Math.floor(Math.random() * (maxVal - minVal) + minVal);
}
async function sleep(ms) {
await new Promise((resolve) => setTimeout(resolve, ms));
}
async function draw(state, acc) {
if (drawing === 0) {
return;
}
const position = acc * cellSize.value;
if (position >= canvas.height && !loop.checked) return;
const rules = getRules();
const newState = evolve(state, '', rules);
const line = getDrawingValues(newState, acc);
line.map((cell) => {
ctx.moveTo(...cell.move);
ctx.fillRect(...cell.fill);
ctx.fillStyle = cell.fillStyle;
return cell;
});
await sleep(40);
const newAcc = () => {
if (position >= canvas.height && loop.checked) return 0;
return acc;
};
await draw(newState, newAcc() + 1);
}
function reset() {
drawing = 0;
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
startBtn.addEventListener('click', async () => {
reset();
await sleep(60);
drawing = 1;
const initialState = [...Array(canvas.width)].map(
() => getRandomInt(0, 2).toString(),
).join('');
draw(initialState, 1);
});
resetBtn.addEventListener('click', async () => {
reset();
});
stopBtn.addEventListener('click', async () => {
drawing = 0;
});

16
package.json Normal file
View File

@ -0,0 +1,16 @@
{
"name": "exploraton",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"serve": "python3 -m http.server 8001 --directory src"
},
"author": "gator",
"license": "MIT",
"devDependencies": {
"eslint": "^8.5.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-plugin-import": "^2.25.3"
}
}

103
src/index.html Normal file
View File

@ -0,0 +1,103 @@
<html>
<head>
<title>Cellular Automaton Explorer</title>
<link rel="stylesheet" href="./style.css" >
</head>
<body>
<h1>Cellular Automata Explorer</h1>
<div id="container">
<sidebar>
<div class="menu-row">
<h2> Cell Properties</h2>
<div class="menu-row-content">
<form>
<div class="form-field">
<label for="live">Living cell color</label>
<input name="live" type="color" id="live" value="#000000"/>
</div>
<div class="form-field">
<label for="dead">Dead cell color</label>
<input name="dead" type="color" id="dead" value="#AA78E8"/>
</div>
<div class="form-field">
<label>Cell size</label>
<input name="cellSize" type="number" id="cellSize" value="5"/>
</div>
</form>
</div>
</div>
<div class="menu-row">
<h2>Elementary Cellular Automata</h2>
<div class="menu-row-content">
<form name="rules">
<div class="form-field">
<label>Rules</label>
</div>
<div class="form-field">
<label>111
<input type="checkbox" name="111" checked>
</label>
</div>
<div class="form-field">
<label>110
<input type="checkbox" name="110">
</label>
</div>
<div class="form-field">
<label>101
<input type="checkbox" name="101" checked>
</label>
</div>
<div class="form-field">
<label>100
<input type="checkbox" name="100">
</label>
</div>
<div class="form-field">
<label>011
<input type="checkbox" name="011" checked>
</label>
</div>
<div class="form-field">
<label>010
<input type="checkbox" name="010">
</label>
</div>
<div class="form-field">
<label>001
<input type="checkbox" name="001">
</label>
</div>
<div class="form-field">
<label>000
<input type="checkbox" name="000" checked>
</label>
</div>
<div class="form-field">
<input type="button" name="start" id="start" value="start"/>
<input type="button" name="stop" class="stop" value="stop"/>
<input type="button" name="reset" class="reset" value="reset"/>
</div>
</form>
</div>
</div>
<div class="menu-row">
<h2>2D Cellular Automata</h2>
<div class="menu-row-content">
<form>
<div class="form-field">
<input type="button" name="start2d" id="start2d" value="start"/>
<input type="button" name="stop" class="stop" value="stop"/>
<input type="button" name="reset" class="reset" value="reset"/>
</div>
</form>
</div>
</div>
</sidebar>
<main id="main">
<canvas width="500" height="500" id="canvas"></canvas>
</main>
</div>
<script type="module" src="./js/main.js"></script>
</body>
</html>

122
src/js/automata.js Normal file
View File

@ -0,0 +1,122 @@
// 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 evolve1d(state, rules) {
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);
}
// 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, []);
}
// 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) {
const safeX = guard(xx, board);
const safeY = guard(yy, rowLength);
return board[safeX][safeY];
}
// the current cell is not included in the result
return [
getCell(x - 1, y - 1), getCell(x, y - 1),
getCell(x + 1, y - 1), getCell(x - 1, y),
getCell(x + 1, y), getCell(x - 1, y + 1),
getCell(x, y + 1), getCell(x + 1, y - 1),
];
}
// 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;
// overpopulation rule
if (cell === 1 && neighbors > 3) return 0;
// born when three live neighbors rule
if (cell === 0 && neighbors === 3) return 1;
// the cell remains the same if none apply
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]);
const sum = getNeighborsSum(neighbors);
return rulesFn(cell, sum);
}));
}
function getDrawingValues(state, acc, cell) {
const d = cell.dimension;
return Object.keys(state).map(
(key) => {
const fillStyle = (() => {
if (state[key] === '1') return cell.liveColor;
return cell.deadColor;
})();
return {
move: [key * d, acc * d],
fill: [key * d, acc * d, d, d],
fillStyle,
};
},
);
}
// Populates the first state of a 1D CA with cells returned
// by initFn
function initialState1d(width, initFn, args) {
return [...Array(width)].map(
() => 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),
),
);
}
export {
getDrawingValues, initialState1d, initialState2d, evolve1d, evolve2d, conwayRules, createBoard,
};

12
src/js/common.js Normal file
View File

@ -0,0 +1,12 @@
function getRandomInt(min, max) {
const minVal = Math.ceil(min);
const maxVal = Math.floor(max);
// The maximum is exclusive and the minimum is inclusive
return Math.floor(Math.random() * (maxVal - minVal) + minVal);
}
async function sleep(ms) {
await new Promise((resolve) => setTimeout(resolve, ms));
}
export { getRandomInt, sleep };

154
src/js/main.js Normal file
View File

@ -0,0 +1,154 @@
import { getRandomInt, sleep } from './common.js';
import {
evolve2d, initialState1d, initialState2d, conwayRules, createBoard,
} from './automata.js';
let drawing = 1;
const form = Array.from(document.forms.rules.elements);
const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');
const main = document.querySelector('#main');
const dead = document.querySelector('#dead');
const live = document.querySelector('#live');
const cellSize = document.querySelector('#cellSize');
const startBtn = document.querySelector('#start');
const startBtn2d = document.querySelector('#start2d');
const resetBtn = document.querySelectorAll('.reset');
const stopBtn = document.querySelectorAll('.stop');
// const loop = document.querySelector('#loop');
const menuRow = document.querySelectorAll('.menu-row');
function drawCanvas(board, props) {
board.map((row, y) => {
const d = props.size;
return row.map(
(cell, x) => {
ctx.fillStyle = (
() => {
if (cell === 1) return props.liveColor;
return props.deadColor;
})();
ctx.fillRect(x * d, y * d, d, d);
return cell;
},
);
});
}
function getRules() {
const rules = {};
form.reduce((_, i) => {
if (i !== undefined
&& i.type === 'checkbox') {
if (i.checked) rules[i.name] = '1';
else rules[i.name] = '0';
}
return rules;
}, rules);
return rules;
}
function getCellProperties() {
return {
size: cellSize.value,
liveColor: live.value,
deadColor: dead.value,
};
}
function reset() {
drawing = 0;
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
function resizeCanvas() {
canvas.width = main.offsetWidth * 0.9;
canvas.height = main.offsetHeight * 0.9;
}
async function draw1d() {
const rules = getRules();
const props = getCellProperties();
const initialState = initialState1d(
Math.floor(canvas.width / props.size),
getRandomInt,
[0, 2],
);
const board = createBoard(initialState, rules, Math.floor(canvas.height / props.size));
drawCanvas(board, props);
}
async function draw2d() {
const props = getCellProperties();
const initialState = initialState2d(
Math.floor(canvas.width / props.size),
Math.floor(canvas.height / props.size),
getRandomInt,
[0, 2],
);
const board = evolve2d(initialState, conwayRules);
async function draw2dNext(b) {
if (drawing === 0) return;
const newBoard = evolve2d(b, conwayRules);
drawCanvas(b, props);
await sleep(300);
draw2dNext(newBoard);
}
return draw2dNext(board);
}
// Listeners
startBtn.addEventListener('click', async () => {
reset();
await sleep(60);
drawing = 1;
draw1d();
});
startBtn2d.addEventListener('click', async () => {
reset();
await sleep(60);
drawing = 1;
draw2d();
});
resetBtn.forEach((elem) => {
elem.addEventListener('click', async () => {
reset();
});
});
stopBtn.forEach((elem) => {
elem.addEventListener('click', async () => {
drawing = 0;
});
});
menuRow.forEach((elem) => {
elem.querySelector('h2').addEventListener('click', async (e) => {
const parent = e.currentTarget.parentNode;
const menuDisplay = parent.querySelector('.menu-row-content').style;
if (menuDisplay.display !== 'none') menuDisplay.setProperty('display', 'none');
else menuDisplay.setProperty('display', 'block');
});
});
window.addEventListener('load', () => {
resizeCanvas();
});
window.addEventListener('resize', () => {
resizeCanvas();
});

View File

@ -6,29 +6,41 @@
body {
background: black;
color: white;
display: flex;
font-family: Courier New;
}
canvas {
background: #110812;
margin: 20px 0 0 0;
}
h1, h2 {
font-weight: bold;
}
h1 {
font-size: large;
font-weight: bold;
margin : 10px auto;
font-size: larger;
text-align: center;
}
.menu-row h2 {
font-size: medium;
padding: 10px;
cursor: pointer;
border: 2px solid darkgrey;
margin: 0 0 10px 0;
}
sidebar {
flex: auto;
padding: 10px;
padding: 0 10px;
}
input[type="button"] {
min-width: 60px;
padding: 5px;
font-weight: bold;
margin-right: 10px;
}
.form-field {
@ -48,3 +60,7 @@ label, .form-field label {
#main {
flex: 4;
}
#container {
display: flex;
}