Pure JavaScript to implement the number guessing game

Pure JavaScript to implement the number guessing game

Develop a number guessing game that randomly selects a natural number within 100 and invites players to guess the number within 10 rounds. After each round the player should be told whether his answer was correct or not, and if he was wrong, whether the number was too low or too high. And the number guessed by the player in the previous round should be displayed. Once a player guesses correctly, or runs out of chances, the game ends. After the game ends, players can choose to start again.

thinking:

1. Randomly generate a natural number within 100

2. Record the player’s current round number. Start from 1

3. Provide players with a way to guess numbers

4. Once a result is submitted, record it first so that users can see their previous guesses

5. Then check if he is correct

6. If correct:

1. Display a congratulatory message

2. Prevent players from guessing

3. Display space for continuous players to restart the game

7. If something goes wrong

1. Tell the player they are wrong

2. Word order They enter another guess

3. Round number plus 1

8. If an error occurs and the player has no turns left

1. Tell the player that the game is over

2. Prevent players from guessing

3. Display space allows players to restart the game

9. Once the game is restarted, make sure the game logic and UI are fully recharged and return to step 1

HTML code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Guess the number game</title>
    <script type="text/javascript" src="./JS/Guess the number game.js" async></script>
/*Change according to your actual situation*/
  </head>
  <body>
    <p class="guesses"></p>
    <p class="lastResult"></p>
    <p class="lowOrHi"></p>
    <label for="guessField">Please guess the number:</label>
    <input type="text" id="guessField" class="guessField" />
    <input type="submit" value="OK" class="guessSubmit" />
  </body>
</html>

js code:

let randomNumber = Math.floor(Math.random() * 100) + 1;
const guesses = document.querySelector(".guesses");
const lastResult = document.querySelector(".lastResult");
const lowOrHi = document.querySelector(".lowOrHi");
const guessSubmit = document.querySelector(".guessSubmit");
const guessField = document.querySelector(".guessField");
let guessCount = 1;
let resetButton;
/* Game logic */
function checkGuess() {
  /* Get the user input and convert it into a numeric value*/
  let userGuess = Number(guessField.value);
  if (guessCount === 1) {
    guesses.textContent = "Last guess:";
  }
  guesses.textContent += userGuess + " ";
 
  if (userGuess === randomNumber) {
    lastResult.textContent = "Congratulations! You guessed it right";
    lastResult.style.backgroundColor = "green";
    lowOrHi.textContent = "";
    setGameOver();
  } else if (guessCount === 10) {
    lastResult.textContent = "!!! GAME OVER !!!";
    setGameOver();
  } else {
    lastResult.textContent = "You guessed wrong";
    lastResult.style.backgroundColor = "red";
    if (userGuess < randomNumber) {
      lowOrHi.textContent = "You guessed too low";
    } else {
      lowOrHi.textContent = "You guessed too high";
    }
  }
  guessCount++;
  guessField.value = "";
  guessField.focus();
}
/* End the game */
function setGameOver() {
  guessField.disabled = true;
  guessSubmit.disabled = true;
  resetButton = document.createElement("button");
  resetButton.textContent = "Start a new game";
  document.body.appendChild(resetButton);
  resetButton.addEventListener("click", resetGame);
}
/* Initialization */
function resetGame() {
  guessCount = 1;
  const resetParas = document.querySelectorAll(".resultParas p");
  for (let i = 0; i < resetParas.length; i++) {
    resetParas[i].textContent = " ";
  }
 
  resetButton.parentNode.removeChild(resetButton);
  guessField.disabled = false;
  guessSubmit.disabled = false;
  guessField.value = "";
  guessField.focus();
  lastResult.style.backgroundColor = "white";
  randomNumber = Math.floor(Math.random() * 100) + 1;
}
guessSubmit.addEventListener("click", checkGuess);

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • An example of a code for a guessing game based on JavaScript
  • JS guessing number game example explanation
  • JavaScript to implement the number guessing game
  • JS implements a web-based guessing game
  • jsp+servlet to realize the number guessing game
  • JSP implements the millionaire guessing game
  • An example of generating random numbers and guessing the size of numbers implemented by AngularJS
  • AngularJS implements the function of guessing the size of numbers
  • js implements a number guessing game
  • Simple implementation code of js guess number game

<<:  Detailed steps to install mysql 8.0.18-winx64 on win10

>>:  Solution to the error when calling yum in docker container

Recommend

Why is IE6 used by the most people?

First and foremost, I am a web designer. To be mor...

Use of docker system command set

Table of contents docker system df docker system ...

Example code for implementing page floating box based on JS

When the scroll bar is pulled down, the floating ...

Comparison between Redis and Memcache and how to choose

I've been using redis recently and I find it ...

Good website copywriting and good user experience

Looking at a website is actually like evaluating a...

Advanced Usage Examples of mv Command in Linux

Preface The mv command is the abbreviation of mov...

Detailed explanation of how to use the canvas operation plugin fabric.js

Fabric.js is a very useful canvas operation plug-...

How to authorize all the contents of a folder to a certain user in Linux?

【Problem Analysis】 We can use the chown command. ...

HTML user registration page settings source code

Design the web page shown above: <!DOCTYPE htm...

It's the end of the year, is your MySQL password safe?

Preface: It’s the end of the year, isn’t it time ...

How to use Javascript to generate smooth curves

Table of contents Preface Introduction to Bezier ...

Vue+SSM realizes the preview effect of picture upload

The current requirement is: there is a file uploa...

How to pass W3C validation?

In addition to setting regulations for various ta...