Compare commits

...

46 Commits

Author SHA1 Message Date
f2e59bbdce Merge pull request 'v0.9.1' (#14) from dev into master
Reviewed-on: #14
2024-04-29 13:29:52 +02:00
b195b89fa9 fix: format, lint, props warning 2024-04-27 16:04:59 +02:00
56d00d9b69 fix: wrong symbol for next 2024-04-27 15:53:13 +02:00
795d852a10 feat: button stylin 2024-04-27 15:24:57 +02:00
2b1ebea049 feat: utf symbols 2024-04-27 14:55:33 +02:00
b68457c9a1 fix: added class for css styling (rather than id selector) 2024-04-27 14:40:13 +02:00
69fad85b45 feat: title in reset menu if mobile viewport 2024-04-27 14:30:45 +02:00
bc19ee1848 feat: extract all css into dedicated file 2024-04-27 13:42:43 +02:00
b77a429568 feat: bump dependencies version 2024-04-27 13:09:23 +02:00
6ecfded408 fix: very minor css and style stuffs 2024-04-27 13:09:09 +02:00
7224d8fb66 fix: typo + shouldn't be scoped anyway 2024-04-27 13:07:03 +02:00
f5f0ee07a4 feat: default value for loop to true 2024-04-27 12:13:08 +02:00
e945efaa3c fix: fix canvas height setting input 2024-04-27 11:55:22 +02:00
263e8ba535 Merge pull request 'feat (canvas): OffscreenCanvas fallback' (#12) from dev into master
Reviewed-on: #12
2023-06-05 09:33:18 +02:00
11071a5972 feat (canvas): OffscreenCanvas fallback 2023-06-05 09:29:46 +02:00
0f31f2556c Merge pull request 'fix evolve 2D' (#11) from dev into master
Reviewed-on: #11
2022-12-29 17:21:47 +01:00
ffa54ab899 Merge branch 'master' into dev 2022-12-29 17:21:39 +01:00
71f8a9c8b5 draw then store 2022-12-29 17:19:26 +01:00
9951ada7b3 evolve1d refacto, evolve2d repair 2022-12-29 17:10:43 +01:00
2b042f89be Merge branch 'dev' of dev.ariona.fr:gator/explorata into dev 2022-12-27 13:04:38 +01:00
8a7d8ec24c test file for core 2022-12-27 11:24:46 +01:00
e718fbfe80 bitwise operations 2022-12-27 11:24:14 +01:00
c592f523af rules 110, 184 2022-12-26 23:05:21 +01:00
f887b7bd18 Merge pull request 'api redesign' (#10) from dev into master
Reviewed-on: #10
2022-12-26 18:14:48 +01:00
96daec016f Merge remote-tracking branch 'origin/master' into dev 2022-12-26 18:14:26 +01:00
cc2c002a4a missing stop. toggles 2022-12-26 17:20:03 +01:00
89c2a79337 render picture : ratio and resizing to board 2022-12-26 15:50:02 +01:00
a3102c895c renderer module 2022-12-23 16:41:03 +01:00
faee8f61d5 board module 2022-12-23 12:32:59 +01:00
f351f37c46 unit test dependancies 2022-12-23 12:27:58 +01:00
495313a5c3 Merge pull request 'Vue composition API' (#9) from dev into master
Reviewed-on: #9
2022-12-22 00:02:26 +01:00
e4f8b8d6bc Merge branch 'master' into dev 2022-12-22 00:02:15 +01:00
2858eb2d27 function call typo 2022-12-21 23:53:27 +01:00
7c9d7d2d5b switching to composition API 2022-12-21 23:45:22 +01:00
1644c8c5ce Merge pull request 'new render method' (#8) from dev into master
Reviewed-on: #8
2022-12-20 16:35:50 +01:00
c825752405 refresh rate, some attempts at optimizing 2022-12-20 16:27:04 +01:00
44d749ac4e restore color selection 2022-12-20 12:32:01 +01:00
7500c6ac1f rule 30 2022-12-20 12:30:58 +01:00
99a54eeb13 wip picture to board 2022-12-20 11:59:48 +01:00
75caa2054f typo 2022-12-20 10:47:32 +01:00
e43bd48794 boardToPic 2022-12-19 22:53:48 +01:00
a402739b97 loop and next button for manual control 2022-12-19 21:49:57 +01:00
cc4a7b08b3 wip optimizing render 2022-12-19 16:00:38 +01:00
61846b88a5 high life rule 2022-12-18 13:50:21 +01:00
1249ba95d7 Merge pull request 'picture to initial state' (#7) from dev into master
Reviewed-on: #7
2022-12-18 12:24:25 +01:00
bce0f39aff styling 2022-12-18 12:23:47 +01:00
25 changed files with 3532 additions and 2683 deletions

View File

@ -44,3 +44,4 @@ See [Configuration Reference](https://vitejs.dev/guide/).
- https://en.wikipedia.org/wiki/Hashlife - https://en.wikipedia.org/wiki/Hashlife
- https://plato.stanford.edu/entries/cellular-automata/supplement.html - https://plato.stanford.edu/entries/cellular-automata/supplement.html
- https://www.conwaylife.com/wiki/Cellular_automaton - https://www.conwaylife.com/wiki/Cellular_automaton
- https://conwaylife.com/

4160
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -7,20 +7,25 @@
"build": "vite build", "build": "vite build",
"serve": "vite preview", "serve": "vite preview",
"lint": "eslint --ext .js,.vue --ignore-path .gitignore --fix src", "lint": "eslint --ext .js,.vue --ignore-path .gitignore --fix src",
"format": "prettier . --write" "format": "prettier . --write",
"coverage": "vitest run --coverage",
"test": "vitest"
}, },
"dependencies": { "dependencies": {
"@vitejs/plugin-vue": "^3.2.0", "@vitejs/plugin-vue": "3.2.0",
"install": "^0.13.0", "install": "0.13.0",
"pinia": "^2.0.27", "pinia": "2.0.27",
"vite": "^3.2.4", "vite": "^3.2.10",
"vue": "3.2" "vue": "3.2"
}, },
"devDependencies": { "devDependencies": {
"@testing-library/vue": "^6.6.1",
"eslint": "^8.28.0", "eslint": "^8.28.0",
"eslint-config-prettier": "^8.5.0", "eslint-config-prettier": "^8.5.0",
"eslint-plugin-vue": "^9.8.0", "eslint-plugin-vue": "^9.8.0",
"prettier": "2.8.0" "happy-dom": "^8.1.1",
"prettier": "2.8.0",
"vitest": "^0.26.2"
}, },
"eslintConfig": { "eslintConfig": {
"root": true, "root": true,

View File

@ -1,154 +1,57 @@
<template> <script setup>
<div id="main">
<h1 id="main-title">
<span id="burger-toggle" @click="toggleMainMenu">{{
mainMenu == true ? "▼" : "☰"
}}</span>
Cellular Automata Explorer
</h1>
<div id="container">
<MainMenu v-if="mainMenu || windowWidth >= 800" />
<CanvasBoard />
</div>
<MenuReset row-title="" />
</div>
</template>
<script>
import MainMenu from "./components/MainMenu.vue"; import MainMenu from "./components/MainMenu.vue";
import CanvasBoard from "./components/CanvasBoard.vue"; import CanvasBoard from "./components/CanvasBoard.vue";
import MenuReset from "./components/MenuReset.vue"; import MenuReset from "./components/MenuReset.vue";
import { mapState, mapWritableState, mapActions } from "pinia";
import { globalStore } from "./stores/index.js"; import { globalStore } from "./stores/index.js";
import { nextTick, onBeforeUnmount, onMounted, ref } from "vue";
export default { const store = globalStore();
name: "App",
components: { const windowWidth = ref(window.innerWidth);
MainMenu,
MenuReset, const toggleMainMenu = () => {
CanvasBoard, store.setMainMenu(!store.mainMenu);
},
data() {
return {
windowWidth: window.innerWidth,
}; };
},
computed: { const onResize = () => {
...mapState(globalStore, ["mainMenu", "activeSubMenu"]), nextTick(() => {
...mapWritableState(globalStore, ["canvasWidth", "canvasHeight"]), windowWidth.value = window.innerWidth;
}, // TODO: changing the width will clear the canvas. Find something else
mounted() { store.renderer.resize(window.innerWidth, window.innerHeight);
this.$nextTick(() => { store.setBoardWidth();
window.addEventListener("resize", this.onResize); store.setBoardHeight();
}); });
},
beforeUnmount() {
window.removeEventListener("resize", this.onResize);
},
methods: {
...mapActions(globalStore, [
"setBoardWidth",
"setBoardHeight",
"setMainMenu",
]),
toggleMainMenu() {
this.setMainMenu(!this.mainMenu);
},
onResize() {
this.$nextTick(() => {
this.windowWidth = window.innerWidth;
this.canvasWidth = window.innerWidth;
this.canvasHeight = window.innerHeight;
this.setBoardWidth();
this.setBoardHeight();
});
},
},
}; };
onMounted(() => {
nextTick(() => {
window.addEventListener("resize", onResize);
});
});
onBeforeUnmount(() => {
window.removeEventListener("resize", onResize);
});
</script> </script>
<style scope> <template>
:root { <main>
--dark1: #000000; <h1
--dark2: #333333; v-if="store.mainMenu || windowWidth <= 800"
--dark3: #666666; id="main-title"
--light1: #999999; class="main-title"
--light2: #cccccc; >
--light3: #eeeeee; <span id="burger-toggle" class="burger-toggle" @click="toggleMainMenu">
} {{ store.mainMenu == true ? "▼" : "☰" }}
</span>
<span>Cellular Automata Explorer</span>
</h1>
<div id="container" class="container">
<MainMenu v-if="store.mainMenu || windowWidth >= 800" class="main-menu" />
<CanvasBoard />
</div>
<MenuReset :window-width="windowWidth" />
</main>
</template>
#app { <style src="./assets/css/main.css"></style>
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
/* color: #2c3e50; */
}
* {
margin: 0;
padding: 0;
}
body {
background: var(--dark1);
color: var(--light3);
font-family: Courier New;
}
canvas {
flex: auto;
background: rgb(0, 0, 0);
background: linear-gradient(
90deg,
rgba(0, 0, 0, 1) 0%,
rgba(131, 131, 131, 1) 52%,
rgba(0, 0, 0, 1) 100%
);
}
h1,
h2 {
font-weight: bold;
}
h1 {
margin: 10px auto;
font-size: larger;
text-transform: uppercase;
}
#container {
display: flex;
height: calc(100vh - 100px);
overflow: hidden;
flex-direction: column;
}
#burger-toggle {
display: none;
cursor: pointer;
font-size: 1.5em;
vertical-align: middle;
color: var(--light2);
}
@media screen and (max-width: 800px) {
h1 {
font-size: medium;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 10px;
}
#burger-toggle {
display: inline;
}
#main-menu {
background: var(--dark2);
margin: 0 auto;
}
}
</style>

228
src/assets/css/main.css Normal file
View File

@ -0,0 +1,228 @@
:root {
--dark1: #000000;
--dark2: #333333;
--dark3: #666666;
--light1: #999999;
--light2: #cccccc;
--light3: #eeeeee;
}
* {
margin: 0;
padding: 0;
}
body {
background: var(--dark1);
color: var(--light3);
/* font-family: Courier New; */
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
}
canvas {
flex: auto;
background: linear-gradient(
90deg,
rgba(0, 0, 0, 1) 0%,
rgba(131, 131, 131, 1) 52%,
rgba(0, 0, 0, 1) 100%
);
}
h1,
h2,
.desktop-title {
font-weight: bold;
}
h1,
.desktop-title {
font-size: larger;
text-transform: uppercase;
}
.container {
display: flex;
height: calc(100vh - 100px);
overflow: hidden;
flex-direction: column;
}
.burger-toggle {
display: none;
cursor: pointer;
font-size: 1.5em;
vertical-align: middle;
color: var(--light2);
}
a {
font-weight: bold;
border: 1px solid white;
padding: 2px;
}
h2:hover {
cursor: pointer;
color: var(--light2);
}
select {
margin-top: 10px;
padding: 5px;
}
input[type="number"] {
max-width: 100%;
height: 100%;
}
input[type="button"] {
min-width: 40px;
min-height: 40px;
margin: 0 5px;
font-weight: bold;
line-height: 1.5em;
border-radius: 0;
outline: none;
border: none;
font-size: 1.1em;
background: var(--light2);
}
input[type="button"]:hover {
background: var(--light3);
}
.form-field {
display: flex;
margin: 10px;
justify-content: space-between;
}
.menu-row {
flex: 1;
position: relative;
}
.menu-row h2 {
font-size: medium;
padding: 10px;
cursor: pointer;
border-bottom: 1px solid var(--dark3);
border-top: 1px solid var(--dark3);
}
.menu-row a {
color: white;
font-weight: bold;
text-decoration: none;
font-size: small;
}
.menu-row-content {
position: absolute;
background: var(--dark1);
width: 100%;
overflow: scroll;
}
label,
.form-field label {
margin-right: 10px;
font-weight: bold;
}
.canvas-board {
flex: 1;
margin: 0 auto;
}
.main-menu {
display: flex;
flex-direction: row;
width: 100%;
flex: 1;
}
/* Hide scrollbar for Chrome, Safari and Opera */
.main-menu::-webkit-scrollbar {
display: none;
}
/* Hide scrollbar for IE, Edge and Firefox */
.main-menu {
-ms-overflow-style: none; /* IE and Edge */
scrollbar-width: none; /* Firefox */
}
.reset-menu {
display: flex;
justify-content: space-between;
padding: 10px;
vertical-align: center;
}
.next,
.stop,
.reset {
display: inline-block;
vertical-align: bottom;
}
.reset-menu .loop {
padding: 5px;
display: inline-block;
}
@media screen and (max-width: 800px) {
h1 {
font-size: medium;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 10px;
}
.burger-toggle {
display: inline;
}
.main-menu {
background: var(--dark2);
margin: 0 auto;
flex-direction: column;
position: absolute;
}
.menu-row {
margin: 0 auto;
width: 100%;
}
.menu-row h2,
.form-field {
margin: 0;
}
.menu-row h2 {
border-bottom: 1px solid var(--dark3);
border-top: none;
}
.form-field {
padding: 10px;
}
.menu-row-content {
position: relative;
width: 100%;
}
.reset-menu {
justify-content: flex-end;
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.7 KiB

View File

View File

@ -1,240 +1,194 @@
<template> <script setup>
<canvas import { onMounted, watch } from "vue";
id="board-canvas"
ref="board-canvas"
:width="canvasWidth"
:height="canvasHeight"
/>
<canvas
id="work-canvas"
ref="work-canvas"
:width="canvasWidth"
:height="canvasHeight"
/>
</template>
<script>
import { mapActions, mapState, mapWritableState } from "pinia";
import { globalStore } from "../stores/index.js"; import { globalStore } from "../stores/index.js";
import { import {
create1dState,
create1dStateOneCell,
create2dState,
createBoard, createBoard,
conwayRules, conwayRules,
overpopulationRules, overpopulationRules,
lonelinessRules, lonelinessRules,
threebornRules, threebornRules,
highLifeRules,
servietteRules,
evolve2d, evolve2d,
} from "../modules/automata.js"; } from "../modules/core.js";
import { getRandomInt, sleep } from "../modules/common.js"; import {
import { picToBoard, picToBlackAndWhite } from "../modules/picture.js"; create1dInitialState,
create2dRandomGrid,
} from "../modules/board.js";
import { picToBoard } from "../modules/picture.js";
export default { const store = globalStore();
name: "CanvasBoard", const available2dRules = {
data() {
return {
canvas: null,
workCanvas: null,
workCtx: null,
ctx: null,
available2dRules: {
conway: conwayRules, conway: conwayRules,
overpopulation: overpopulationRules, overpopulation: overpopulationRules,
loneliness: lonelinessRules, loneliness: lonelinessRules,
threeborn: threebornRules, threeborn: threebornRules,
}, highlife: highLifeRules,
serviette: servietteRules,
}; };
},
computed: {
...mapState(globalStore, {
cellProperties: "cellProperties",
ruleset: "ruleset1d",
refreshRate: "refreshRate",
initial1dState: "initial1dState",
drawingDirection: "drawingDirection",
canDraw: "canDraw",
getDraw1d: "draw1d",
getDraw2d: "draw2d",
getDraw2dLast: "draw2dLast",
getDraw2dPicture: "draw2dpicture",
boardWidth: "boardWidth",
boardHeight: "boardHeight",
picture: "picture",
selected2dRules: "selected2dRules",
}),
...mapWritableState(globalStore, {
lastBoard: "lastBoard",
canvasWidth: "canvasWidth",
canvasHeight: "canvasHeight",
getReset: "reset",
}),
// used to determine the dimensions of the board // used to determine the dimensions of the board
max() { // TODO: should be a Board method
return Math.max(this.boardWidth, this.boardHeight); const max = () => {
}, return Math.max(store.board.width, store.board.height);
}, };
watch: {
getDraw1d(value) { const selectedRules = () => {
if (value == true) this.draw1d(); return available2dRules[store.selected2dRules.id];
}, };
getDraw2d(value) {
if (value == true) this.draw2dNew(); watch(
}, () => store.draw1d,
getDraw2dLast(value) { (value) => {
if (value == true) this.draw2dLast(); if (value == true) draw1d();
}, }
getDraw2dPicture(value) { );
if (value == true) this.draw2dPicture();
}, watch(
getReset(value) { () => store.draw2d,
if (value == true) this.reset(); (value) => {
}, if (value == true) draw2dNew();
}, }
mounted() { );
this.canvas = Object.freeze(document.getElementById("board-canvas"));
this.workCanvas = Object.freeze(document.getElementById("work-canvas")); watch(
this.ctx = this.canvas.getContext("2d", { willReadFrequently: true }); () => store.draw2dLast,
this.workCtx = this.workCanvas.getContext("2d", { async (value) => {
if (value == true) await draw2dLast();
}
);
watch(
() => store.draw2dpicture,
(value) => {
if (value == true) draw2dPicture();
}
);
watch(
() => store.reset,
(value) => {
if (value == true) reset();
}
);
onMounted(() => {
// TODO : butt ugly.
const canvas = document.getElementById("board-canvas");
store.renderer.width = canvas.parentElement.clientWidth;
store.renderer.height = canvas.parentElement.clientHeight;
store.renderer.canvas = canvas;
store.renderer.ctx = store.renderer.canvas.getContext("2d", {
willReadFrequently: true, willReadFrequently: true,
}); });
this.canvasWidth = this.canvas.parentElement.clientWidth; if (typeof OffscreenCanvas != "undefined") {
this.canvasHeight = this.canvas.parentElement.clientHeight; store.renderer.workCanvas = new OffscreenCanvas(
this.setBoardWidth(); canvas.parentElement.clientWidth,
this.setBoardHeight(); canvas.parentElement.clientHeight
}, );
methods: { }
...mapActions(globalStore, [ // https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas/OffscreenCanvas#Browser_compatibility
"toggleStop", // Fallback for when offscreenCanvas is unsupported or disabled (Firefox < 44, default for Firefox?)
"setBoardWidth", else {
"setBoardHeight", store.renderer.workCanvas = document.createElement("canvas");
]), store.renderer.workCanvas.width = canvas.parentElement.clientWidth;
store.renderer.workCanvas.height = canvas.parentElement.clientHeight;
}
store.renderer.workCtx = store.renderer.workCanvas.getContext("2d", {
willReadFrequently: true,
});
store.setBoardWidth();
store.setBoardHeight();
});
// draws the board on the canvas // draws the board on the canvas
drawCanvas(board) { const drawCanvas = async (board) => {
const props = this.cellProperties; store.renderer.render(board);
board.map((row, y) => {
const d = props.size;
return row.map((cell, x) => {
this.ctx.fillStyle = (() => {
if (cell === 1) return props.liveColor;
return props.deadColor;
})();
if (this.drawingDirection === "x")
this.ctx.fillRect(y * d, x * d, d, d);
else this.ctx.fillRect(x * d, y * d, d, d);
return cell;
});
});
},
// create a first state, either a single living cell
// at the center or random ones
compute1dInitialState() {
if (this.initial1dState === "onecell")
return create1dStateOneCell(this.boardWidth);
return create1dState(this.boardWidth, getRandomInt, [0, 2]);
},
// draw elementary automaton on the canvas based on selected ruleset
draw1d() {
const initialState = this.compute1dInitialState();
const board = createBoard(initialState, this.ruleset.rules, this.max);
this.lastBoard = Object.freeze(board);
this.drawCanvas(this.lastBoard);
this.toggleStop();
},
// draw 2D automaton on the canvas in a loop
draw2d(board) {
if (!this.canDraw) return;
const draw2dNext = async (b) => {
if (!this.canDraw) return;
const newBoard = evolve2d(
b,
this.available2dRules[this.selected2dRules.id]
);
this.drawCanvas(b, this.cellProperties);
this.lastBoard = Object.freeze(newBoard);
await sleep(this.refreshRate);
draw2dNext(newBoard);
}; };
return draw2dNext(board);
}, // draw elementary automaton on the canvas based on selected ruleset
// draw 2d automaton from a new state const draw1d = () => {
draw2dNew() { const initialState = create1dInitialState(
const initialState = create2dState( store.board,
this.boardWidth, store.initial1dState
this.boardHeight,
getRandomInt,
[0, 2]
); );
const board = evolve2d(initialState, conwayRules); const board = createBoard(initialState, store.ruleset1d.rules, max());
this.lastBoard = Object.freeze(board); store.board.grid = Object.freeze(board);
this.draw2d(board); drawCanvas(store.board);
}, store.toggleStop();
};
// draw 2D automaton on the canvas in a loop
const draw2d = (board) => {
drawCanvas(store.board);
const newBoard = Object.freeze(evolve2d(board.grid, selectedRules()));
if (store.board.grid == newBoard) store.toggleStop();
store.board.grid = newBoard;
};
// draw 2d automaton in a loop, starting from passed state
const draw2dNext = async (board) => {
setTimeout(() => {
if (!store.canDraw) return;
draw2d(board);
return draw2dNext(store.board);
}, store.renderer.refreshRate);
};
// draw 2d automaton from a new state
const draw2dNew = async () => {
if (!store.canDraw) return;
const initialGrid = create2dRandomGrid(
store.board.width,
store.board.height
);
store.board.grid = Object.freeze(evolve2d(initialGrid, selectedRules()));
if (store.loop) return draw2dNext(store.board);
else draw2d(store.board);
store.toggleStop();
};
// draw 2d automaton from the last known generated board // draw 2d automaton from the last known generated board
draw2dLast() { const draw2dLast = async () => {
if (this.lastBoard != undefined) this.draw2d(this.lastBoard); if (!store.canDraw) return;
}, if (store.loop) return draw2dNext(store.board);
else draw2d(store.board);
store.toggleStop();
};
// draw 2d automaton from an uploaded picture. // draw 2d automaton from an uploaded picture.
// use the picture representation as an initial state // use the picture representation as an initial state
draw2dPicture() { const draw2dPicture = async () => {
// get image data by drawing it on a work canvas store.renderer.renderImage(
this.workCtx.drawImage( store.picture,
this.picture, store.renderer.ctx,
0, store.renderer.width,
0, store.renderer.height
this.canvasWidth,
this.canvasHeight
); );
const imgData = this.workCtx.getImageData( const resized = store.renderer.renderImage(
0, store.picture,
0, store.renderer.workCtx,
this.canvasWidth, store.board.width,
this.canvasHeight store.board.height
); );
const newBoard = picToBoard(resized.data, store.board);
store.board.grid = Object.freeze(newBoard);
store.toggleStop();
};
// convert the image to black and white const reset = () => {
const black = picToBlackAndWhite( store.toggleStop();
imgData.data, store.board.grid = null;
this.canvasWidth, store.renderer.reset();
this.canvasHeight store.toggleReset();
);
// draw it back on the canvas
this.ctx.putImageData(black, 0, 0);
// draw the image back on the work canvas with the dimensions of the board
this.workCtx.drawImage(
this.picture,
0,
0,
this.boardWidth,
this.boardHeight
);
const resized = this.workCtx.getImageData(
0,
0,
this.boardWidth,
this.boardHeight
);
// convert the resized image into a 2D board of boolean based on pixel value
this.lastBoard = Object.freeze(
picToBoard(resized.data, this.boardWidth, this.boardHeight)
);
this.toggleStop();
},
// stop drawing routines and clear the canvas
reset() {
this.toggleStop();
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.getReset = 0;
},
},
}; };
</script> </script>
<style> <template>
#canvas-board { <canvas
flex: 1; id="board-canvas"
margin: 0 auto; ref="board-canvas"
} class="board-canvas"
</style> :width="store.renderer.width"
:height="store.renderer.height"
/>
</template>

View File

@ -7,45 +7,9 @@
</div> </div>
</template> </template>
<script> <script setup>
import MenuCellProperties from "./MenuCellProperties.vue"; import MenuCellProperties from "./MenuCellProperties.vue";
import MenuGeneralOptions from "./MenuGeneralOptions.vue"; import MenuGeneralOptions from "./MenuGeneralOptions.vue";
import MenuElementaryCA from "./MenuElementaryCA.vue"; import MenuElementaryCA from "./MenuElementaryCA.vue";
import Menu2dCA from "./Menu2dCA.vue"; import Menu2dCA from "./Menu2dCA.vue";
export default {
name: "MainMenu",
components: {
MenuCellProperties,
MenuGeneralOptions,
MenuElementaryCA,
Menu2dCA,
},
};
</script> </script>
<style>
#main-menu {
display: flex;
flex-direction: row;
width: 100%;
flex: 1;
}
/* Hide scrollbar for Chrome, Safari and Opera */
#main-menu::-webkit-scrollbar {
display: none;
}
/* Hide scrollbar for IE, Edge and Firefox */
#main-menu {
-ms-overflow-style: none; /* IE and Edge */
scrollbar-width: none; /* Firefox */
}
@media screen and (max-width: 800px) {
#main-menu {
flex-direction: column;
position: absolute;
}
}
</style>

