Home > Software engineering >  While loop multiple statements in js. "The Dice Game"
While loop multiple statements in js. "The Dice Game"

Time:07-04

I have to create a dice roller game, if it lands on 2,3,6,12 the game is supposed to stop and tell me which of the numbers the sum of both my dices landed on and how many "rolls" or tries it took me to get there. I haven't been able to figure out why my program isn't working, if I erase the conditions in the while loop and leave only one for example: while(dice != 2); the program will run but it would obviously only match if it lands on 2. Please help me!

  function play() {
    var dice = -1;
    var rolls = 1;
    var numb1 = 2;
    var numb2 = 3;
    var numb3 = 6;
    var numb4 = 12;
    while (dice != numb1 || dice != numb2 || dice != numb3 || dice != numb4) {
      dice = Math.floor(Math.random() * 11)   2;
      rolls  ;

    }

    document.getElementById('results').innerHTML = 'Your dice landed on: '   dice;
    document.getElementById('rolls').innerHTML = 'Rolls: '   rolls;
    
  }

CodePudding user response:

Change your || to && in your while

function play() {
  var dice = -1;
  var rolls = 1;
  var numb1 = 2;
  var numb2 = 3;
  var numb3 = 6;
  var numb4 = 12;
  while (dice != numb1 && dice != numb2 && dice != numb3 && dice != numb4) {
    dice = Math.floor(Math.random() * 11)   2;
    rolls  ;

  }

  document.getElementById('results').innerHTML = 'Your dice landed on: '   dice;
  document.getElementById('rolls').innerHTML = 'Rolls: '   rolls;

}

play()
<div id="results"></div>
<div id="rolls"></div>

you can improve the while condition by using includes

function play() {
  var dice = -1;
  var rolls = 1;
  var numb1 = 2;
  var numb2 = 3;
  var numb3 = 6;
  var numb4 = 12;
  while (![numb1, numb2, numb3, numb4].includes(dice)) {
    dice = Math.floor(Math.random() * 11)   2;
    rolls  ;

  }

  document.getElementById('results').innerHTML = 'Your dice landed on: '   dice;
  document.getElementById('rolls').innerHTML = 'Rolls: '   rolls;

}

play()
<div id="results"></div>
<div id="rolls"></div>

CodePudding user response:

Your code doesn't work, because dice would need to be each of these numbers at the same time to work, which is impossible.

Try doing this:

while (![2, 3, 6, 12].includes(dice)) {

Also, your random function can't get 1, maybe try:

Math.floor(Math.random() * 12)   1
  • Related