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

Detailed explanation of padding and abbreviations within the CSS box model

As shown above, padding values ​​are composite at...

Detailed explanation of the basic commands of Docker run process and image

Table of contents 1. Run workflow 2. Basic comman...

Summary of the pitfalls of using primary keys and rowids in MySQL

Preface We may have heard of the concept of rowid...

About the problem of writing plugins for mounting DOM in vue3

Compared with vue2, vue3 has an additional concep...

Detailed explanation of the use of bus in Vue

Vue bus mechanism (bus) In addition to using vuex...

MySQL database architecture details

Table of contents 1. MySQL Architecture 2. Networ...

Web front-end development CSS related team collaboration

The front-end development department is growing, ...

How to insert Emoji expressions into MySQL

Preface Today, when I was designing a feedback fo...

Example analysis of mysql non-primary key self-increment usage

This article uses an example to illustrate the us...

Vue project implements left swipe delete function (complete code)

Achieve results The code is as follows html <t...

K3s Getting Started Guide - Detailed Tutorial on Running K3s in Docker

What is k3d? k3d is a small program for running a...

About Zabbix forget admin login password reset password

The problem of resetting the password for Zabbix ...

Two ways to understand CSS priority

Method 1: Adding values Let's go to MDN to se...