What could be causing my function to not loop properly without any errors being displayed?

I'm currently working through a Javascript tutorial from a book that guides me in creating a hangman game using only functions. I'm almost at the end but I've hit a roadblock... My function seems to not be looping properly, specifically, my prompt message stops after the first input and doesn't continue for additional guesses, even though it should as part of the loop implementation. It's a simple issue, but I can't seem to get past it. If someone could take a look, I would appreciate it.

I've attempted to use "console.log" within an "if" statement and inside a "for" loop to check if the loop is functioning correctly. The loop works, but the prompt doesn't repeat as expected. I'm unsure why this is happening...

var updateGameState = function (guess, word, answerArray) {
// Update answerArray and return a number indicating how many times
// the guess appears in the word so remainingLetters can be updated

    for (var j = 0; j < word.length; j++) {
            if (word[j] === guess && answerArray[j] !== word[j]) {
                answerArray[j] = guess;
                remainingLetters--;

                };

    }; getGuess();
        console.log(answerArray);   

};

var remainingLetters = word.length;
var correctGuesses = updateGameState(guess, word, answerArray);

Currently, I just need my prompt message to keep popping up until I'm able to input all my letters/guesses...

----Below are the .js and html files----

var pickWord = function(random) {
  // Retrieve a random word
  return random[Math.floor(Math.random() * random.length)];

};

var word = pickWord(["fakultet", "zirafa", "trava", "labelo"]);
console.log(word);

var setupAnswerArray = function(word) {
  // Generate the answer array
  var answerArray = [];
  for (i = 0; i < word.length; i++) {
    answerArray[i] = "_";
  }
  console.log(answerArray);
  return answerArray;
};
var answerArray = setupAnswerArray(word);

var showPlayerProgress = function(answerArray) {
  // Use alert to display the player their progress
  return alert(answerArray.join(" "));
};
showPlayerProgress(answerArray);

var getGuess = function() {
  // Utilize prompt to fetch a guess
  return (prompt("Guess a letter, or click Cancel to stop playing " + answerArray)).toLowerCase();
};
var guess = getGuess();
console.log(guess);

// PROBLEM OCCURS HERE
///*******************************************************
var updateGameState = function(guess, word, answerArray) {
  // Modify answerArray and provide a count of how many times
  // the guess appears in the word to update remainingLetters
  for (var j = 0; j < word.length; j++) {
    if (word[j] === guess && answerArray[j] !== word[j]) {
      answerArray[j] = guess;
      remainingLetters--;
    };
  };
  getGuess();
  console.log(answerArray);
};

var remainingLetters = word.length;
var correctGuesses = updateGameState(guess, word, answerArray);
//*********************************************************

/* - code from the book

var showAnswerAndCongratulatePlayer = function (answerArray) {
// Display the answer using alert and congratulate the player
};

var word = pickWord();
var answerArray = setupAnswerArray(word);
var remainingLetters = word.length;
while (remainingLetters > 0) {
showPlayerProgress(answerArray);
var guess = getGuess();
if (guess === null) {
break;
} else if (guess.length !== 1) {
alert("Please enter a single letter.");
} else {
var correctGuesses = updateGameState(guess, word, answerArray);
remainingLetters -= correctGuesses;
}
}
showAnswerAndCongratulatePlayer(answerArray);

*/
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Section 2: JavaScript Language Basics</title>
</head>

<body>
  <h1>Section 2: JavaScript Language Basics</h1>
</body>

<script src="script.js"></script>

</html>

Answer №1

In order to successfully complete the game, you must continue looping until there are no more letters left to guess. Currently, you ask for a guess, update the state once, ask for another guess, and then stop.

It may be beneficial to create a separate function that handles the process of asking for a guess and updating the state. This way, you can keep calling that function until the user wins the game. I also organized all the function calls into one block to make it easier to follow the flow of the program. Previously, they were scattered throughout various functions making it difficult to understand.

Demo:

var chooseRandomWord = function(list) {
  // Select a word randomly from the list
  return list[Math.floor(Math.random() * list.length)];
};

var initializeAnswerArray = function(word) {
  // Initialize an array representing the answer
  var answerArray = [];
  for (var i = 0; i < word.length; i++) {
    answerArray[i] = "_";
  }
  console.log(answerArray);
  return answerArray;
};

var getLetterGuess = function() {
  // Prompt the user for a letter guess
  return prompt("Guess a letter, or click Cancel to quit: " + answerArray).toLowerCase();
};

var updateGameProgress = function(guess, word, answerArray) {
  // Update the answerArray based on the user's guess
  for (var j = 0; j < word.length; j++) {
    if (word[j] === guess && answerArray[j] !== word[j]) {
      answerArray[j] = guess;
      remainingLetters--;
    }
  }
  console.log(answerArray);
};

function startPlaying() {
  var guess = getLetterGuess();
  console.log(guess);
  updateGameProgress(guess, word, answerArray);
}

var chosenWord = chooseRandomWord(["university", "giraffe", "grass", "label"]);
console.log(chosenWord);
var answerArray = initializeAnswerArray(chosenWord);
var remainingLetters = chosenWord.length;

while (remainingLetters > 0) {
  startPlaying();
}

alert("Congratulations! You win!");
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Section 2: JavaScript Language Basics</title>
</head>

<body>
  <h1>Section 2: JavaScript Language Basics</h1>