View File

@ -1,3 +1,48 @@
<script setup>
import MenuRow from "./MenuRow.vue";
import { globalStore } from "../stores/index.js";
import { preset2dRules } from "../modules/preset.js";
import { shallowRef } from "vue";
const store = globalStore();
const uploadedPicture = shallowRef(null);
const img = new Image();
// TODO : I have no idea why this works
const preparePicture = () => {
const file = uploadedPicture.value.files[0];
if (!file || file.type.indexOf("image/") !== 0) return;
if (FileReader && file) {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = (event) => {
img.onload = () => {
store.picture.width = img.width;
store.picture.height = img.height;
};
store.picture.src = event.target.result;
store.toggle2dDrawFromPicture();
};
reader.onerror = () => {
console.log(reader.error);
};
}
};
const update2dRules = (event) => {
const elem = event.target;
const id = elem.value;
const newRuleset = preset2dRules.find((ruleset) => {
return ruleset.id === id;
});
store.selected2dRules = newRuleset;
};
</script>
<template> <template>
<MenuRow row-title="2D Cellular Automaton"> <MenuRow row-title="2D Cellular Automaton">
<div class="form-field"> <div class="form-field">
@ -5,17 +50,17 @@
<input <input
type="button" type="button"
name="start2d" name="start2d"
value="start" value=""
@click="toggleDraw2d()" @click="store.toggleDraw2d()"
/> />
</div> </div>
<div class="form-field"> <div class="form-field">
<label>Start from last result</label> <label>Start from last result</label>
<input type="button" value="start" @click="toggleDraw2dLast()" /> <input type="button" value="▶" @click="store.toggleDraw2dLast()" />
</div> </div>
<div class="form-field"> <div class="form-field">
<label>Start from picture</label><br /> <label>Start from picture</label><br />
<input type="file" @change="preparePicture" /> <input ref="uploadedPicture" type="file" @change="preparePicture" />
</div> </div>
<div class="form-field"> <div class="form-field">
<label> <label>
@ -23,7 +68,7 @@
<br /> <br />
<select <select
name="preset2dRules" name="preset2dRules"
:value="selected2dRules.id" :value="store.selected2dRules.id"
@input="update2dRules" @input="update2dRules"
> >
<option <option
@ -38,59 +83,3 @@
</div> </div>
</MenuRow> </MenuRow>
</template> </template>
<script>
import MenuRow from "./MenuRow.vue";
import { mapActions, mapWritableState } from "pinia";
import { globalStore } from "../stores/index.js";
import { preset2dRules } from "../modules/preset.js";
export default {
name: "Menu2dCA",
components: {
MenuRow,
},
data() {
return {
uploadedFile: "",
preset2dRules: preset2dRules,
};
},
computed: {
...mapWritableState(globalStore, ["picture", "selected2dRules"]),
},
methods: {
...mapActions(globalStore, [
"toggleDraw2dLast",
"toggleDraw2d",
"toggle2dDrawFromPicture",
]),
preparePicture(event) {
const files = event.target.files;
this.picture = new Image();
this.picture.width = this.canvasWidth;
if (FileReader && files && files.length) {
const reader = new FileReader();
reader.onload = () => {
this.picture.src = Object.freeze(reader.result);
this.toggle2dDrawFromPicture();
};
reader.onerror = () => {
console.log(reader.error);
};
reader.readAsDataURL(files[0]);
}
},
update2dRules(event) {
const elem = event.target;
const id = elem.value;
const newRuleset = this.preset2dRules.find((ruleset) => {
return ruleset.id === id;
});
this.selected2dRules = newRuleset;
},
},
};
</script>

