Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

121
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.

about 4 years 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);
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!