I'm just starting to learn JavaScript (with HTML), and so I'm trying to make a Dice Game from the course I'm doing. The two functions, ranGen1
and ranGen2
basically just generate a random number (1-6) and shows a new image for the dice to fit that.
What I'm trying to do with this scoreCounter
, is to compare ranGen1
and ranGen2
and whichever has a higher dice roll wins and adds 1 to the score on its side.
var scorePlayer1 = 0;
var scorePlayer2 = 0;
function scoreCounter(){
ranGen1();
ranGen2();
if (ranGen1() > ranGen2()){
scorePlayer1 ;
document.querySelector(".scoreCounter1").textContent = scorePlayer1;
}
else if (ranGen2() > ranGen1()){
scorePlayer2 ;
document.querySelector(".scoreCounter2").textContent = scorePlayer2;
}
}
Everything is working as it should be - the dice is producing a new image when I click the button, the points are being written in the right place (scoreCounter1
and scoreCounter2
- sorry for the naming, I'm not gonna bother coming up with something else right now), except the scoreCounter
function is super inconsistent.
Often, when ranGen1
is bigger or equal, it gives the point to ranGen2
and vice versa. And many times, it just doesn't give the points to either side.
CodePudding user response:
You're calling RanGen1()
and RanGen2()
multiple times, and they return different random numbers each time. So the results of the comparisons will change.
You should just call them once, save the results in variables, and compare these.
function scoreCounter() {
let r1 = ranGen1();
let r2 = ranGen2();
if (r1 > r2) {
scorePlayer1 ;
document.querySelector(".scoreCounter1").textContent = scorePlayer1;
} else if (r2 > r1) {
scorePlayer2 ;
document.querySelector(".scoreCounter2").textContent = scorePlayer2;
}
}