jeudi 26 mars 2015

Putting functions in an array based on a condition (if checkbox is checked)

I'm still working on my math game. It now generates random addition, subtraction, multiplication and division questions. What I did was I created functions for each type of mathematical operation and put it in an array, then I have another function to get a random one from that array. And it works! (If the question doesn't show up click the "Back to Options" button and then hit the "Click to Play" button again) Click here to see it.



//function definitions (See line 116 of jsFiddle link)
var operatorFunctions = [additionQuest,
subtractionQuest,
multiplicationQuest,
divisionQuest];

//Array randomizer
function randomFrom(array) {return array[Math.floor(Math.random() * array.length)];}
function randomOp() {
var func = randomFrom(operatorFunctions);
(func)();
}


But now I'd like to let users choose what kind of questions (operators) they would like to practice, based on what they've chosen on the start screen. My thinking is that if the checkbox is checked, then its corresponding function will be pushed into the operatorFunctions array.



var operatorFunctions = []
// Code below is wrapped in a function that is executed on start button click
if ($('#allowAddition').is(':checked')) {
allowAdd = true;
} else {
allowAdd = false;
}

if (allowAdd == true) {
operatorFunctions.push(additionQuest);
return operatorFunctions;
}


But this doesn't work at all! See it here Do you guys see any obvious flaws in my logic? I feel like it's a scope thing...?


Also, my divisionQuest function is not 100% right, sometimes the first question doesn't initialize. Also, it seems like I get the same question repeatedly when I shouldn't. (Comment the other operator functions out of the array on the first jsFiddle on line 49 to see these problems.) Do you guys see any problems in this function?



function divisionQuest() {
var self = this;
var $numberOne = getRandomInt(0,rangeMax);
var $numberTwo = getRandomInt(1,rangeMax); //Divisor cannot be zero

//CANNOT DIVIDE BY ZERO
while ($numberOne % $numberTwo != 0) {
$numberOne = getRandomInt(0,rangeMax);
$numberTwo = getRandomInt(1,rangeMax)
return $numberOne, $numberTwo;
}

self.quest = $numberOne / $numberTwo;
self.formatquest = $numberOne + " ÷ " + $numberTwo; //Tidy it up a bit
$questionHolder.html(self.formatquest);
$questionHolder.hide().fadeIn(600);
}




Aucun commentaire:

Enregistrer un commentaire