I'm trying to make a very basic dice game (new to Javascript). On the page load, the 'dice' is 'rolled' three times and the results are displayed, with a message to say whether you managed to roll a 6 or not. I'm trying to put in a permanant message about how many games have been won - problem is, if you look at my code below, the variable I'm using for this 'wins' is incremented each time there is a win, but it only actually displays two values: 0 if the user just lost, and 1 if it was a win. It never gets to a higher number no matter how many times the dice is rolled. Wondering if anyone has a solution/explanation?
Code:
console.log("Dice game. You have 3 tries to roll a 6 - go");
var rolls = 0;
var wins = 0;
function rollDice() {
var dice = Math.random();
if (dice <= .17) {
dice = 1;
}
else if (dice <= .33) {
dice = 2;
}
else if (dice <= .50) {
dice = 3;
}
else if (dice <= .67) {
dice = 4;
}
else if (dice <= .84) {
dice = 5;
}
else if (dice <= 1) {
dice = 6;
}
return dice;
}
function diceGame() {
do {
var dice = rollDice();
console.log(dice);
rolls++;
if (dice === 6) {
console.log("You won!");
wins++;
if (rolls === 1) {
console.log("It took " + rolls + " try");
}
else {
console.log("It took " + rolls + " tries");
}
break;
}
}
while (rolls <= 2);
if (dice !== 6) {
console.log("You lost");
}
}
diceGame();
console.log("Times won: " + wins);