View File

@ -1,3 +1,21 @@
<script setup>
import { globalStore } from "../stores/index.js";
import MenuRow from "./MenuRow.vue";
const store = globalStore();
const updateCellProperties = (event) => {
const { name, value } = event.target;
store.setCellProperties(name, value);
store.setBoardWidth();
store.setBoardHeight();
};
const switchColor = () => {
store.switchColor();
};
</script>
<template> <template>
<MenuRow row-title="Cell Properties"> <MenuRow row-title="Cell Properties">
<form> <form>
@ -6,7 +24,7 @@
<input <input
name="liveColor" name="liveColor"
type="color" type="color"
:value="cellProperties.liveColor" :value="store.board.cellProperties.liveColor"
@input="updateCellProperties" @input="updateCellProperties"
/> />
</div> </div>
@ -15,7 +33,7 @@
<input <input
name="deadColor" name="deadColor"
type="color" type="color"
:value="cellProperties.deadColor" :value="store.board.cellProperties.deadColor"
@input="updateCellProperties" @input="updateCellProperties"
/> />
</div> </div>
@ -28,50 +46,10 @@
name="size" name="size"
type="number" type="number"
min="1" min="1"
:value="cellProperties.size" :value="store.board.cellProperties.size"
@click="updateCellProperties" @click="updateCellProperties"
/> />
</div> </div>
</form> </form>
</MenuRow> </MenuRow>
</template> </template>
<script>
import { mapActions, mapWritableState } from "pinia";
import { globalStore } from "../stores/index.js";
import MenuRow from "./MenuRow.vue";
export default {
name: "MenuCellProperties",
components: {
MenuRow,
},
computed: {
...mapWritableState(globalStore, ["cellProperties"]),
},
methods: {
...mapActions(globalStore, ["setBoardHeight", "setBoardWidth"]),
getCellProperties(event) {
const elem = event.target;
const prop = this.cellProperties;
return prop[elem.name];
},
updateCellProperties(event) {
const elem = event.target;
this.cellProperties[elem.name] = elem.value;
this.setBoardWidth();
this.setBoardHeight();
},
switchColor() {
[this.cellProperties["liveColor"], this.cellProperties["deadColor"]] = [
this.cellProperties["deadColor"],
this.cellProperties["liveColor"],
];
},
},
};
</script>
<style scoped>
a:hover {
cursor: pointer;
}
</style>

