Compare commits

..

No commits in common. "master" and "mobile-friendly" have entirely different histories.

26 changed files with 2610 additions and 3799 deletions

View File

@ -44,4 +44,3 @@ 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/

4154
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -3,29 +3,24 @@
"version": "0.1.0", "version": "0.1.0",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "vite --host", "dev": "vite",
"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.10", "vite": "^3.2.4",
"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",
"happy-dom": "^8.1.1", "prettier": "2.8.0"
"prettier": "2.8.0",
"vitest": "^0.26.2"
}, },
"eslintConfig": { "eslintConfig": {
"root": true, "root": true,

View File

@ -1,57 +1,153 @@
<script setup> <template>
<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 { mapWritableState, mapActions } from "pinia";
import { globalStore } from "./stores/index.js"; import { globalStore } from "./stores/index.js";
import { nextTick, onBeforeUnmount, onMounted, ref } from "vue";
const store = globalStore(); export default {
name: "App",
const windowWidth = ref(window.innerWidth); components: {
MainMenu,
const toggleMainMenu = () => { MenuReset,
store.setMainMenu(!store.mainMenu); CanvasBoard,
},
data() {
return {
mainMenu: false,
windowWidth: window.innerWidth,
};
},
computed: {
...mapWritableState(globalStore, {
canvasWidth: "canvasWidth",
canvasHeight: "canvasHeight",
}),
},
mounted() {
this.$nextTick(() => {
window.addEventListener("resize", this.onResize);
});
},
beforeUnmount() {
window.removeEventListener("resize", this.onResize);
},
methods: {
...mapActions(globalStore, ["setBoardWidth", "setBoardHeight"]),
toggleMainMenu() {
this.mainMenu = !this.mainMenu;
},
onResize() {
this.$nextTick(() => {
this.windowWidth = window.innerWidth;
this.canvasWidth = window.innerWidth;
this.canvasHeight = window.innerHeight;
this.setBoardWidth();
this.setBoardHeight();
});
},
},
}; };
const onResize = () => {
nextTick(() => {
windowWidth.value = window.innerWidth;
// TODO: changing the width will clear the canvas. Find something else
store.renderer.resize(window.innerWidth, window.innerHeight);
store.setBoardWidth();
store.setBoardHeight();
});
};
onMounted(() => {
nextTick(() => {
window.addEventListener("resize", onResize);
});
});
onBeforeUnmount(() => {
window.removeEventListener("resize", onResize);
});
</script> </script>
<template> <style scope>
<main> :root {
<h1 --dark1: #000000;
v-if="store.mainMenu || windowWidth <= 800" --dark2: #333333;
id="main-title" --dark3: #666666;
class="main-title" --light1: #999999;
> --light2: #cccccc;
<span id="burger-toggle" class="burger-toggle" @click="toggleMainMenu"> --light3: #eeeeee;
{{ 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>
<style src="./assets/css/main.css"></style> #app {
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>

View File

@ -1,228 +0,0 @@
: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;
}
}

BIN
src/assets/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

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

View File

@ -1,194 +1,149 @@
<script setup>
import { onMounted, watch } from "vue";
import { globalStore } from "../stores/index.js";
import {
createBoard,
conwayRules,
overpopulationRules,
lonelinessRules,
threebornRules,
highLifeRules,
servietteRules,
evolve2d,
} from "../modules/core.js";
import {
create1dInitialState,
create2dRandomGrid,
} from "../modules/board.js";
import { picToBoard } from "../modules/picture.js";
const store = globalStore();
const available2dRules = {
conway: conwayRules,
overpopulation: overpopulationRules,
loneliness: lonelinessRules,
threeborn: threebornRules,
highlife: highLifeRules,
serviette: servietteRules,
};
// used to determine the dimensions of the board
// TODO: should be a Board method
const max = () => {
return Math.max(store.board.width, store.board.height);
};
const selectedRules = () => {
return available2dRules[store.selected2dRules.id];
};
watch(
() => store.draw1d,
(value) => {
if (value == true) draw1d();
}
);
watch(
() => store.draw2d,
(value) => {
if (value == true) draw2dNew();
}
);
watch(
() => store.draw2dLast,
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,
});
if (typeof OffscreenCanvas != "undefined") {
store.renderer.workCanvas = new OffscreenCanvas(
canvas.parentElement.clientWidth,
canvas.parentElement.clientHeight
);
}
// https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas/OffscreenCanvas#Browser_compatibility
// Fallback for when offscreenCanvas is unsupported or disabled (Firefox < 44, default for Firefox?)
else {
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
const drawCanvas = async (board) => {
store.renderer.render(board);
};
// draw elementary automaton on the canvas based on selected ruleset
const draw1d = () => {
const initialState = create1dInitialState(
store.board,
store.initial1dState
);
const board = createBoard(initialState, store.ruleset1d.rules, max());
store.board.grid = Object.freeze(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
const draw2dLast = async () => {
if (!store.canDraw) return;
if (store.loop) return draw2dNext(store.board);
else draw2d(store.board);
store.toggleStop();
};
// draw 2d automaton from an uploaded picture.
// use the picture representation as an initial state
const draw2dPicture = async () => {
store.renderer.renderImage(
store.picture,
store.renderer.ctx,
store.renderer.width,
store.renderer.height
);
const resized = store.renderer.renderImage(
store.picture,
store.renderer.workCtx,
store.board.width,
store.board.height
);
const newBoard = picToBoard(resized.data, store.board);
store.board.grid = Object.freeze(newBoard);
store.toggleStop();
};
const reset = () => {
store.toggleStop();
store.board.grid = null;
store.renderer.reset();
store.toggleReset();
};
</script>
<template> <template>
<canvas <canvas
id="board-canvas" id="canvas-board"
ref="board-canvas" ref="canvas-board"
class="board-canvas" :width="canvasWidth"
:width="store.renderer.width" :height="canvasHeight"
:height="store.renderer.height"
/> />
</template> </template>
<script>
import { mapActions, mapState, mapWritableState } from "pinia";
import { globalStore } from "../stores/index.js";
import {
create1dState,
create1dStateOneCell,
create2dState,
createBoard,
conwayRules,
evolve2d,
} from "../modules/automata.js";
import { getRandomInt, sleep } from "../modules/common.js";
export default {
name: "CanvasBoard",
data() {
return {
canvas: null,
ctx: null,
};
},
computed: {
...mapState(globalStore, {
cellProperties: "cellProperties",
ruleset: "ruleset1d",
refreshRate: "refreshRate",
initial1dState: "initial1dState",
drawingDirection: "drawingDirection",
canDraw: "canDraw",
getDraw1d: "draw1d",
getDraw2d: "draw2d",
getDraw2dLast: "draw2dLast",
boardWidth: "boardWidth",
boardHeight: "boardHeight",
}),
...mapWritableState(globalStore, {
lastBoard: "lastBoard",
canvasWidth: "canvasWidth",
canvasHeight: "canvasHeight",
getReset: "reset",
}),
},
watch: {
getDraw1d(value) {
if (value == true) this.draw1d();
},
getDraw2d(value) {
if (value == true) this.draw2dNew();
},
getDraw2dLast(value) {
if (value == true) this.draw2dLast();
},
getReset(value) {
if (value == true) this.reset();
},
},
mounted() {
this.canvas = Object.freeze(document.getElementById("canvas-board"));
this.ctx = this.canvas.getContext("2d");
this.canvasWidth = this.canvas.parentElement.clientWidth;
this.canvasHeight = this.canvas.parentElement.clientHeight;
this.setBoardWidth();
this.setBoardHeight();
},
methods: {
...mapActions(globalStore, [
"toggleStop",
"setBoardWidth",
"setBoardHeight",
]),
drawCanvas(board) {
const props = this.cellProperties;
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;
});
});
},
compute1dInitialState() {
if (this.initial1dState === "onecell")
return create1dStateOneCell(this.boardWidth);
return create1dState(this.boardWidth, getRandomInt, [0, 2]);
},
draw1d() {
const initialState = this.compute1dInitialState();
const board = createBoard(
initialState,
this.ruleset.rules,
this.boardWidth
);
this.lastBoard = Object.freeze(board);
this.drawCanvas(board);
this.toggleStop();
},
draw2d(board) {
if (!this.canDraw) return;
const draw2dNext = async (b) => {
if (!this.canDraw) return;
const newBoard = evolve2d(b, conwayRules);
this.drawCanvas(b, this.cellProperties);
await sleep(this.refreshRate);
draw2dNext(newBoard);
};
return draw2dNext(board);
},
draw2dNew() {
const initialState = create2dState(
this.boardWidth,
this.boardHeight,
getRandomInt,
[0, 2]
);
const board = evolve2d(initialState, conwayRules);
this.lastBoard = Object.freeze(board);
this.draw2d(board);
},
async draw2dLast() {
if (this.lastBoard != undefined) this.draw2d(this.lastBoard);
},
reset() {
this.toggleStop();
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.getReset = 0;
},
},
};
</script>
<style>
#canvas-board {
flex: 1;
margin: 0 auto;
}
</style>

