dice/src/main/js/index.js

239 lines
5.8 KiB
JavaScript

import {$, doAfterLoad, footer, header, nav} from "@fwdekker/template";
import Chart from "chart.js"
//////
///
/// Helper functions
///
//////
const repeat = (value, length) => {
const zeroArray = [];
for (let i = 0; i < length; i++)
zeroArray.push(value);
return zeroArray;
};
const rangeExclusive = (from, to) => {
const rangeArray = [];
for (let i = from; i < to; i++)
rangeArray.push(i);
return rangeArray;
};
const rangeInclusive = (from, to) => {
const rangeArray = rangeExclusive(from, to);
rangeArray.push(to);
return rangeArray;
};
const iterateNodeList = (nodeList, fun) => {
for (let i = 0; i < nodeList.length; i++) {
const node = nodeList.item(i);
fun(node);
}
};
//////
///
/// Template
///
//////
doAfterLoad(() => {
$("#nav").appendChild(nav());
$("#header").appendChild(header({
title: "Dice",
description: "Calculate the probability of rolling a value given a combination of dice"
}));
$("#footer").appendChild(footer({
author: "Felix W. Dekker",
authorURL: "https://fwdekker.com/",
license: "MIT License",
licenseURL: "https://git.fwdekker.com/FWDekker/dice/src/branch/master/LICENSE",
vcs: "git",
vcsURL: "https://git.fwdekker.com/FWDekker/dice/",
version: "v%%VERSION_NUMBER%%"
}));
$("main").style.display = null;
});
//////
///
/// Input
///
//////
const inputTable = {};
// Functions
inputTable.getTable = () => $("#dieSettings tbody");
inputTable.dieRowCount = () => inputTable.getTable().querySelectorAll(".dieEyes").length;
inputTable.highestDieRowIndex = () => {
const table = inputTable.getTable();
let highestDieRowIndex = -1;
iterateNodeList(table.getElementsByTagName("tr"), (node) => {
if ("index" in node.dataset)
highestDieRowIndex = Math.max(highestDieRowIndex, +node.dataset.index);
});
return highestDieRowIndex;
};
inputTable.addDieRow = () => {
const createNumberInput = (index, className, value) => {
const input = document.createElement("input");
input.id = className + index;
input.className = className;
input.type = "number";
input.min = "1";
input.step = "1";
input.value = value;
input.addEventListener("keypress", (e) => {
if (e.key === "Enter")
outputChart.updateProbGraph();
});
input.focus();
return input;
};
const createRemoveLink = (index, className) => {
const link = document.createElement("button");
link.id = className + index;
link.className = className + " button-clear";
link.type = "button";
link.innerHTML = "Remove";
link.onclick = (() => inputTable.removeDieRow(index));
return link;
};
const table = inputTable.getTable();
const newIndex = inputTable.highestDieRowIndex() + 1;
const row = table.insertRow(inputTable.dieRowCount());
row.dataset.index = "" + newIndex;
row.insertCell().appendChild(createNumberInput(newIndex, "dieEyes", 6));
row.insertCell().appendChild(createNumberInput(newIndex, "dieCount", 2));
row.insertCell().appendChild(createRemoveLink(newIndex, "dieRemove"));
};
inputTable.removeDieRow = index => {
if (inputTable.highestDieRowIndex() > 0) {
const table = inputTable.getTable();
const row = table.querySelector("tr[data-index=\"" + index + "\"]");
row.parentElement.removeChild(row);
}
};
inputTable.getDice = () => {
const dice = [];
const eyesInputs = document.getElementsByClassName("dieEyes");
const countInputs = document.getElementsByClassName("dieCount");
for (let i = 0; i < eyesInputs.length; i++) {
const count = parseInt(countInputs.item(i).value);
for (let j = 0; j < count; j++)
dice.push(parseInt(eyesInputs.item(i).value));
}
return dice;
};
// Init
doAfterLoad(() => {
const button = $("#addDieRowButton");
button.onclick = inputTable.addDieRow;
button.click()
});
//////
///
/// Output
///
//////
const outputChart = {};
let probChart;
// Functions
outputChart.calculateDiceFrequencies = dice => {
if (dice.length === 0)
return [];
// Roll dice
let rollFreqs = [0].concat(repeat(1, dice[0]));
dice.slice(1).forEach(die => {
const dieRollFreqs = rollFreqs.concat(repeat(0, die));
rollFreqs = repeat(0, dieRollFreqs.length);
rangeInclusive(1, die).forEach(rollValue => {
rangeExclusive(1, dieRollFreqs.length - die).forEach(i => {
rollFreqs[rollValue + i] += dieRollFreqs[i];
});
});
});
rollFreqs.shift();
// Calculate frequencies
const totalRolls = rollFreqs.reduce((a, b) => a + b, 0);
rangeExclusive(0, rollFreqs.length).forEach(roll => {
rollFreqs[roll] = rollFreqs[roll] / totalRolls;
});
return rollFreqs;
};
outputChart.updateProbGraph = () => {
const dice = inputTable.getDice();
const rollFreqs = outputChart.calculateDiceFrequencies(dice);
probChart.data.labels = rangeInclusive(1, rollFreqs.length);
probChart.data.datasets = [{
data: rollFreqs,
backgroundColor: "rgb(0, 51, 204, 0.4)"
}];
probChart.update();
};
// Init
doAfterLoad(() => {
probChart = new Chart($("#probChart").getContext("2d"), {
type: "line",
data: {},
options: {
legend: {
display: false
},
scales: {
yAxes: [{
display: true,
ticks: {
suggestedMin: 0
}
}]
}
}
});
const submit = $("#submit");
submit.onclick = outputChart.updateProbGraph;
submit.click()
});