JSFiddle - React, Tailwind, and code Playground
by 76484
HTML
<nav>
<button id="Reset" type="button">New Game</button>
<div class="score utilites">
Score: <span id="Score"> 0</span>
</div>
<div class="highScore utilites">
High Score: <span id="HighScore"> 0</span>
</div>
</nav>
<section id="Question"></section>
<section id="Choices"></section>
<button id="Next" type="button">
Next Question
</button>
CSS
.correct {
background: green;
}
.incorrect {
background: red;
}
.actual {
border: 1px solid green;
}
JavaScript
// shuffle function from: https://stackoverflow.com/a/33760558/3397771
function shuffle(array) {
let currentIndex = array.length, randomIndex;
// While there remain elements to shuffle.
while (currentIndex != 0) {
// Pick a remaining element.
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
return array;
}
const generateNumber = function() {
return Math.trunc(Math.random() * 12 + 1);
};
const generateOptions = (state) => {
const product = state.numbersToMultiply[0] * state.numbersToMultiply[1];
const options = (new Array(state.numOptions - 1).fill(null)).reduce((acc) => {
let nextTry = Math.round(Math.random() * 100);
// ensure no duplicates in options
while (acc.includes(nextTry)) {
nextTry = Math.round(Math.random() * 100);
}
acc.push(nextTry);
return acc;
}, [product]); // start with the correct answer
return shuffle(options);
}
const state = {
highScore: 0,
isShowOptions: false,
numbersToMultiply: [generateNumber(), generateNumber()],
numOptions: 4,
options: [],
selectedOption: null,
score: 0
};
state.options = generateOptions(state);
const choices = document.getElementById("Choices");
const highScore = document.getElementById("HighScore");
const next = document.getElementById("Next");
const question = document.getElementById("Question");
const reset = document.getElementById("Reset");
const score = document.getElementById('Score');
const render = (state) => {
const product = state.numbersToMultiply[0] * state.numbersToMultiply[1];
const optionElements = state.options.map(option => {
let className = '';
if (state.isShowOptions) {
if (state.selectedOption === option && state.selectedOption === product) {
className = 'correct';
} else if (state.selectedOption ===...