What is the process for reverting variables back to their original values using pure Javascript?

I am working on developing a hangman game using vanilla javascript and I need some assistance with resetting the game after a player loses. Specifically, I would like to: 1. Reset the "guessRemain" variable. 2. Clear out the "guess" id so that none of the guessed letters are displayed. 3. Choose another random word from the array.

Your help is greatly appreciated!

<!DOCTYPE html>
<html lang="en-us">
<head>
  <meta charset="UTF-8">
  <title>Hangman Game</title>

  <link rel="stylesheet" type="text/css" href="assets\css\reset.css"/>
  <link rel="stylesheet" type="text/css" href="assets\css\style.css">
  <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">

  <script src="https://use.fontawesome.com/ca6de464ee.js"></script>

</head>
<body>
    <div id="white">
        <img src="assets\images\turkey.png" alt="turkey" class="turkeyImage">
    </div>
    <div id="orangebox">
        <h4>thanksgiving</h4>
        <h4 class="hangman">hangman</h4>
    </div>
    <div class="instructions">
        <h1>Instructions:</h1>
        <br/>
        <h2>1. Guess a Thanksgiving dish!</h2>
        <br/>
        <h3>2. Press any key to begin.</h3>
    </div>
    <div class="display">
        <p class="greywords">Current Word:</p>
        <br/>
        <p id="current"></p>
        <br/>
        <br/>
         <p class ="greywords">Number of Guesses Remaining:</p>
         <br/>
         <p id="remain"></p>
         <br>
         <br/>
         <p class="greywords">Letters Already Guessed:</p>
         <p id="guess"></p>
         <br>
         <br/>
         <p class="greywords">Wins:</p>
         <p id="win"></p>
         <br>
         <br/>
         <p class="greywords">Losses:</p>
         <p id="loss"></p>
     </div>

<!-- End of HTML -->

<script type="text/javascript">

// Step 2: create variable of the food words
var wins = 1;
var losses = 1;
var guessRemain = 10;
var foodWords = [
 "pie",
 "turkey",
 "bacon",
 "bread"
 ];


// Step 1: display remaining gueses
document.getElementById("remain").innerHTML = guessRemain;
// Step 3: create a variable to pick a random word from that array
var randomWord = foodWords[Math.floor(Math.random() * foodWords.length)];
console.log(randomWord);
//Step 4: make it count the number of letters in that word that you just picked
var count = [];
 for (var i = 0; i < randomWord.length; i++) {
 count[i] = "_ ";
 }
//Step 5: write the var on the screen
document.getElementById("current").innerHTML = count;

//Step 6: have it recognize that there are remaining letters
var remainingLetters = randomWord.length;
    console.log("I HAVE " + remainingLetters + " left");

//Step 7: function for when they click a key
document.onkeyup=function(event) {
    var userGuess = event.key;
    document.getElementById("guess").innerHTML += userGuess + " ";
    // console.log(randomWord.length);
    if (randomWord.includes(userGuess)) {
        // console.log("test");
// Step 7: if this statment is true, then modify the count variable, replace the dash in count with letter, and it has the correct position, and display the letter
    var guessIndex = randomWord.indexOf(userGuess);
    //console.log(randomWord.indexOf(userGuess));
    count[guessIndex] = userGuess
    //console.log(count);
    document.getElementById("current").innerHTML = count;
    remainingLetters--;
    console.log("I HAVE " + remainingLetters + " left");
    if (remainingLetters === 0) {
        document.getElementById("win").innerHTML = wins++;
        console.log("I have won");}
}
// Step 8: if not true, then subtract a guess

    else {
       document.getElementById("remain").innerHTML = guessRemain--;
       document.getElementById("remain").innerHTML = guessRemain;
        if (guessRemain === 0) {
        document.getElementById("loss").innerHTML = losses++;
        console.log("I have lost");
    }
            }
}
// Step 10: if there are no letters remaining in count, then add "1" to the win id and reset the page

        // if (remainingLetters === 0) {
        // document.getElementById("#win").innerHTML = winSs++;
        // console.log("I have won");
        //console.log("i win");
        // function reset() {
        // document.getElementById("display").reset();
        // }
// }
// Step 11: if there are no guesses remaining, add a "1" to the loss id and reset the page
        // if (remainingGuess < 0) {
        // document.getElementById("#loss").innerHTML = ++1;
        // function reset() {
        // document.getElementById("display").reset();
        // }
        // }

 </script>
</body>
<div class="footer">
</div>
</html>

Answer №1

To clear the value of a variable and start fresh, simply assign a new value to it like this:

guessRemain = 10;

This can be done within your reset function, along with any other variables you need to reset.

If you want to remove any guesses already displayed on the web page, you can use JavaScript like this:

document.getElementById("guess").innerHTML = "";

I hope this solution is helpful for you!

Answer №2

To begin, ensure to empty the guess element in one of the first 6 steps by setting its innerHTML to an empty value. Organize these steps 1-6 within a function named initialize as shown below:

Update: Define your variables wins, losses, guessRemain, foodWords, randomWords, count, remainingLetters outside of the function mentioned so that they are accessible within your onkeyup handler.

var wins, losses, guessRemain, foodWords, randomWords, count, remainingLetters;

function initialize() {

    // Step 1: create variable of the food words
    wins = 1;
    losses = 1;
    guessRemain = 10;
    foodWords = [
     "pie",
     "turkey",
     "bacon",
     "bread"
     ];

    // Clear the guess
    document.getElementById("guess").innerHTML = "";

    // Step 2: display remaining guesses
    document.getElementById("remain").innerHTML = guessRemain;

    // Step 3: generate a random word from the array
    randomWord = foodWords[Math.floor(Math.random() * foodWords.length)];
    console.log(randomWord);

    //Step 4: count the number of letters in the selected word
    count = [];

    for (var i = 0; i < randomWord.length; i++) {
        count[i] = "_ ";
    }

    //Step 5: display the var on the screen
    document.getElementById("current").innerHTML = count;

    //Step 6: acknowledge the existence of remaining letters
    remainingLetters = randomWord.length;

    console.log("I HAVE " + remainingLetters + " left");

}

Invoke the function initialize() at a appropriate location in your code (outside of the onkeyup handler) to commence your game initially.

Subsequently, you can reuse the initialize function whenever you need to restart your game. For instance, incorporate this code towards the end of your onkeyup handler like so:

if (remainingLetters === 0 || remainingGuess === 0) {
    inititalize();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using regular expressions, eliminate the element from a JSON object that contains a specified property

Imagine I have a string representing a JSON object. It could be invalid, with some params that will be replaced by another system (e.g. %param%). The task at hand is to remove all objects with a known propertyName equal to "true" using regex. { "someT ...

What is preventing me from deleting cookies on Express?

Whenever a new user is registered, the number of cookies just keeps increasing endlessly. userRoutes.js: const { registerUser, loginUser, registerVerify } = require("./userController"); const express=require('express') const router=ex ...

Is the issue with AJAX and a global variable a result of my misunderstanding?

My goal is to use AJAX to load client data onto a page and then replace a company ID with the corresponding name from a different company table in the same database. However, I am facing an issue where the global JavaScript variable is not being updated wi ...

What is the best approach to integrating an idle timeout feature with identityserver4 and aspnet identity for a secure implementation?

Currently, I am developing a login site using IdentityServer4 (server UI) with .NET Identity in .NET Core 2.2 Razor Pages. I have implemented a javascript modal alert that notifies users of an impending idle timeout and redirects them to the logout screen ...

Nuxtjs is incorporating the Vue-pano component for enhanced functionality

When using vue-pano with Nuxtjs, I encountered the error message: "window is undefined". If I import it like this: <script> import Pano from 'vue-pano' export default { components: { Pano } } </script> I then tried using a ...

What is the process for adjusting the form transition?

I am currently working on a form that has a transition effect However, I encountered an issue: check out the problem here My goal is to keep the magnifying glass fixed in place while the form moves Here is a snippet of my code: import Search fro ...

Execute AJAX request for two individual buttons

I have a scenario where I want to use two buttons to open separate PHP pages, but I would like to trigger both buttons with a single function. The AJAX function should then determine which button was clicked and open the corresponding PHP page - for exam ...

Initiate the React application with the given external parameters

I have created a React app that is embedded within a webpage and needs to start with specific parameters obtained from the page. Currently, I am passing these parameters in the index.HTML file within a div element. The issue arises when these parameters ar ...

Ensure that a div with fluid width remains consistently centered within another div

I have a bunch of boxes filled with content. The number of boxes in each row varies depending on the width of the browser window. Is there a way to ensure that all the boxes are always horizontally centered on the page? For guidance, you can check out th ...

What are some methods for bypassing the use of a keypad for a specific input

I have a mobile app built with Ionic. When the user taps on any input field, the keypad opens which works well. However, I have a datepicker with an input field where I want to prevent the keypad from opening. How can I achieve this? <div class="col" ...

Using discord.js to conveniently set up a guild along with channels that are equipped with custom

When Discord devs introduced this feature, I can't seem to wrap my head around how they intended Discord.GuildManager#create to function. How could they possibly have expected it to work with Discord.GuildCreateOptions#channels[0], for instance, { ...

Error message in Node.js: Unable to establish connection to 127.0.0.1 on port 21 due to E

I am currently developing a simple application using node js, and I have encountered the following issue: Error: connect ECONNREFUSED 127.0.0.1:21 at Object exports._errnoException (util.js:1034:11) at exports _exceptionWithHostPort (util.js:1057: ...

Merging double borders in a div using CSS is essential for creating

Upon examining this sample, it's evident that the borders do not blend together. css: div{ float:left; background-color:moccasin; width:100px; height:100px; border:1px solid tomato; } The number of divs is arbitrary, and only on ...

Check the Full Calendar to see if any events are scheduled for today

I have a group of users who need to save their availability. Currently, I am utilizing Full Calendar and looking for a way to prevent them from adding the same event multiple times on a single day. My tech stack includes VueJs and all events are stored in ...

Promises and Their Valuable Variables

Recently I began learning JavaScript and I'm encountering some confusion. Here's the code snippet that is causing me trouble: api.posts .browse({ limit: 5, include: 'tags,authors' }) .then(posts => { posts.forEach(post =&g ...

The following 13 error occurred in the node_modules/next/dist/esm/server/web/spec-extension/cookies/serialize.js file

Every time I try to use the serialize function in my application on Next, it throws errors. Error - node_modules/next/dist/esm/server/web/spec-extension/cookies/serialize.js (40:0) @ parseCookieString Error - URI malformed I have attempted numerous soluti ...

Incorporating a Custom CKEditor5 Build into an Angular Application

I am currently in the process of developing an article editor, utilizing the Angular Integration for CKEditor5. By following the provided documentation, I have successfully implemented the ClassicEditor build with the ckeditor component. Below are the ess ...

What is the best way to link labels with input fields located separately in Angular?

Imagine a scenario where labels and form fields are being created in a *ngFor loop, as shown below: app.component.ts export class AppComponent { items = ['aaa', 'bbbbbb', 'ccccccccc'] } app.component.html <div class ...

Using Javascript/JQuery to extract numbers from a URL with regex or alternative methods

I need help extracting a specific group of consecutive numbers from the following URLs: www.letters.com/letters/numbers/letters" and www.letters.com/letters/letters/numbers/symbols Is there a way to isolate only the continuous sequence of numbers in th ...

Emphasize the URL of the current page and navigate up one level

I have a list of links in my navigation. I want the current page's link to be highlighted, as well as the parent page's link one level up. For example: All pages: /blog, blog/careers, blog/authors Page: /blog/author Highlight: /blog/author, /blo ...