View File

@ -1,3 +1,36 @@
<script setup>
import { presetRuleset, initialStates } from "../modules/preset.js";
import { globalStore } from "../stores/index.js";
import MenuRow from "./MenuRow.vue";
const store = globalStore();
const copyRuleset = () => {
const newRuleset = JSON.stringify(store.ruleset1d);
navigator.clipboard.writeText(newRuleset);
};
const updateSingleRule = (event) => {
const elem = event.target;
const value = elem.checked ? 1 : 0;
store.ruleset1d.rules[elem.name] = value;
};
const updateRuleset = (event) => {
const elem = event.target;
const name = elem.value;
const newRuleset = presetRuleset.find((ruleset) => {
return ruleset.name === name;
});
store.ruleset1d = newRuleset;
};
const updateInitialState = (event) => {
const elem = event.target;
store.initial1dState = elem.value;
};
</script>
<template> <template>
<MenuRow row-title="Elementary Automaton"> <MenuRow row-title="Elementary Automaton">
<form> <form>
@ -5,8 +38,8 @@
<input <input
type="button" type="button"
name="start" name="start"
value="start" value=""
@click="toggleDraw1d()" @click="store.toggleDraw1d()"
/> />
</div> </div>
<div class="form-field"> <div class="form-field">
@ -15,7 +48,7 @@
<br /> <br />
<select <select
name="initialStates" name="initialStates"
:value="initialState" :value="store.initial1dState"
@input="updateInitialState" @input="updateInitialState"
> >
<option <option
@ -37,7 +70,7 @@
<br /> <br />
<select <select
name="ruleset-elementary" name="ruleset-elementary"
:value="ruleset.name" :value="store.ruleset1d.name"
@input="updateRuleset" @input="updateRuleset"
> >
<option <option
@ -54,7 +87,7 @@
<a style="cursor: pointer" @click="copyRuleset">copy rules</a> <a style="cursor: pointer" @click="copyRuleset">copy rules</a>
</div> </div>
<div <div
v-for="(rule, name, index) in ruleset.rules" v-for="(rule, name, index) in store.ruleset1d.rules"
:key="'rule-' + index" :key="'rule-' + index"
class="form-field" class="form-field"
> >
@ -72,74 +105,3 @@
</form> </form>
</MenuRow> </MenuRow>
</template> </template>
<script>
import { mapActions, mapWritableState } from "pinia";
import { presetRuleset, initialStates } from "../modules/preset.js";
import { globalStore } from "../stores/index.js";
import MenuRow from "./MenuRow.vue";
export default {
name: "MenuElementaryCA",
components: {
MenuRow,
},
data() {
return {
presetRuleset: presetRuleset,
initialStates: initialStates,
};
},
computed: {
...mapWritableState(globalStore, {
initialState: "initial1dState",
ruleset: "ruleset1d",
}),
rules1dFileName() {
// TODO: broken
return (
Object.keys(this.ruleset)
.map((index) => {
return this.ruleset[index];
})
.join("_") + ".json"
);
},
},
methods: {
...mapActions(globalStore, ["toggleDraw1d"]),
copyRuleset() {
const newRuleset = JSON.stringify(this.ruleset);
navigator.clipboard.writeText(newRuleset);
},
isCurrentPreset(event) {
const elem = event.target;
return this.initialState === elem.value;
},
updateSingleRule(event) {
const elem = event.target;
const value = elem.checked ? 1 : 0;
this.ruleset.rules[elem.name] = value;
},
updateRuleset(event) {
const elem = event.target;
const name = elem.value;
const newRuleset = this.presetRuleset.find((ruleset) => {
return ruleset.name === name;
});
this.ruleset = newRuleset;
},
updateInitialState(event) {
const elem = event.target;
this.initialState = elem.value;
},
},
};
</script>
<style>
.menu-row a {
color: white;
font-weight: bold;
text-decoration: none;
font-size: small;
}
</style>

