Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

56
Views
Javascript guessing game with cookie

Instruction:

Create a number guessing game to generate a number between the range of 1 and 2. The game should prompt users for their username (saved in cookie). Set range as function parameter and prompt the player to predict the generated number between the given range, at a correct guess, the game should award the player a point (also saved in cookie), and move them to stage 2 by increasing the range limit value by 1, e.g range is from 1 and 3 for stage 2 and so on.

This is what I have done so far.

playButton.addEventListener("click", () => {
  const guessingGame = (range) => {
    const rndGuess = Math.floor(Math.random() * range) + 1;
    console.log(rndGuess);
    let point = 0;
    const playerName = prompt("Please enter username");
    setCookie("username", playerName, 1);
    const guess = prompt(`Predict a number between 1 and ${range}`);
    const playerGuess = Number(guess);

    if (rndGuess === playerGuess) {
      console.log(point, "point");
      point = point + 1;
      console.log(point);
      alert(`You won!, ${playerName}, You've scored ${point} point`);
      setCookie("point", point, 1);
      guessingGame(range + 1);
      point = point += 1;
      setCookie("point", point, 1);
    } else {
      point = 0;
      alert("You lose!");
    }
  };
  guessingGame(2);
});

problem: point does not increase, and I only want to prompt username once if rndGuess === playerGuess is true.

Thanks in advance.

8 months ago · Juan Pablo Isaza
1 answers
Answer question

0

I got it working this way

playButton.addEventListener("click", () => {
  const playerName = prompt("Please enter username");
  setCookie("username", playerName, 1);
  let point = 0;
  const guessingGame = (range) => {
    const rndGuess = Math.floor(Math.random() * range) + 1;
    console.log(rndGuess);
    const guess = prompt(`Predict a number between 1 and ${range}`);
    const playerGuess = Number(guess);

    if (rndGuess === playerGuess) {
      point = point + 1;
      setCookie("point", point, 1);
      alert(`You won!, ${playerName}, You've scored ${point} point`);
      guessingGame(range + 1);
    } else {
      point = 0;
      alert("You lose!");
    }
  };
  guessingGame(2);
});
8 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs