Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

While loop multiple statements in js. "The Dice Game"

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;
    
  }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading