Please help me with the Javascript of my rock paper scissors game.
When I press any image sometimes nothing happens with the scores and highlighting of the images but the count of chance increases. Sometimes it happens at starting of game and sometime in between and last.
I’m trying to debug my Javascript file main.js inside assets/js folder but I’m not getting what is wrong.
Live Demo:
https://sharadcodes.github.io/rock-paper-scissors-game/
Github Repo
Please help!
Hey!
Your getRandomInt function is generating only 0, 1 and 2.
function getRandomInt() {
return Math.floor(Math.random() * Math.floor(max));
}
That’s because Math.random() returns a number between 0 (included) and 1 (not included).
So it never returns 1. If you do Math.random() * 3, it will return numbers between 0 (included) and 3 (not included). That way, if you use Math.floor() you get only 0, 1 or 2
and your function that generates the computer’s choice is thinking it is receiving numbers from 1 to 3:
function generate_C_choice() {
var random_value = getRandomInt();
var z = "";
if (random_value === 1) {
z = "rock";
} else if (random_value === 2) {
z = "paper";
} else if (random_value === 3) {
z = "scissors";
} else {
}
return z;
}
Change that to
function generate_C_choice() {
let random_value = getRandomInt();
let z = "";
if (random_value === 0) {
z += "rock";
} else if (random_value === 1) {
z += "paper";
} else if (random_value === 2) {
z += "scissors";
}
return z;
}
Also, notice that I used let
keyword (and I think you should too).
I just changed =
to +=
because I thought I couldn’t doo =
with strings, but I guess I can (?).
1 Like
Thank you @Renpet_hhh for such a thorough reply ! solved my problem