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

On-page refresh triggering HTTP 404 error in Vue3 routing situation

Issue Upon reloading a route, such as /installer, in Vue3.js, I encounter the following error: https://i.sstatic.net/UKxdk.png Code Snippet I am utilizing the Router with the setup below: const router = createRouter({ history: createWebHistory(proces ...

React Native encounters issues with removing the reference to the callback attribute upon unmounting

Utilizing a component that I place in an array (of various sizes) and controlling individual components through refs, while adding refs to an object to keep track of each separately. constructor(props){ super(props); this.stamps = []; this.get ...

Tips on converting comma-separated values into HTML table rows using <tr> tags

JSON Data { "catalog_name": ["Sistem Autodownline ", "Karipap Pusing Ayu"], "price": ["100", "8"], "qty": "", "qty2": ["", ""], "total_qty": "", "total": "", "mem": "10", "email_2": "", "ic_add": "890527-08-6136", "c ...

Displaying only the validation messages that are accurate according to the Vuetify rules

<v-text-field label='New Password' class="required" v-model='password' type='password' :rules="passwordRules" required> </v-text-field> passwordRules: [ value => !!value || 'Pl ...

What is the method for setting a default value for a disabled input?

<input type="checkbox" disabled="disabled" checked="checked" name="is_ok" id="id_is_ok"/> Is there a way to set a default value for this disabled input? I've noticed that if this field is disabled and I make edits to my data, the changes are n ...

Advancing past the stage of developing basic functions in the document.ready() event handler

When I develop a website, I have a personal preference of creating a main JavaScript file with window.load and window.ready functions at the top. I find it easier to refactor any logic into separate functions within these functions for better readability. ...

Socket.io-powered notification system

I'm currently in the process of developing a notification system for my Events Manager Website. Every time a user is logged in and performs an action (such as creating an event), a notification about the event creation should be sent to other user ...

Start up Angular with a Fire $http.get when the page loads

I am facing an issue where my $http.get() request is firing after the home page has already loaded. How can I ensure that the request fires before the page loads so I can utilize the returned data on the page? Here is a snippet of the routing code: var l ...

Reload entire page for AJAX request if JavaScript is not enabled

Currently utilizing JSF2. I have a button that triggers an action and then updates a section of the page (fairly standard). <h:commandButton value="foo" action="#{myBean.myAction}" > <f:ajax execute="@form" render="#content" /> ...

Creating visualizations by overlaying shapes onto images using specified coordinates in jQuery

I have a web application in development that integrates with the skybiometry API. Their demo showcases a fantastic user feedback system displayed after facial recognition, similar to the one shown below. I am currently working on implementing a similar fe ...

Sorting through a collection by using a nested array

I've been working on optimizing my code to prevent making new http requests to my API every time I need to filter results. Currently, I have an array called pageContent that is populated with data from an API fetch when the page loads. Each object in ...

What is the process of integrating an HTML web component with an HTML file? Can I use innerHTML = foo("myfile.html") to achieve

Using HTML web components allows me to define their code using this method: this.innerHTML = `<h1></h1>`; However, I find it cumbersome as I do not have access to the Emmet Abbreviation feature which slows down my component creation process. ...

Placing jQuery in the lower part of my HTML templates lacks adaptability

Lately, I've been optimizing my templates by placing the jQuery code link at the end of the template files to ensure fast page load speeds. Along with that, I have specific javascript modules reserved for certain pages that are included within the con ...

Can you explain the significance of the res.render callback parameter in Express 4.0 for Node.js?

Can you explain the role of the res.render callback argument? When would it be necessary to use this callback argument, especially when there is already a template specified as the first argument? The following code snippet is taken from the official doc ...

React - Component not updating after Axios call in separate file

Recently I decided to delve into React while working on some R&D projects. One of my goals was to build an application from scratch as a way to learn and practice with the framework. As I started working on my project, I encountered a rather perplexin ...

Inquiring about the functionality of vertical and horizontal scrolling in jQuery localscroll

I recently finished building a webpage at . On this page, I have a set of main links along with corresponding sublinks. Currently, clicking on a main link causes the content to scroll vertically, while clicking on a sublink like Blue Inner Link 1 results i ...

Using Javascript to Retrieve Object-Related Information from an Associative Array

I have a list of students' names along with the grades they achieved for the semester. How can I modify my JavaScript code to display the first names of students who earned an "A" grade based on the array provided? This is my current progress, but I k ...

Include a back button during the loading of a URL in an Electron application

Within my Electron application, I have implemented elements that, upon clicking, redirect to a URL. However, navigating back to the previous (local) page is not currently achievable. Is there a feasible method to incorporate a layered back button on top o ...

Creating a custom jQuery selector

I've been struggling with a particular problem all day today, trying different approaches but still unable to find a solution. The crux of the issue is this: I have multiple JavaScript functions running to determine whether certain variables should b ...

Sending state properties to components within a route

In my React structure, I have the following setup: <Provider store={ store }> <Router> <Switch> <Route path="/how-to" component={ Help } /> <Route path="/start" c ...