我正在创建一个游戏,将2个随机数相乘,并给出4个选项,包括正确的答案供您选择。我的问题是我不知道如何为与随机生成的答案混合的乘法问题提供正确的答案
// button to start and reset the game
btn.addEventListener("click", function(){
display.textContent = equation;
displayStyle();
for(var i=0;i<text.length; i++){
text[i].textContent=answer[i];
btn.textContent="Play Again!"
}
});
// push the random numbers in an array to be looped unto the screen
function answers(n){
var correct = [];
for(var i = 0; i<n;i++){
correct.push(randomAnswers());
}
return correct;
}
// the random 2 numbers that are multiply and seen by the user
function multply(){
var x =Math.floor(Math.random()*11);
var y =Math.floor(Math.random()*11);
return x+"x"+y+"= ";
}
function displayStyle(){
display.style.fontSize = '5rem';
display.style.border="1px white solid";
display.style.marginLeft="34%";
display.paddingRight="5%";
}
用户将选择的随机答案,我希望在混合中生成正确的答案,或者希望两个函数进行通信,以便逻辑可以在选择正确答案时进行验证
function randomAnswers(){
var a =Math.floor(Math.random()*11);
var b =Math.floor(Math.random()*11);
return a*b;
}
答案 0 :(得分:0)
问题在于multply
正在选择两个新的随机数,而不是用于创建选择项的任何数字。
randomAnswers()
函数应在返回值中包含a
和b
。然后,您可以从answers
数组中选择一个随机元素,显示相乘的数字,然后测试答案是否与乘积匹配。
let correctAnswer;
btn.addEventListener("click", function() {
const answer = answers(4);
const chosen = answer[Math.floor(answer.length * Math.random())];
display.textContent = multiply(chosen.a, chosen.b);
correctAnswer = chosen.answer;
for (var i = 0; i < answer.length; i++) {
text[i].textContent = answer[i].answer;
}
btn.textContent = "Play Again!"
});
// push the random numbers in an array to be looped unto the screen
function answers(n) {
var correct = [];
for (var i = 0; i < n; i++) {
correct.push(randomAnswers());
}
return correct;
}
// the random 2 numbers that are multiply and seen by the user
function multply(x, y) {
return x + "x" + y + "= ";
}
function randomAnswers() {
var a = Math.floor(Math.random() * 11);
var b = Math.floor(Math.random() * 11);
return {
a,
b,
answer: a * b
};
}