Reputation: 17
I'm making a game that starts of with 15-30 stones in a pile, and both the user and computer take stones until the last stone is taken. However, I need a function to determine whether the amount of stones the user take is valid, meaning it is less than or equal to 3 and greater than 0. So my function is supposed to return either true or false, but when I enter "2", it returns false. Here's the code invovled:
var valid = validEntry(stones, stonesTaken);
function validEntry(stones, stonesTaken) {
if (stones >= stonesTaken) {
if(stonesTaken <= 3 && stonesTaken > 0) {
return true;
} else {
return false;
}
} else {
return false;
}
}
P.S.-- Whenever the stones goes under three, the player nor the computer can take more stones than are available, which is why the first if statement is there.
Upvotes: 1
Views: 595
Reputation: 7242
Make sure you pass integer values or just use parseInt()
as @Jared Farrish mentioned in comments.
function validEntry(stones, stonesTaken) {
stones = parseInt(stones);
stonesTaken = parseInt(stonesTaken);
if (stones >= stonesTaken) {
if(stonesTaken <= 3 && stonesTaken > 0) {
return true;
} else {
return false;
}
} else {
return false;
}
}
Upvotes: 0
Reputation: 173562
That's because you're comparing strings:
"19" >= "2" // false
You have to cast at least one variable into an integer, assuming they're both strings:
stones = parseInt(stones, 10);
stonesTaken = parseInt(stonesTaken, 10);
Upvotes: 1