</body>

<script src="script.js"></script>

</html>

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

Tips for effectively passing a $scope object between various controllers

I am encountering an issue with sharing a $scope object between two controllers. Within the 'IssueBookCtrl' controller, I update the 'books' object element value like this: $scope.books[i].issued = true; After that, I use the $emit s ...

Tips for looping through each element with a time delay in Node.js

I am currently developing a Twitter monitoring system in Node.js. Each time I make a request to the Twitter API, I need to iterate through an array of API keys with a 3-second delay between each iteration. I attempted to use setTimeout for this purpose, b ...

The useEffect hook is failing to resolve a promise

I have received a response from an API that I need to display. Here is a snippet of the sample response (relevant fields only): [ { ...other fields, "latitude": "33.5682166", "longitude": "73 ...

Issue: appbridgeError: APP::ERROR::INVALID_CONFIG: shopOrigin is a required field and must be provided

While developing my Shopify App using Koa and Nextjs, I encountered the following error: appbridgeError: APP::ERROR::INVALID_CONFIG: shopOrigin must be provided The behavior of the app is a bit odd as it works fine when accessed for the first time. Howev ...

Disable postback onkeypress event in the page

I am encountering an issue with my ASP.NET 4.0 form where I have multiple textboxes within divs that are dynamically shown or hidden. Specifically, I have a textbox with an onkeypress event defined as follows: <fieldset> <div class="WizardSte ...

Modify a number with a check box using inline Ajax

I have an HTML structure similar to this example: <li><label class="desc"><font color="green">Want to receive emails ($<span id="price">50</span>/month)</font></label> <input type="checkbox" checked ...

How can I refresh the container with a new version of the file using PDFObject?

I'm having trouble with a button that generates a PDF and then reloads the PDF in the browser by replacing the container it's in, but with a different link. Despite my efforts, the new PDF does not show up and the old one remains even after refre ...

Strategies for resolving a mix of different data types within a single parameter

Here, I am setting up the options params to accept a value that can either be a single string or another object like options?: string[] | IServiceDetail[] | IServiceAccordion[]; However, when attempting to map these objects, an error is encountered: Prope ...

"Implementing a 2D graphical user interface on a three.js

Struggling to create a 2D graphical user interface on the renderer. The challenge lies in positioning the 2D GUI dynamically based on the width of an element drawn in threejs (the element has a width of X using threejs units, and the menu needs to be posit ...

Struggling to get my chart to render dynamically in vue-chartjs

In my MainChart.vue file, I defined my chart like this: import { Line, mixins } from 'vue-chartjs' const { reactiveProp } = mixins // const brandPrimary = '#20a8d8' export default { extends: Line, mixins: [reactiveProp], props: [& ...

What is the process for removing an element from my Reducer Object?

I'm facing a challenge with my reducer object structure. Here's an example of what it looks like: clientData : { 1080 : [{ID : 1111,name : 'John'},{ID : 2222,name : 'Stan'},], 1090 : [{ID : 3333,name : 'Adam'},{ ...

Monitor MongoDB for expired document date fields

I'm currently working with MongoDB and MeteorJS, and I'm wondering if there is a way to observe the value of a specific field in a document. I know we can observe document updates, creations, and removals, but I am interested in monitoring a fiel ...

Unlocking the AngularJS variable within the template script

My controller code: $scope.totals = totals; In the template, I am able to successfully inject HTML using this code: {{totals}} However, my goal is to access the totals variable in a script within the template. Here's what I attempted: <script& ...

I am looking to optimize my JavaScript function so that the console.log structure is functioning correctly. What changes can I make to

I've been trying out this method to tackle the issue, however, my console.log isn't providing the expected output. What adjustments should I make? const executeCalculator = ({ x, y, operation }) => { let calculator = { x: this.x, ...

Using arrays as parameters in Java functions: Passing and receiving

I'm looking for assistance in returning an array from a function called X(). My goal is to then pass that array as a parameter to a function named Y() within the same class. This is what I currently have: int[] create()throws IOException { Syste ...

Guide to accessing an API via oAuth 1.0a using Javascript in an Angular.js application

Presently, I am engaged in developing a web application that necessitates connecting to an external API to retrieve a JSON file. The specific API I am utilizing is the noun project, which requires Oauth1.0a authentication. For this project, Angular.JS is ...

Storing dynamic field data in React JS: Tips and Tricks

I need help figuring out how to save dynamic field values in a specific format to the database. Here is an example of the format I am looking for: "items": [ { "item_id" : 6, "description" : "", ...

Steps to create an if statement using jQuery

.data( "autocomplete" )._renderItem = function( ul, item ) { return $( "<li></li>" ) .data( "item.autocomplete", item ) if ( ( item.parent_term_id == "16" ) ) { .append( "<a>" + (item.child_term ? item.child ...

Is it true that Firefox fails to display javascript errors on AJAX 'threads'?

Currently, I have a function called test_fn that is being called in two ways: (a) Through an onclick event of a button; or (b) from the success callback within a jQuery AJAX request, as shown here: $.ajax({ type: 'POST', ... succes ...

Error: Attempting to access the first element of a null property is not allowed

Currently, I am working on a NodeJS Project that utilizes Sails.js as the framework. The goal is to implement a permissions system where each group's permissions are set using Check Boxes within a form powered by AngularJS. However, upon clicking th ...