Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Create the Loop – One Solution

My solution with easy changeable values option.

const main = document.querySelector('main');
let randomNumber;
let guess;
const upper = 6;
const guessChancesNumber = 3;
const gameRules = alert(`Hello !
You are about to play a guessing game. 
The machine is thinking to a number and you have ${guessChancesNumber} chances to guess it. Good luck ! `);

function getRandomNumber(upper) {
  return Math.floor(Math.random() * upper) + 1;
};
for (i = 1; i <= guessChancesNumber; i++) {
  randomNumber = getRandomNumber(upper);
  console.log(randomNumber);
  guess = prompt(`I am thimking of a number betweeen 1 and ${upper}. What is it ?`);
  if (parseInt(guess) == randomNumber) {
    main.innerHTML = `<h1> It was ${randomNumber} .You guessed it ! Congrat !!!</h1>`;
    break;
    // Terminate the loop if the user guesses the number
  } else {
    // The game is over because the user have no more guessing chances left.
    main.innerHTML = `<h1> It was number ${randomNumber} .You have ${guessChancesNumber - i} guesses left! Try again.</h1>`;
  }
};

It is a solution where someone can change many variables values - like how many chances for guessing, the random number upper limit etc. Any feedback really appreciated. Thank you !

1 Answer

P.S. Here is a link to my Workspace snapshot: https://w.trhou.se/8d9jran0ek .

Thank you so much for your time.