-2

I'm working on a little dice game but i'm having a problem checking if the number is between 1 and 6.

For an example 1,2,3,4,5,6 all work fine but if i put a zero in front of the number it will still roll the dice but i want it to be only a number from 1 to 6 and i can workout what i'm doing wrong and was hoping maybe someone could tell me.

let diceRolled = false;

const rollDice = (guess) => {
  console.log('guess:', guess);
  
  if (guess == '' || guess === undefined) {
    console.log(`You didn't pick a number from 1 to 6`);
  } else if (diceRolled) {
    console.log(`Dice has already been rolled. Please try again soon.`);
  } else if (!(guess > 0 && guess < 7)) {
    console.log(`You can only pick a number from 1 to 6`);
  } else {
    diceRolled = true;
    let dice = Math.floor(Math.random() * 6) + 1;
    console.log(`Dice has been rolled.`);
    setTimeout(() => {
      if (dice == guess) {
        console.log(`Correct guess - The dice landed on: ${dice} :thumbsup:`);
      } else {
        console.log(`Incorrect guess - The dice landed on: ${dice} :thumbsdown:`);
      }
      diceRolled = false;
    }, 5000);
  }
};

rollDice('03');
yellowleg
  • 1
  • 1

1 Answers1

-1

The below should answer your question. Specifically, I've replaced the !(guess > 0 && guess < 7) condition with !Array.from('123456').includes(guess).

let diceRolled = false;

const rollDice = (guess) => {
  console.log('guess:', guess);
  
  if (guess == '' || guess === undefined) {
    console.log(`You didn't pick a number from 1 to 6`);
  } else if (diceRolled) {
    console.log(`Dice has already been rolled. Please try again soon.`);
  } else if (!Array.from('123456').includes(guess)) {
    console.log(`You can only pick a number from 1 to 6`);
  } else {
    diceRolled = true;
    let dice = Math.floor(Math.random() * 6) + 1;
    console.log(`Dice has been rolled.`);
    setTimeout(() => {
      if (dice == guess) {
        console.log(`Correct guess - The dice landed on: ${dice} :thumbsup:`);
      } else {
        console.log(`Incorrect guess - The dice landed on: ${dice} :thumbsdown:`);
      }
      diceRolled = false;
    }, 5000);
  }
};

rollDice('3');

However, I'm curious to why 01, 02, 03, 04, 05, 06 aren't accepted?

Levi Cole
  • 3,561
  • 1
  • 21
  • 36