View File

@ -7,9 +7,46 @@
</div> </div>
</template> </template>
<script setup> <script>
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,48 +1,3 @@
<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">
@ -50,36 +5,29 @@
<input <input
type="button" type="button"
name="start2d" name="start2d"
value="" value="start"
@click="store.toggleDraw2d()" @click="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="▶" @click="store.toggleDraw2dLast()" /> <input type="button" value="start" @click="toggleDraw2dLast()" />
</div>
<div class="form-field">
<label>Start from picture</label><br />
<input ref="uploadedPicture" type="file" @change="preparePicture" />
</div>
<div class="form-field">
<label>
Rules
<br />
<select
name="preset2dRules"
:value="store.selected2dRules.id"
@input="update2dRules"
>
<option
v-for="(state, index) in preset2dRules"
:key="'initial-state-elementary' + index"
:value="state.id"
>
{{ state.name }}
</option>
</select>
</label>
</div> </div>
</MenuRow> </MenuRow>
</template> </template>
<script>
import { mapActions } from "pinia";
import MenuRow from "./MenuRow.vue";
import { globalStore } from "../stores/index.js";
export default {
name: "Menu2dCA",
components: {
MenuRow,
},
methods: {
...mapActions(globalStore, ["toggleDraw2dLast", "toggleDraw2d"]),
},
};
</script>

View File

@ -1,21 +1,3 @@
<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>
@ -24,7 +6,7 @@
<input <input
name="liveColor" name="liveColor"
type="color" type="color"
:value="store.board.cellProperties.liveColor" @value="cellProperties.liveColor"
@input="updateCellProperties" @input="updateCellProperties"
/> />
</div> </div>
@ -33,23 +15,46 @@
<input <input
name="deadColor" name="deadColor"
type="color" type="color"
:value="store.board.cellProperties.deadColor" :value="cellProperties.deadColor"
@input="updateCellProperties" @input="updateCellProperties"
/> />
</div> </div>
<div class="form-field">
<a name="switchColor" @click="switchColor">Switch Colors</a>
</div>
<div class="form-field"> <div class="form-field">
<label>Cell size</label> <label>Cell size</label>
<input <input
name="size" name="size"
type="number" type="number"
min="1" min="1"
:value="store.board.cellProperties.size" :value="cellProperties.size"
@click="updateCellProperties" @input="updateCellProperties"
/> />
</div> </div>
</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: "MainMenu",
components: {
MenuRow,
},
computed: {
...mapWritableState(globalStore, ["cellProperties"]),
},
methods: {
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;
},
},
};
</script>

View File

@ -1,54 +1,13 @@
<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>
<div class="form-field">
<input
type="button"
name="start"
value="▶"
@click="store.toggleDraw1d()"
/>
</div>
<div class="form-field"> <div class="form-field">
<label> <label>
Initial state presets Initial state presets
<br /> <br />
<select <select
name="initialStates" name="initialStates"
:value="store.initial1dState" :value="initialState"
@input="updateInitialState" @input="updateInitialState"
> >
<option <option
@ -70,7 +29,7 @@
<br /> <br />
<select <select
name="ruleset-elementary" name="ruleset-elementary"
:value="store.ruleset1d.name" :value="ruleset.name"
@input="updateRuleset" @input="updateRuleset"
> >
<option <option
@ -87,7 +46,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 store.ruleset1d.rules" v-for="(rule, name, index) in ruleset.rules"
:key="'rule-' + index" :key="'rule-' + index"
class="form-field" class="form-field"
> >
@ -103,5 +62,79 @@
</label> </label>
</div> </div>
</form> </form>
<div class="form-field">
<input type="button" name="start" value="start" @click="toggleDraw1d()" />
</div>
</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,31 +1,3 @@
<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>
@ -39,7 +11,7 @@
name="canvasWidth" name="canvasWidth"
type="number" type="number"
step="10" step="10"
:value="store.renderer.width" :value="canvasWidth"
@input="updateCanvasWidth" @input="updateCanvasWidth"
/> />
</div> </div>
@ -50,19 +22,21 @@
name="canvasHeight" name="canvasHeight"
type="number" type="number"
step="10" step="10"
:value="store.renderer.height" :value="canvasHeight"
@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="store.renderer.refreshRate" :value="refreshRate"
@input="updateRefreshRate" @input="updateRefreshRate"
/> />
</div> </div>
@ -71,8 +45,8 @@
>Invert Drawing Direction >Invert Drawing Direction
<input <input
type="checkbox" type="checkbox"
:checked="store.drawingDirection === 'x'" :checked="drawingDirection === 'x'"
:value="store.drawingDirection" :value="drawingDirection"
@input="updateDrawingDirection" @input="updateDrawingDirection"
/> />
</label> </label>
@ -80,3 +54,42 @@
</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,56 +1,36 @@
<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="reset-menu"> <div class="form-field">
<div v-if="props.windowWidth >= 800" class="desktop-title"> <input
Cellular Automata Explorer type="button"
</div> name="stop"
<div class="reset-input"> class="stop"
<div class="loop"> value="stop"
<label> @click="toggleStop()"
loop />
<input <input
:value="store.loop" type="button"
type="checkbox" name="reset"
:checked="store.loop" class="reset"
@input="store.toggleLoop()" value="reset"
/> @click="toggleReset()"
</label> />
</div>
<input
type="button"
name="next"
class="next"
value="⇨"
@click="store.toggleNext()"
/>
<input
type="button"
name="stop"
class="stop"
value="⏹"
@click="store.toggleStop()"
/>
<input
type="button"
name="reset"
class="reset"
value="⌫"
@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,51 +1,105 @@
<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="updateActiveMenu">
{{ rowTitle }} {{ rowTitle }}
</h2> </h2>
<div v-if="isActive" ref="content" class="menu-row-content"> <div class="menu-row-content">
<slot /> <slot />
</div> </div>
</div> </div>
</template> </template>
<script>
export default {
name: "MenuRow",
props: {
rowTitle: {
type: String,
default: "",
},
},
};
</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:hover .menu-row-content {
display: block;
width: 100%;
}
.menu-row-content {
position: absolute;
background: var(--dark1);
display: none;
}
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>

95
src/components/preset.js Normal file
View File

@ -0,0 +1,95 @@
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 };

152
src/modules/automata.js Normal file
View File

@ -0,0 +1,152 @@
// 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, []);
// }
// performance "choke point" in full imperative
function createBoard(state, rules, height) {
var board = [];
let prevState = [];
for (let i = 0; i < height; i++) {
let nextState = [];
if (i == 0) {
nextState = evolve1d(state, rules);
} else {
nextState = evolve1d(prevState, rules);
}
board = board.concat([nextState]);
prevState = nextState;
}
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
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
// Rules : Moore neighborhood
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 with a single living cell in the center
function create1dStateOneCell(width) {
return [...Array(width)].map((cell, index) => {
if (index === width / 2 || index === width + 1 / 2) return 1;
return 0;
});
}
// Populates the first state of a 1D CA with cells returned
// by initFn
function create1dState(width, initFn, args) {
return [...Array(width)].map(() => initFn(...args));
}
// Populates the first state of a 2D CA with cells returned
// by initFn
function create2dState(width, height, initFn, args) {
return [...Array(height)].map(() =>
[...Array(width)].map(() => initFn(...args))
);
}
export {
getDrawingValues,
create1dState,
create2dState,
createBoard,
create1dStateOneCell,
conwayRules,
evolve1d,
evolve2d,
};

View File

@ -1,28 +0,0 @@
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,212 +0,0 @@
// core functions to generate initial states and evolve them
// get the next evolution of a 1D CA initial state
// buggy BUT produces interesting results
// 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
function evolve1d(state, rules) {
const sl = state.length - 1;
const edge1 = [state[sl - 2], state[sl - 1], state[sl]].join("");
const edge2 = [state[0], state[1], state[2]].join("");
// normal case (3 neighbor cells)
const center = state
.map((_, x) => rules[[state[x - 1], state[x], state[x + 1]].join("")])
.slice(1, sl);
return [rules[edge1], ...center, rules[edge2]];
}
// 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
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);
}
board = board.concat([nextState]);
prevState = nextState;
}
return board;
}
// 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 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,
// where the "three live neighbors" rule is ignored
function threebornRules(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
return cell;
}
// variation on the game of life's rules,
// where the loneliness rule is ignored
function lonelinessRules(cell, neighbors) {
// 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;
}
// variation on the game of life's rules,
// where the overpopulation rule is ignored
function overpopulationRules(cell, neighbors) {
// loneliness rule
if (cell === 1 && neighbors < 2) 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
// Rules : Moore neighborhood
function evolve2d(board, rulesFn) {
const bh = board.length - 1;
const bw = board[0].length - 1;
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);
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 with a single living cell in the center
function create1dStateOneCell(width) {
return [...Array(width)].map((cell, index) => {
if (index === Math.floor(width / 2)) return 1;
return 0;
});
}
// Populates the first state of a 1D CA with cells returned
// by initFn
function create1dState(width, initFn, args) {
return [...Array(width)].map(() => initFn(...args));
}
// Populates the first state of a 2D CA with cells returned
// by initFn
function create2dState(width, height, initFn, args) {
return [...Array(height)].map(() =>
[...Array(width)].map(() => initFn(...args))
);
}
export {
getDrawingValues,
create1dState,
create2dState,
createBoard,
create1dStateOneCell,
conwayRules,
overpopulationRules,
lonelinessRules,
threebornRules,
highLifeRules,
servietteRules,
evolve1d,
evolve2d,
};

View File

@ -1,80 +0,0 @@
// 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
// convert a 1D array into a 2D matrix
export function toMatrix(array, width) {
return array.reduce(
(rows, key, index) =>
(index % width == 0
? rows.push([key])
: rows[rows.length - 1].push(key)) && rows,
[]
);
}
// convert an image into a black and white image
export function picToBlackAndWhite(pixels, width, height) {
return pixels.reduce((acc, pixel, index) => {
if (index % 4 == 0) {
const count = pixels[index] + pixels[index + 1] + pixels[index + 2];
const colour = count >= 255 ? 255 : 1;
acc.data[index] = colour;
acc.data[index + 1] = colour;
acc.data[index + 2] = colour;
acc.data[index + 3] = 255;
}
return acc;
}, new ImageData(width, height));
}
// convert an ImageData into a 2D array of boolean (0, 1) values
export function picToBoard(pixels, board) {
const flat = pixels.reduce((acc, pixel, index) => {
const i = index * 4;
const count = pixels[i] + pixels[i + 1] + pixels[i + 2];
const value = (count >= 255) & 1;
acc[index] = value;
return acc;
}, []);
// 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,19 +64,6 @@ 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: {
@ -90,45 +77,6 @@ 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 = [
@ -144,41 +92,4 @@ const initialStates = [
}, },
]; ];
const preset2dRules = [ export { presetRuleset, initialStates };
{
id: "conway",
name: "Conway's Game of Life",
description: "The most popular 2d automata",
},
{
id: "overpopulation",
name: "Overpopulation variation",
description:
"Variation on Conway's Game of Life *without* the overpopulation rule",
},
{
id: "loneliness",
name: "Loneliness variation",
description:
"Variation on Conway's Game of Life *without* the loneliness rule",
},
{
id: "threeborn",
name: "Three lives variation",
description:
"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 };

View File

@ -1,67 +0,0 @@
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,6 +1,4 @@
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: () => {
@ -18,109 +16,57 @@ export const globalStore = defineStore("globalStore", {
"000": 1, "000": 1,
}, },
}, },
selected2dRules: { cellProperties: {
id: "conway", size: 3,
name: "Conway's Game of Life", liveColor: "#000000",
description: "The most popular 2d automata", deadColor: "#F5F5F5",
}, },
canvasWidth: 0,
canvasHeight: 0,
boardWidth: 0,
boardHeight: 0,
refreshRate: 300,
initial1dState: "onecell", initial1dState: "onecell",
drawingDirection: "y", drawingDirection: "y",
board: new Board(), lastBoard: {},
draw1d: false, draw1d: false,
draw2d: false, draw2d: false,
draw2dLast: false, draw2dLast: false,
draw2dpicture: false,
reset: false, reset: false,
canDraw: true, canDraw: true,
picture: new Image(),
mainMenu: false,
activeSubMenu: "",
loop: true,
lastAction: "drawfromlast",
renderer: new Renderer(),
}; };
}, },
actions: { actions: {
setBoardWidth() { setBoardWidth() {
this.board.width = Math.floor( this.boardWidth = Math.floor(this.canvasWidth / this.cellProperties.size);
this.renderer.width / this.board.cellProperties.size
);
}, },
setBoardHeight() { setBoardHeight() {
this.board.height = Math.floor( this.boardHeight = Math.floor(
this.renderer.height / this.board.cellProperties.size this.canvasHeight / this.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.draw1d = true;
this.setMainMenu(false);
this.draw1d = !this.draw1d;
}, },
toggleDraw2d() { toggleDraw2d() {
this.setActiveSubMenu("");
this.lastAction = "draw2d";
this.setMainMenu(false);
this.toggleStop(); this.toggleStop();
this.canDraw = !this.canDraw; this.canDraw = true;
this.draw2d = !this.draw2d; this.draw2d = true;
}, },
toggleDraw2dLast() { toggleDraw2dLast() {
this.setActiveSubMenu("");
this.lastAction = "drawfromlast";
this.setMainMenu(false);
this.toggleStop(); this.toggleStop();
this.canDraw = !this.canDraw; this.canDraw = true;
this.draw2dLast = !this.draw2dLast; this.draw2dLast = true;
},
toggle2dDrawFromPicture() {
this.toggleStop();
this.canDraw = !this.canDraw;
this.draw2dpicture = !this.draw2dpicture;
}, },
toggleReset() { toggleReset() {
this.toggleStop(); this.toggleStop();
this.reset = !this.reset; this.reset = true;
}, },
toggleStop() { toggleStop() {
this.draw1d = false; this.draw1d = false;
this.draw2d = false; this.draw2d = false;
this.draw2dLast = false; this.draw2dLast = 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) {
if (this.activeSubMenu == data) this.activeSubMenu = "";
else this.activeSubMenu = data;
},
setMainMenu(data) {
this.mainMenu = data;
},
}, },
}); });

View File

@ -1,28 +0,0 @@
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);
});
});

View File

@ -1,18 +0,0 @@
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,11 +13,4 @@ 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",
},
}); });