henhen henhen - 1 month ago 5
HTML Question

Make previous selected word go away on html and replace with new word in Hangman game for javascript

I am currently making a hangman game with javascript and I am struggling with how to remove and replace the previously selected word, with a new word. Currently I ahve my code set up so that when the player guesses the word correctly, a message pops up and asks the user if they want to play again. If they press Y, I call the function that randomly selects a word from and array and also uses the push method to fill and empty array with blank lines the same length of the chosen word. But when I call this function after Y has been pressed, the previous word doesnt go away and key presses also do not register.

var hangmanObject = {
randomWords: ['rock','paper','modular synthesizer', 'led zeppelin'],
chosenWord: "",
numWins: 0,
numLives: 10,

empty: [],
incorrect: [],
splitArray: []

}
function startFunction()
{
document.getElementById("numLives").innerHTML = hangmanObject.numLives;
displayChosenWord();
}

function displayChosenWord()
{
hangmanObject.chosenWord = hangmanObject.randomWords[Math.floor(Math.random()*hangmanObject.randomWords.length)]
hangmanObject.splitArray = hangmanObject.chosenWord.split("");
for (x = 0; x < hangmanObject.chosenWord.length; x++)
{
if (hangmanObject.chosenWord.charAt(x) === " ")
hangmanObject.empty.push(" ");
else
hangmanObject.empty.push(" _ ");
}

document.getElementById("blanks").innerHTML = hangmanObject.empty.join("");
}



document.onkeyup = function(event)
{

var userGuess = String.fromCharCode(event.keyCode).toLowerCase();


for (x = 0; x < hangmanObject.chosenWord.length; x++)
{
if (hangmanObject.chosenWord.charAt(x) === userGuess)
{
hangmanObject.empty[x] = userGuess;
document.getElementById("blanks").innerHTML = hangmanObject.empty.join("");
}

}
if (hangmanObject.splitArray.indexOf(userGuess) === -1) //checking to see if wrong letter chosen
{
hangmanObject.numLives--;
document.getElementById("numLives").innerHTML = hangmanObject.numLives;
hangmanObject.incorrect.push(userGuess);
document.getElementById("LettersGuessed").innerHTML = hangmanObject.incorrect;
}
console.log(hangmanObject.empty);
if (hangmanObject.empty.indexOf(" _ ") === -1)
{
hangmanObject.numWins++;

// console.log("i won");
document.getElementById("wins").innerHTML = hangmanObject.numWins;
document.getElementById("Play").innerHTML = "Play Again? Y/N";
document.onkeyup = function(event)
{
// Determines which exact key was selected. Make it lowercase
var Choice = String.fromCharCode(event.keyCode).toLowerCase();
if (Choice === 'y')
{
hangmanObject.numLives = 10;
displayChosenWord();
}
}

}
if (hangmanObject.numLives <= 0)
{
document.getElementById("lose").innerHTML = "You Lose";
}
}

Answer

You are setting the document.onkeyup callback inside the callback, effectively disabling it for letter guesses.

Also, the empty array is never emptied so the next word is appended to the empty letters array from the previous word. Here's a simpler approach, by using a gameState flag, you can decide whether the user is entering letters to guess, or they are deciding to play again. Also, a single div for status can be used ;)

var hangmanObject = {
  gameState: 'playing',
  randomWords: [
    'rock',
    'paper',
    'modular synthesizer',
    'led zeppelin'
  ],
  chosenWord: "",
  numWins: 0,
  numLives: 10,

  empty: [],
  incorrect: [],
  splitArray: []
}

function startFunction() {
  document.getElementById("numLives").innerHTML = hangmanObject.numLives;

  chooseNewWord();
}

function chooseNewWord() {
  hangmanObject.chosenWord = hangmanObject.randomWords[Math.floor(Math.random() * hangmanObject.randomWords.length)]
  hangmanObject.splitArray = hangmanObject.chosenWord.split("");

  // Reset guesses and misses
  hangmanObject.empty = [];
  hangmanObject.incorrect = [];

  for (x = 0; x < hangmanObject.chosenWord.length; x++) {
    if (hangmanObject.chosenWord.charAt(x) === " ")
      hangmanObject.empty.push(" ");
    else
      hangmanObject.empty.push("_");
  }

  document.getElementById("blanks").innerHTML = hangmanObject.empty.join(" ");
}


document.onkeyup = function(event) {
  var userGuess = String.fromCharCode(event.keyCode).toLowerCase();

  // Game status is "playing"
  if (hangmanObject.gameState === 'playing') {
    for (x = 0; x < hangmanObject.chosenWord.length; x++) {
      if (hangmanObject.chosenWord.charAt(x) === userGuess) {
        hangmanObject.empty[x] = userGuess;

        document.getElementById("blanks").innerHTML = hangmanObject.empty.join(" ");
      }
    }

    // checking to see if wrong letter chosen
    if (hangmanObject.splitArray.indexOf(userGuess) === -1) {
      hangmanObject.numLives--;

      document.getElementById("numLives").innerHTML = hangmanObject.numLives;

      hangmanObject.incorrect.push(userGuess);

      document.getElementById("LettersGuessed").innerHTML = hangmanObject.incorrect.join(",");
    }

    // Some debug
    console.log(hangmanObject.empty);

    // WIN situation
    if (hangmanObject.empty.indexOf("_") === -1) {
      hangmanObject.numWins++;

      // Set status message and game state
      document.getElementById("status").innerHTML = "You won " + hangmanObject.numWins + " times";
      hangmanObject.gameState = 'finished';
    }

    // LOSE situation
    if (hangmanObject.numLives <= 0) {
      // Set status message and game state
      document.getElementById("status").innerHTML = "You Lose";
      hangmanObject.gameState = 'finished';
    }

    // Set message if game finished
    if (hangmanObject.gameState === 'finished') {
      document.getElementById("Play").innerHTML = "Play Again? Y/N";
    }

    // Game status is "finished"
  } else {
    // If user selects play again
    if (userGuess === 'y') {
      // Set status back to "playing"
      hangmanObject.gameState = 'playing';

      // Reset lives and messages
      hangmanObject.numLives = 10;

      document.getElementById("status").innerHTML = "";
      document.getElementById("LettersGuessed").innerHTML = "";
      document.getElementById("Play").innerHTML = "";

      // Choose new word
      chooseNewWord();
    } else {
      // Set message
      document.getElementById("status").innerHTML = "Goodbye!";

      // Disable key handler
      document.onkeyup = null;
    }
  }
}

startFunction();
<div id="numLives"></div>

<div id="blanks"></div>

<div id="LettersGuessed"></div>

<div id="status"></div>

<div id="Play"></div>