let dice = Math.trunc(Math.random() * 6) 1;
while (dice !== 6) {
console.log(`you rolled ${dice}`);
dice = Math.trunc(Math.random() * 6) 1;
if (dice === 6) {
console.log("Game over at 6");
}
}
CodePudding user response:
At the first line dice is given a value between 1-6, if it is not 6 it goes inside the loop and tells you what you rolled. If we don't reassign the dice variable it results with dice being the same value at the first line and the code is stuck inside an infinite loop since the dice was not 6 and will never be 6. We need to reassign it so that the dice can become 6 if it was not at the first line and end the game.
PS. if the dice is 6 at the first line it wont print Game over.
CodePudding user response:
On line 1 you give dice a random value between 1 and 6. On line 2 you state that while the value is not 6 you should do what's in the while loop. On line 4 you give dice a new random value between 1 and 6. Then you check if the code is 6.
Also I hope this code is very poorly written with bad understanding of programing. Don't expect to learn to code properly from the teacher that gave it to you.
Here is a better way to do it.
while true {
let dice;
dice = Math.trunc(Math.random() * 6) 1;
console.log(`you rolled ${dice}`);
if (dice === 6) {
console.log("Game over at 6");
break; // this will end the while loop
}
}