I've made a simple game for testing math facts (think practice for elementary school-age kids). It displays a random addition, subtraction, multiplication, or division problem, and feedback on if the right answer was entered.
For now it works interacts with the user via prompt()
, but I plan to add a GUI later. You can exit out of the infinite prompt()
loop by clicking cancel.
I'd like feedback on how to improve the code, particularly if there's a better way of doing the getCorrectAns()
function, and if I'm using best practices.
var maxNum = 12,
stillPlaying = true,
ans, isCorrect = '',
correctAns = '',
sign, num1 = 0,
num2 = 0,
prob, correctAns;
function randInt(max) {
return Math.floor(Math.random() * max);
}
function getCorrectAns(n1, sign, n2) {
switch (sign) {
case '+':
return n1 + n2;
case '\u2212':
return n1 - n2;
case '\xD7':
return n1 * n2;
case '\xF7':
return n1 / n2;
default:
return false;
}
}
while (stillPlaying) {
sign = ['+', '\u2212', '\xD7', '\xF7'][randInt(4)];
num1 = randInt(maxNum + 1);
num2 = randInt(maxNum + 1);
if (sign == '\u2212') num1 += num2;
if (sign == '\xF7') {
num2 = randInt(maxNum) + 1;
num1 *= num2;
}
prob = num1 + ' ' + sign + ' ' + num2;
ans = prompt(isCorrect + prob);
if (!ans) stillPlaying = false;
correctAns = getCorrectAns(num1, sign, num2);
isCorrect = (correctAns == ans) ? 'Correct! ' : 'Incorrect, ' + prob + ' = ' + correctAns + '.\n';
}
Incorrect, 0 ÷ 0 = NaN.
I think division by zero should be excluded! \$\endgroup\$