View File

@ -1,3 +1,31 @@
<script setup>
import { globalStore } from "../stores/index.js";
import MenuRow from "./MenuRow.vue";
const store = globalStore();
const updateCanvasHeight = (event) => {
const elem = event.target;
store.renderer.resize(store.renderer.width, elem.value);
};
const updateCanvasWidth = (event) => {
const elem = event.target;
store.renderer.resize(elem.value, store.renderer.height);
};
const updateRefreshRate = (event) => {
const elem = event.target;
store.renderer.refreshRate = elem.value;
};
const updateDrawingDirection = (event) => {
const elem = event.target;
const value = elem.checked ? "x" : "y";
store.drawingDirection = value;
};
</script>
<template> <template>
<MenuRow row-title="General Options"> <MenuRow row-title="General Options">
<form> <form>
@ -11,7 +39,7 @@
name="canvasWidth" name="canvasWidth"
type="number" type="number"
step="10" step="10"
:value="canvasWidth" :value="store.renderer.width"
@input="updateCanvasWidth" @input="updateCanvasWidth"
/> />
</div> </div>
@ -22,21 +50,19 @@
name="canvasHeight" name="canvasHeight"
type="number" type="number"
step="10" step="10"
:value="canvasHeight" :value="store.renderer.height"
@input="updateCanvasHeight" @input="updateCanvasHeight"
/> />
</div> </div>
<div class="form-field"> <div class="form-field">
<label>Refresh Rate (ms)</label> <label>Refresh Rate (ms)</label>
</div>
<div class="form-field">
<input <input
id="refreshRate" id="refreshRate"
name="refreshRate" name="refreshRate"
type="number" type="number"
min="100" min="100"
step="100" step="100"
:value="refreshRate" :value="store.renderer.refreshRate"
@input="updateRefreshRate" @input="updateRefreshRate"
/> />
</div> </div>
@ -45,8 +71,8 @@
>Invert Drawing Direction >Invert Drawing Direction
<input <input
type="checkbox" type="checkbox"
:checked="drawingDirection === 'x'" :checked="store.drawingDirection === 'x'"
:value="drawingDirection" :value="store.drawingDirection"
@input="updateDrawingDirection" @input="updateDrawingDirection"
/> />
</label> </label>
@ -54,42 +80,3 @@
</form> </form>
</MenuRow> </MenuRow>
</template> </template>
<script>
import { mapWritableState } from "pinia";
import { globalStore } from "../stores/index.js";
import MenuRow from "./MenuRow.vue";
export default {
name: "MenuGeneralOptions",
components: {
MenuRow,
},
computed: {
...mapWritableState(globalStore, [
"canvasWidth",
"canvasHeight",
"refreshRate",
"drawingDirection",
]),
},
methods: {
updateCanvasHeight: function (event) {
const elem = event.target;
this.canvasHeight = elem.value;
},
updateCanvasWidth: function (event) {
const elem = event.target;
this.canvasWidth = elem.value;
},
updateRefreshRate: function (event) {
const elem = event.target;
this.refreshRate = elem.value;
},
updateDrawingDirection: function (event) {
const elem = event.target;
const value = elem.checked ? "x" : "y";
this.drawingDirection = value;
},
},
};
</script>

View File

