OK, what result do you get?
I don’t see where you call the roll() function so I’m guessing undefined for currentScore and NaN for totalScore.
You need to call the function somewhere in your code. (You might also have another typo at the top where you declare totalscore and then set totalScore to zero.)
Your guess is correct. I am calling the function through a button in the html file. I wanted to insert the link to my project but forum is unfortunately not permitting me to include the link. You may find the project live on spot-light dot ga . And its the Dice 2 Game
Here is the complete Java Code.
var n1,n2,currentScore1,currentScore2,totalScore1,totalScore2;
currentScore1 = 0;
currentScore2 = 0;
totalScore1 = 0;
totalScore2 = 0;
//Generate Random Number via function
function roll(){
n1 = Math.floor(Math.random()*6 +1);
n2 = Math.floor(Math.random()*6 +1);
//Display Dice
document.querySelector(".player1 img").src = "images/" + n1 + ".png";
document.querySelector(".player2 img").src = "images/" + n2 + ".png";
//Display Current Score
document.querySelector("#currentScore1").innerHTML = n1;
document.querySelector("#currentScore2").innerHTML = n2;
}
//Adding Current Score to Total Score
totalScore1 += currentScore1;
totalScore2 += currentScore2;
//Displaying Total Score
document.querySelector("#totalScore1").innerHTML = totalScore1;
document.querySelector("#totalScore2").innerHTML = totalScore2;
Shouldn’t the total score be updated within the function? Or maybe make another function that updates the total score and prints it, and call that from within roll().
And it’s JavaScript code, not to be confused with Java.
Thank you for pointing out the issue. I included the adding totalScore lines within the roll function and now it is working. Could you please explain what do you mean by " And it’s JavaScript code, not to be confused with Java." . Honestly speaking, I have no idea what do you mean by that. I openly admit that I have just started learning JavaScript and got to the point, where they started explaining DOM manipulation basics.
Here is the code after your suggestion and it is working. Though it works but can you identify if something is wrong with it.
var n1,n2,totalScore1,totalScore2;
totalScore1 = 0;
totalScore2 = 0;
//Generate Random Number via function
function roll(){
n1 = Math.floor(Math.random()*6 +1);
n2 = Math.floor(Math.random()*6 +1);
//Adding Current Score to Total Score
totalScore1 += n1;
totalScore2 += n2;
//Display Dice
document.querySelector(".player1 img").src = "images/" + n1 + ".png";
document.querySelector(".player2 img").src = "images/" + n2 + ".png";
//Display Current Score
document.querySelector("#currentScore1").innerHTML = n1;
document.querySelector("#currentScore2").innerHTML = n2;
//Displaying Total Score
document.querySelector("#totalScore1").innerHTML = totalScore1;
document.querySelector("#totalScore2").innerHTML = totalScore2;
}