I am trying to code a bot that can play hangman. I have used an array to store all the previous letter guesses. How can I add to this array, so that all previous guesses are shown in the console?
I have already tried using the push()
function in JavaScript, and this seems to work fine for the first guess. But a second guess returns another array, which contains only that letter, instead of an array containing all guesses.
This also happens when I try to write the array using correctGuessed[correctGuessed.length] = guessVal;
and I am not sure where I am going wrong.
var word = "ALPHABET";
var wordLength = word.length;
var choices = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
"L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
"W", "X", "Y", "Z"];
var correctGuessed = correctGuessed || [];
var guess = Math.floor(Math.random() * choices.length);
var guessVal = choices[guess].valueOf();
//Start the game with a word length and a letter guess
message.reply("I am thinking of a " + wordLength + " letter word.");
message.channel.send("My guess is " + guessVal);
//If the guess was correct
if(word.includes(guessVal))
{
//Send a congratulatory message and push the letter onto
//the end of the array so it cannot be guessed again.
message.channel.send("Your guess was correct! Guess again!");
//newCorrect = correctGuessed.push(guessVal);
correctGuessed[correctGuessed.length] = guessVal;
console.log(correctGuessed);
}
The expected outcome of this code is that if I guess the letter 'A', the console will display the result ['A']. Then, after guessing, say, the letter 'B', the console will display the result ['A', 'B'].
The actual output of this code is ['A'] after guessing 'A', and after guessing 'B', the output is ['B'] rather than ['A', 'B']. I am getting each guess in its own array.
The problem is not that I don't understand how push()
works; I understand that
var array = [1,2,3];
array.push(4);
will produce [1,2,3,4]
, but I am trying to achieve this, and it is not working.