// beginner learning Js in a program I was asked to start work on a Rock, Paper, Scissors game this is the code I made, but the computer always choses scissors!? any idea why? any help would be awesome!
If computerChoice is between 0 and 0.33, make computerChoice equal to "rock".
If computerChoice is between 0.34 and 0.66, make computerChoice equal to "paper".
If computerChoice is between 0.67 and 1, make computerChoice equal to "scissors".
var userChoice = prompt ("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice === (0 , 0.33)) {
console.log("rock");
} else if (computerChoice === (0.34 , 0.66)) {
console.log("paper");
} else {
console.log("scissors");
}
First off, you can't just make up syntax - it Just Doesn't Work. Programming is about the application of existing rules, where most rules are not your own.
In JavaScript, due to the comma-operator, x === (a, b)
is semantically equivalent to x === b
(when the a
expression has no side-effects), so that clearly won't work. In the original code this ensured that none of the first two conditions (e.g choice === 0.33
) ever matched - so the default/else of "scissors" was always chosen.
While the general way to check an inclusive range is x >= a && x <= b
, we can do one better than this by relying on the ordering of if
conditional evaluation and "inchworming" through an expanding range.
if (choice <= 1/3) {
console.log("rock");
} else if (choice <= 2/3) { /* choice > 1/3, per above */
console.log("paper");
} else { /* choice > 2/3, per above */
console.log("scissors");
}
Alternatively, we could also get a discreet random integer back,
/* get a random number 1, 2, or 3 */
var choice = Math.floor(Math.random() * 3 + 1);
and then direct equality without a range check can be used
if (choice === 1) {
console.log("rock");
} else if (choice === 2) {
console.log("paper");
} else { /* choice === 3 */
console.log("scissors");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With