@ -1,36 +1,56 @@
<script setup>
import { globalStore } from "../stores/index.js";
import { defineProps } from "vue";
const props = defineProps(
{
windowWidth: {
type: Number,
default: 800
}
}
);
const store = globalStore();
</script>
<template> <template>
<div class="form-field"> <div class="reset-menu">
<div v-if="props.windowWidth >= 800" class="desktop-title">
Cellular Automata Explorer
</div>
<div class="reset-input">
<div class="loop">
<label>
loop
<input
:value="store.loop"
type="checkbox"
:checked="store.loop"
@input="store.toggleLoop()"
/>
</label>
</div>
<input
type="button"
name="next"
class="next"
value="⇨"
@click="store.toggleNext()"
/>
<input <input
type="button" type="button"
name="stop" name="stop"
class="stop" class="stop"
value="stop" value="⏹"
@click="toggleStop()" @click="store.toggleStop()"
/> />
<input <input
type="button" type="button"
name="reset" name="reset"
class="reset" class="reset"
value="reset" value="⌫"
@click="toggleReset()" @click="store.toggleReset()"
/> />
</div> </div>
</div>
</template> </template>
<script>
import { mapActions } from "pinia";
import { globalStore } from "../stores/index.js";
export default {
name: "MenuReset",
methods: {
...mapActions(globalStore, ["toggleReset", "toggleStop"]),
},
};
</script>
<style scoped>
.form-field {
display: flex;
margin: 5px;
justify-content: flex-end;
}
</style>

View File

@ -1,3 +1,44 @@
<script setup>
import { computed, defineProps, onBeforeUnmount, ref } from "vue";
import { globalStore } from "../stores/index.js";
const store = globalStore();
const props = defineProps({
rowTitle: {
type: String,
default: "",
},
});
const content = ref(null);
const isActive = computed(() => {
return props.rowTitle == store.activeSubMenu;
});
const storeActiveSubMenu = () => {
window.addEventListener("click", onWindowClick);
store.setActiveSubMenu(props.rowTitle);
};
// hides submenu when click is detected outside from it
const onWindowClick = (event) => {
const form = content.value;
if (form != null) {
if (!form.contains(event.target)) {
store.setActiveSubMenu("");
store.setMainMenu(false);
}
return;
}
};
onBeforeUnmount(() => {
window.removeEventListener("click", onWindowClick);
});
</script>
<template> <template>
<div class="menu-row"> <div class="menu-row">
<h2 :id="rowTitle" @click.stop="storeActiveSubMenu"> <h2 :id="rowTitle" @click.stop="storeActiveSubMenu">
@ -8,132 +49,3 @@
</div> </div>
</div> </div>
</template> </template>
<script>
import { mapActions, mapState } from "pinia";
import { globalStore } from "../stores/index.js";
export default {
name: "MenuRow",
props: {
rowTitle: {
type: String,
default: "",
},
},
computed: {
...mapState(globalStore, ["activeSubMenu"]),
isActive() {
return this.rowTitle == this.activeSubMenu;
},
},
beforeUnmount() {
window.removeEventListener("click", this.onWindowClick);
},
methods: {
...mapActions(globalStore, [
"setActiveSubMenu",
"toggleMainMenu",
"setMainMenu",
]),
onKeyDown: function (event) {
// escape
if (event.keyCode == 27) {
this.setActiveSubMenu("");
}
},
storeActiveSubMenu() {
window.addEventListener("click", this.onWindowClick);
this.setActiveSubMenu(this.rowTitle);
},
// hides submenu when click is detected outside from it
onWindowClick(event) {
const form = this.$refs.content;
if (form != null) {
if (!form.contains(event.target)) {
this.setActiveSubMenu("");
this.setMainMenu(false);
}
return;
}
},
},
};
</script>
<style>
.menu-row h2 {
font-size: medium;
padding: 10px;
cursor: pointer;
border-bottom: 1px solid var(--dark3);
border-top: 1px solid var(--dark3);
margin: 0 0 10px 0;
}
select {
margin-top: 10px;
padding: 5px;
}
input[type="button"] {
min-width: 60px;
padding: 5px;
font-weight: bold;
margin-right: 10px;
}
.form-field {
display: flex;
margin: 10px;
justify-content: space-between;
}
.menu-row {
flex: 1;
position: relative;
}
.menu-row-content {
position: absolute;
background: var(--dark1);
width: 100%;
}
label,
.form-field label {
margin-right: 10px;
font-weight: bold;
}
@media screen and (max-width: 800px) {
.menu-row {
margin: 0 auto;
width: 100%;
}
.menu-row h2,
.form-field {
margin: 0;
}
.menu-row h2 {
border-bottom: 1px solid var(--dark3);
border-top: none;
}
.form-field {
padding: 10px;
}
/* .menu-row:active .menu-row-content {
display: flex;
flex-direction: column;
height: 100%;
} */
.menu-row-content {
position: relative;
width: 100%;
}
}
</style>

View File

@ -1,95 +0,0 @@
const presetRuleset = [
{
name: "rule 73",
rules: {
100: 0,
101: 0,
110: 1,
111: 0,
"011": 1,
"010": 0,
"001": 0,
"000": 1,
},
},
{
name: "rule 86",
rules: {
100: 1,
101: 0,
110: 0,
111: 1,
"011": 0,
"010": 1,
"001": 0,
"000": 1,
},
},
{
name: "rule 90",
rules: {
100: 1,
101: 0,
110: 1,
111: 0,
"011": 0,
"010": 0,
"001": 1,
"000": 0,
},
},
{
name: "rule 45?",
rules: {
100: 0,
101: 0,
110: 1,
111: 0,
"011": 1,
"010": 0,
"001": 1,
"000": 1,
},
},
{
name: "rule 54?",
rules: {
100: 1,
101: 0,
110: 1,
111: 1,
"011": 0,
"010": 1,
"001": 1,
"000": 0,
},
},
{
name: "unknown rule",
rules: {
100: 0,
101: 0,
110: 0,
111: 1,
"011": 0,
"010": 0,
"001": 1,
"000": 1,
},
},
];
const initialStates = [
{
id: "onecell",
name: "One cell at center",
description: "State with a single cell in the middle",
},
{
id: "random",
name: "Random cell",
description: "State populated with random cells",
},
];
export { presetRuleset, initialStates };

28
src/modules/board.js Normal file
View File

@ -0,0 +1,28 @@
import { create2dState, create1dStateOneCell, create1dState } from "./core.js";
import { getRandomInt } from "./common.js";
function Board(width, height, grid = []) {
this.width = width;
this.height = height;
(this.cellProperties = {
size: 3,
liveColor: "#000000",
deadColor: "#F5F5F5",
}),
(this.grid = grid);
}
// create a first state, either a single living cell
// at the center or random ones
const create1dInitialState = (board, type = "onecell") => {
if (type === "onecell") return create1dStateOneCell(board.width);
return create1dState(board.width, getRandomInt, [0, 2]);
};
// initialize 2d board with random cells
const create2dRandomGrid = (width, height) => {
return create2dState(width, height, getRandomInt, [0, 2]);
};
export { Board, create1dInitialState, create2dRandomGrid };

View File

