Implement the choosing system.
This commit is contained in:
parent
2776e10f80
commit
3297c70db4
2 changed files with 59 additions and 1 deletions
|
|
@ -12,6 +12,7 @@
|
|||
|
||||
<!-- JAVASCRIPT -->
|
||||
<script src="./js/add_choice.js"></script>
|
||||
<script src="./js/choosing.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<template id="choice-template">
|
||||
|
|
@ -26,14 +27,16 @@
|
|||
<h2>Choices:</h2>
|
||||
<button onclick="add_choice()">Add New Choice</button>
|
||||
<br>
|
||||
<div class="line"></div>
|
||||
<div id="choices">
|
||||
<div class="choice">
|
||||
<div class="line"></div>
|
||||
<input class="left" type="text" id="text-in-0" placeholder="Choice Name">
|
||||
<input class="right" type="text" id="weight-in-0" placeholder="Choice Weighting">
|
||||
<div class="line"></div>
|
||||
</div>
|
||||
</div>
|
||||
<button onclick="choose_option()">Choose</button>
|
||||
<h2>Chosen Entry: <span id="result"></span></h2>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
55
js/choosing.js
Normal file
55
js/choosing.js
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
const construct_choices = () => {
|
||||
let choices = document.getElementById("choices").children;
|
||||
let start_of_next_range = 1;
|
||||
let options = [];
|
||||
|
||||
// Construct the array for choosing
|
||||
for (choice of choices) {
|
||||
let name = choice.children[0].value;
|
||||
let weight = parseInt(choice.children[1].value);
|
||||
|
||||
if (Number.isNaN(weight)) {
|
||||
break;
|
||||
};
|
||||
|
||||
options.push({
|
||||
"name": name,
|
||||
"min": start_of_next_range,
|
||||
"max": start_of_next_range + weight - 1
|
||||
});
|
||||
start_of_next_range += weight;
|
||||
};
|
||||
|
||||
return {
|
||||
"choices": options,
|
||||
"max_value": start_of_next_range - 1
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
const choose_option = () => {
|
||||
let {choices, max_value} = construct_choices();
|
||||
|
||||
// No options, error
|
||||
if (choices.length === 0 && max_value === 0) {
|
||||
document.getElementById("result").innerText = "\nERROR: No Choices to pick from";
|
||||
return;
|
||||
}
|
||||
|
||||
// Only one option exists, no need to waste time with randomness
|
||||
else if (choices.length === 1) {
|
||||
document.getElementById("result").innerText = choices[0].name
|
||||
};
|
||||
|
||||
|
||||
let chosen_value = Math.round(Math.random() * max_value);
|
||||
|
||||
|
||||
// Find the choice which the randomly chosen number fits within
|
||||
for (choice of choices) {
|
||||
if (choice.min <= chosen_value <= choice.max) {
|
||||
document.getElementById("result").innerText = choice.name;
|
||||
return;
|
||||
};
|
||||
};
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue