Hi! I would like to ask if there is a java script function that functions as a randomizer.
I’m thinking of creating a game where there are many choices that will appear on screen but I want them to move and appear randomly.
Here’s the code that I have initially but it’s not working
function randomizer(doc, e) {
const gameElements = [
{ name: “opt1a”, correct: true },
{ name: “opt1b”, correct: true },
{ name: “opt1c”, correct: true },
{ name: “opt2a”, correct: false },
{ name: “opt2b”, correct: false },
{ name: “opt2c”, correct: false },
];
function shuffle(array) {
for (let i = array.length - 1; i > 0; i–) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
function generateGameElements() {
const gameContainer = doc.getElement(“background”);
gameElements.forEach((element, index) => {
const elementDiv = doc.createElement(“div”);
elementDiv.innerHTML = element.name;
elementDiv.style.position = “absolute”;
elementDiv.style.left = ${index * 100}px
;
elementDiv.style.top = ${Math.random() * 200}px
;
elementDiv.addEventListener(“click”, () => {
if (element.correct) {
alert(“Correct!”);
} else {
alert(“Incorrect!”);
}
});
gameContainer.appendChild(elementDiv);
});
}
function moveGameElements() {
const gameContainer = doc.getElement(“background”);
gameContainer.childNodes.forEach((element, index) => {
let left = parseFloat(element.style.left) || 0;
left += index + 1;
element.style.left = ${left}px
;
if (left > gameContainer.offsetWidth) {
element.style.left = “-100px”;
}
});
}