@ -1,22 +1,26 @@
// handles negative index and index bigger than its array length // core functions to generate initial states and evolve them
function guard(index, array) {
if (index > array.length - 1) return 0; // get the next evolution of a 1D CA initial state
if (index < 0) return array.length - 1; // buggy BUT produces interesting results
return index; // function evolve1d(state, rules) {
} // const sl = state.length - 1;
// return [
// rules[[state[sl - 1], state[sl], state[sl + 1]].join("")],
// ...state.map((_,x) => (rules[[state[x - 1], state[x], state[x + 1]].join("")])).slice(0, sl),
// rules[[state[0], state[1], state[2]].join("")]
// ]
// }
// get the next evolution of a 1D CA initial state // get the next evolution of a 1D CA initial state
function evolve1d(state, rules) { function evolve1d(state, rules) {
function getCell(index) { const sl = state.length - 1;
const safeIndex = guard(index, state); const edge1 = [state[sl - 2], state[sl - 1], state[sl]].join("");
return state[safeIndex]; const edge2 = [state[0], state[1], state[2]].join("");
} // normal case (3 neighbor cells)
const newState = state.map((_, x) => { const center = state
const cells = [getCell(x - 1), getCell(x), getCell(x + 1)]; .map((_, x) => rules[[state[x - 1], state[x], state[x + 1]].join("")])
return rules[cells.join("")]; .slice(1, sl);
}); return [rules[edge1], ...center, rules[edge2]];
return newState.map(Number);
} }
// create a 2D board from a 1D CA initial state // create a 2D board from a 1D CA initial state
@ -48,31 +52,6 @@ function createBoard(state, rules, max) {
return board; return board;
} }
// 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 // Sums the value of a cell's neighbors
function getNeighborsSum(cells) { function getNeighborsSum(cells) {
return cells.reduce((cell, acc) => cell + acc, 0); return cells.reduce((cell, acc) => cell + acc, 0);
@ -91,6 +70,30 @@ function conwayRules(cell, neighbors) {
return cell; return cell;
} }
// Get the next evolution of a cell according to
// Conway's game of life rules
function servietteRules(cell, neighbors) {
// loneliness rule
if (cell === 0 && [2, 3, 4].find((x) => x == neighbors)) return 1;
// the cell remains the same if none apply
return 0;
}
// variation of the game of life where a
// cell comes to live if 6 neigbor cells are alive
function highLifeRules(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 === 2) return 1;
// highlife rules
if ((cell === 0 && neighbors === 3) || neighbors === 6) return 1;
// the cell remains the same if none apply
return cell;
}
// variation on the game of life's rules, // variation on the game of life's rules,
// where the "three live neighbors" rule is ignored // where the "three live neighbors" rule is ignored
function threebornRules(cell, neighbors) { function threebornRules(cell, neighbors) {
@ -127,13 +130,31 @@ function overpopulationRules(cell, neighbors) {
// get the next evolution of a 2D CA initial state // get the next evolution of a 2D CA initial state
// Rules : Moore neighborhood // Rules : Moore neighborhood
function evolve2d(board, rulesFn) { function evolve2d(board, rulesFn) {
return board.map((row, x) => const bh = board.length - 1;
row.map((cell, y) => { const bw = board[0].length - 1;
const neighbors = getCellNeighbors(board, [x, y]); return board.map((row, y) => {
// handle edges
const prow = y - 1 < 0 ? board[bh] : board[y - 1];
const nrow = y + 1 > bh ? board[0] : board[y + 1];
return row.map((cell, x) => {
// handle edges too
const pcell = x - 1 < 0 ? bw : x - 1;
const ncell = x + 1 > bw ? 0 : x + 1;
// the current cell is not included in the result
const neighbors = [
prow[pcell],
prow[x],
prow[ncell],
row[pcell],
row[ncell],
nrow[pcell],
nrow[x],
nrow[ncell],
];
const sum = getNeighborsSum(neighbors); const sum = getNeighborsSum(neighbors);
return rulesFn(cell, sum); return rulesFn(cell, sum);
}) });
); });
} }
function getDrawingValues(state, acc, cell) { function getDrawingValues(state, acc, cell) {
@ -184,6 +205,8 @@ export {
overpopulationRules, overpopulationRules,
lonelinessRules, lonelinessRules,
threebornRules, threebornRules,
highLifeRules,
servietteRules,
evolve1d, evolve1d,
evolve2d, evolve2d,
}; };

View File

@ -1,3 +1,13 @@
// https://stackoverflow.com/questions/21646738/convert-hex-to-rgba
// [
function hexToRGB(hex) {
return [
parseInt(hex.slice(1, 3), 16),
parseInt(hex.slice(3, 5), 16),
parseInt(hex.slice(5, 7), 16),
];
}
// https://stackoverflow.com/questions/4492385/convert-simple-array-into-two-dimensional-array-matrix // https://stackoverflow.com/questions/4492385/convert-simple-array-into-two-dimensional-array-matrix
// convert a 1D array into a 2D matrix // convert a 1D array into a 2D matrix
export function toMatrix(array, width) { export function toMatrix(array, width) {
@ -26,14 +36,45 @@ export function picToBlackAndWhite(pixels, width, height) {
} }
// convert an ImageData into a 2D array of boolean (0, 1) values // convert an ImageData into a 2D array of boolean (0, 1) values
export function picToBoard(pixels, width, height) { export function picToBoard(pixels, board) {
const flat = pixels.reduce((acc, pixel, index) => { const flat = pixels.reduce((acc, pixel, index) => {
if (index % 4 == 0) { const i = index * 4;
const count = pixels[index] + pixels[index + 1] + pixels[index + 2]; const count = pixels[i] + pixels[i + 1] + pixels[i + 2];
const value = count >= 255 ? 1 : 0; const value = (count >= 255) & 1;
acc.push(value); acc[index] = value;
}
return acc; return acc;
}, []); }, []);
return toMatrix(flat, Math.max(width, height)); // TODO: The representation has to be 2D, not the data structure
// (change to flat)
return toMatrix(flat, board.width, board.height);
}
// convert board to ImageData
// TODO : different cell to color functions
// (binary, intermediate states, camaieux, etc)
export function boardToPic(board) {
const live = board.cellProperties.liveColor;
const dead = board.cellProperties.deadColor;
const img = new ImageData(board.width, board.height);
const colors = [hexToRGB(live), hexToRGB(dead)];
board.grid.flat().reduce((acc, cell, index) => {
const color = colors[(cell === 1) & 1];
const i = index * 4;
acc[i] = color[0];
acc[i + 1] = color[1];
acc[i + 2] = color[2];
acc[i + 3] = 255;
return acc;
}, img.data);
return img;
}
// https://stackoverflow.com/questions/3332237/image-resizing-algorithm
export function scaleToTargetSize(w1, h1, w2, h2) {
const sourceRatio = w1 / h1;
const targetRatio = w2 / h2;
if (sourceRatio > targetRatio) {
return [w2, w2 / sourceRatio];
}
return [h2 * sourceRatio, h2];
} }

View File

@ -64,6 +64,19 @@ const presetRuleset = [
"000": 0, "000": 0,
}, },
}, },
{
name: "rule 30",
rules: {
100: 1,
101: 0,
110: 0,
111: 0,
"011": 1,
"010": 1,
"001": 1,
"000": 0,
},
},
{ {
name: "unknown rule", name: "unknown rule",
rules: { rules: {
@ -77,6 +90,45 @@ const presetRuleset = [
"000": 1, "000": 1,
}, },
}, },
{
name: "unknown rule 2",
rules: {
100: 1,
101: 0,
110: 1,
111: 0,
"011": 0,
"010": 0,
"001": 0,
"000": 1,
},
},
{
name: "rule 184",
rules: {
100: 1,
101: 1,
110: 0,
111: 1,
"011": 1,
"010": 0,
"001": 0,
"000": 0,
},
},
{
name: "rule 110",
rules: {
100: 0,
101: 1,
110: 1,
111: 0,
"011": 1,
"010": 1,
"001": 1,
"000": 0,
},
},
]; ];
const initialStates = [ const initialStates = [
@ -116,6 +168,17 @@ const preset2dRules = [
description: description:
"Variation on Conway's Game of Life *without* the 'three live neighbors' rule", "Variation on Conway's Game of Life *without* the 'three live neighbors' rule",
}, },
{
id: "highlife",
name: "HighLife variation",
description:
"Variation on Conway's Game of Life where a cell live if the six neighbor cells are alive",
},
{
id: "serviette",
name: "Serviette variation",
description: "bla",
},
]; ];
export { presetRuleset, initialStates, preset2dRules }; export { presetRuleset, initialStates, preset2dRules };

67
src/modules/renderer.js Normal file
View File

@ -0,0 +1,67 @@
import { boardToPic, scaleToTargetSize } from "./picture.js";
function scaleAndApply(context, ratio, callback) {
context.save();
// rescale
context.imageSmoothingEnabled = false;
context.scale(ratio, ratio);
// apply
callback();
context.restore();
}
// draws the board representation on the canvas
function render(board) {
const d = board.cellProperties.size;
// bool to RGBA colors
const img = boardToPic(board);
this.ctx.clearRect(0, 0, this.width, this.height);
scaleAndApply(this.ctx, d, () => {
this.workCtx.putImageData(img, 0, 0);
this.ctx.drawImage(this.workCanvas, 0, 0, this.width, this.height);
});
}
// draw image on canvas
function renderImage(image, ctx, tw, th) {
ctx.fillStyle = "black";
ctx.fillRect(0, 0, tw, th);
const dimensions = scaleToTargetSize(image.width, image.height, tw, th);
ctx.drawImage(
image,
Math.floor((tw - dimensions[0]) / 2),
Math.floor((th - dimensions[1]) / 2),
dimensions[0],
dimensions[1]
);
return ctx.getImageData(0, 0, tw, th);
}
function resize(width, height) {
this.width = width;
this.height = height;
this.canvas.height = height;
this.canvas.width = width;
this.workCanvas.height = height;
this.workCanvas.width = width;
}
function reset() {
this.ctx.clearRect(0, 0, this.width, this.height);
}
function Renderer() {
this.canvas = null;
this.workCanvas = null;
this.workCtx = null;
this.width = null;
this.height = null;
this.ctx = null;
this.refreshRate = 300;
this.render = render;
this.renderImage = renderImage;
this.reset = reset;
this.resize = resize;
}
export { Renderer };

View File

@ -1,4 +1,6 @@
import { defineStore } from "pinia"; import { defineStore } from "pinia";
import { Board } from "../modules/board.js";
import { Renderer } from "../modules/renderer.js";
export const globalStore = defineStore("globalStore", { export const globalStore = defineStore("globalStore", {
state: () => { state: () => {
@ -21,66 +23,75 @@ export const globalStore = defineStore("globalStore", {
name: "Conway's Game of Life", name: "Conway's Game of Life",
description: "The most popular 2d automata", description: "The most popular 2d automata",
}, },
cellProperties: {
size: 3,
liveColor: "#000000",
deadColor: "#F5F5F5",
},
canvasWidth: 0,
canvasHeight: 0,
boardWidth: 0,
boardHeight: 0,
refreshRate: 300,
initial1dState: "onecell", initial1dState: "onecell",
drawingDirection: "y", drawingDirection: "y",
lastBoard: {}, board: new Board(),
draw1d: false, draw1d: false,
draw2d: false, draw2d: false,
draw2dLast: false, draw2dLast: false,
draw2dpicture: false, draw2dpicture: false,
reset: false, reset: false,
canDraw: true, canDraw: true,
picture: null, picture: new Image(),
mainMenu: false, mainMenu: false,
activeSubMenu: "", activeSubMenu: "",
loop: true,
lastAction: "drawfromlast",
renderer: new Renderer(),
}; };
}, },
actions: { actions: {
setBoardWidth() { setBoardWidth() {
this.boardWidth = Math.floor(this.canvasWidth / this.cellProperties.size); this.board.width = Math.floor(
this.renderer.width / this.board.cellProperties.size
);
}, },
setBoardHeight() { setBoardHeight() {
this.boardHeight = Math.floor( this.board.height = Math.floor(
this.canvasHeight / this.cellProperties.size this.renderer.height / this.board.cellProperties.size
); );
}, },
setCellProperties(name, value) {
this.board.cellProperties[name] = value;
},
switchColor() {
[
this.board.cellProperties["liveColor"],
this.board.cellProperties["deadColor"],
] = [
this.board.cellProperties["deadColor"],
this.board.cellProperties["liveColor"],
];
},
toggleDraw1d() { toggleDraw1d() {
this.setActiveSubMenu(""); this.setActiveSubMenu("");
this.setMainMenu(false); this.setMainMenu(false);
this.draw1d = true; this.draw1d = !this.draw1d;
}, },
toggleDraw2d() { toggleDraw2d() {
this.setActiveSubMenu(""); this.setActiveSubMenu("");
this.lastAction = "draw2d";
this.setMainMenu(false); this.setMainMenu(false);
this.toggleStop(); this.toggleStop();
this.canDraw = true; this.canDraw = !this.canDraw;
this.draw2d = true; this.draw2d = !this.draw2d;
}, },
toggleDraw2dLast() { toggleDraw2dLast() {
this.setActiveSubMenu(""); this.setActiveSubMenu("");
this.lastAction = "drawfromlast";
this.setMainMenu(false); this.setMainMenu(false);
this.toggleStop(); this.toggleStop();
this.canDraw = true; this.canDraw = !this.canDraw;
this.draw2dLast = true; this.draw2dLast = !this.draw2dLast;
}, },
toggle2dDrawFromPicture() { toggle2dDrawFromPicture() {
this.toggleStop(); this.toggleStop();
this.canDraw = true; this.canDraw = !this.canDraw;
this.draw2dpicture = true; this.draw2dpicture = !this.draw2dpicture;
}, },
toggleReset() { toggleReset() {
this.toggleStop(); this.toggleStop();
this.reset = true; this.reset = !this.reset;
}, },
toggleStop() { toggleStop() {
this.draw1d = false; this.draw1d = false;
@ -89,6 +100,21 @@ export const globalStore = defineStore("globalStore", {
this.draw2dpicture = false; this.draw2dpicture = false;
this.canDraw = false; this.canDraw = false;
}, },
toggleLoop() {
this.loop = !this.loop;
},
toggleNext() {
switch (this.lastAction) {
case "drawfromlast":
this.toggleDraw2dLast();
break;
case "draw2d":
this.toggleDraw2d();
break;
default:
return;
}
},
setActiveSubMenu(data) { setActiveSubMenu(data) {
if (this.activeSubMenu == data) this.activeSubMenu = ""; if (this.activeSubMenu == data) this.activeSubMenu = "";
else this.activeSubMenu = data; else this.activeSubMenu = data;

28
tests/board.test.js Normal file
View File

@ -0,0 +1,28 @@
import { describe, expect, test } from "vitest";
import {
Board,
create1dInitialState,
create2dRandomGrid,
} from "src/modules/board.js";
describe("Board", () => {
const board = new Board(503, 301);
test("create1dInitialState onecell", () => {
const stateOne = create1dInitialState(board);
expect(stateOne.length).toBe(board.width);
expect(stateOne).toContain(1);
});
test("create1dInitialState random", () => {
const stateRandom = create1dInitialState(board, "random");
expect(stateRandom.length).toBe(board.width);
expect(stateRandom).toContain(1);
});
test("create2dRandomGrid", () => {
const board = new Board(503, 301);
const got = create2dRandomGrid(board.width, board.height);
expect(got.length).toBe(board.height);
expect(got[0].length).toBe(board.width);
});
});

18
tests/core.test.js Normal file
View File

@ -0,0 +1,18 @@
import { describe, expect, test } from "vitest";
import { evolve1d, create1dStateOneCell } from "src/modules/core.js";
import { presetRuleset } from "src/modules/preset.js";
describe("Core", () => {
test("evolve1d, rules73, 9 cells", () => {
const state = [0, 0, 0, 0, 1, 0, 0, 0, 0];
const got = evolve1d(state, presetRuleset[0].rules);
const valid = [1, 1, 1, 0, 0, 0, 1, 1, 1];
expect(got.length).toBe(state.length);
expect(got).toEqual(valid);
}),
test("create1dStateOneCell, 49 cells", () => {
const got = create1dStateOneCell(49);
expect(got.length).toBe(49);
expect(got[24]).toBe(1);
});
});

View File

@ -13,4 +13,11 @@ export default defineConfig({
"@": path.resolve(__dirname, "./src"), "@": path.resolve(__dirname, "./src"),
}, },
}, },
test: {
// enable jest-like global test APIs
globals: true,
// simulate DOM with happy-dom
// (requires installing happy-dom as a peer dependency)
environment: "happy-dom",
},
}); });