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

Introduction to ApplicationHost.config (IIS storage configuration area file)

For a newly created website, take ASP.NET MVC5 as...

Linux tutorial on replacing strings using sed command

To replace a string, we need to use the following...

MySQL 8.0.15 version installation tutorial connect to Navicat.list

The pitfalls 1. Many tutorials on the Internet wr...

Solution to nacos not being able to connect to mysql

reason The mysql version that nacos's pom dep...

A detailed introduction to Linux memory management and addressing

Table of contents 1. Concept Memory management mo...

How to implement Mysql switching data storage directory

How to implement Mysql switching data storage dir...

Implementation of CSS dynamic height transition animation effect

This question originated from a message on Nugget...

Vue implements Dialog encapsulation

Table of contents Vue2 Writing Vue3 plugin versio...

Why is the scroll bar on the web page set on the right?

Why are the scroll bars of the browsers and word ...

TCP third handshake data transmission process diagram

The process packets with the SYN flag in the RFC7...

Detailed analysis of javascript data proxy and events

Table of contents Data Brokers and Events Review ...

Try Docker+Nginx to deploy single page application method

From development to deployment, do it yourself Wh...

Detailed introduction to linux host name configuration

Table of contents 1. Configure Linux hostname Con...

Several ways to generate unique IDs in JavaScript

Possible solutions 1. Math.random generates rando...