How to debug a console Hangman program? - javascript

This program takes sentence as user input. Then it randomly selects word of hangman game. After user is asked to enter letters one by one. I believe there is something wrong with my function guess. It does not behave like I wanted to.
Guess function suppose to do guess(letter). If letter hasn't been tried already, push the letter tried into the array of guessedLetters and decrease guesses by 1. Loop through currentWord to see if letter is a match. If it is, assign letter to appropriate spots in hangmanWord.
If isOver returns true, invoke overMessage, else invoke render, prompt a new letter and invoke guess with that letter (using recursion).
var numOfGuesses;
var gueesedLetters = []
var currentWord = ''
var hangmanWord = []
var letter;
function guess(letter) {
if (gueesedLetters.indexOf(letter) === -1) {
gueesedLetters.push(letter);
numOfGuesses--;
}
else {
for (var i = 0; i < currentWord.length; i++) {
if (letter === currentWord[i]) {
var currWrdIndex = currentWord.indexOf(letter)
hangmanWord.splice(currentWord[i], 0, letter)
}
}
}
if (isOver() === true) {
overMessage();
} else {
console.log(render());
letter = prompt("Please enter the letter").toLowerCase();
guess(letter);
}
}
function isOver() {
if (currentWord.split("").sort().join("") === hangmanWord.sort().join("") || numOfGuesses === 0) {
return true
} else {
return false
}
}
function overMessage() {
if (currentWord.split().sort().join("") === hangmanWord.sort().join("")) {
return "You win";
} else if (numOfGuesses === 0) {
return "You lose";
} else {
return "Game is not over";
}
}
function render() {
console.log("The hangman word was %s", currentWord);
console.log("The total number of guesses are %s", numOfGuesses);
console.log("Total guess letters are %s", gueesedLetters);
}
function startGame(wordsArray) {
numOfGuesses = 10;
gueesedLetters = []
currentWord = wordsArray[Math.floor(Math.random() * wordsArray.length)]
letter = prompt("Please enter the letter ?")
guess(letter);
}
function mainProgram() {
var userSentence = prompt("Please enter sentences to begin.")
userSentence = userSentence.split(" ")
startGame(userSentence)
if (isOver() === true) {
console.log(overMessage())
console.log(render())
}
}
mainProgram()

Related

Hangman same letter cannot be used again javascript

I am trying to run a program that makes the user guess the word by typing in the letter. The same letter should not be allowed to be inputted twice. I was thinking of storing each letter inputted in a list and then I would loop through the list checking each element against the user input. If it is inputted twice and error message like try again will occur. This is what I have so far.
var x = ["Football", "Pie", "Red", "Amber", "Purple", "Blue"];
var y = x[Math.floor(Math.random() * x.length)].toLowerCase();
var answerArray = [];
var lettersUsed = [];
var numberOfGuesses = 10;
for (var i = 0; i < y.length; i++)
{
answerArray[i] = "_";
}
var remainingLetters = y.length;
while (remainingLetters > 0 && numberOfGuesses > 0)
{
console.log(answerArray.join(" "));
var guess = prompt("Guess a letter\n");
if (guess === null)
{
console.log("Game over");
break;
}
else if (guess.length !== 1)
{
console.log("Enter a single letter\n");
}
else
{
numberOfGuesses--;
lettersUsed.push(guess);
for (var j = 0; j < y.length; j++)
{
if (y[j] === guess.toLowerCase() && answerArray[j] === "_")
{
answerArray[j] = guess.toLowerCase();
remainingLetters--;
}
}
}
}
console.log(answerArray.join(" "));
if (numberOfGuesses > 0)
{
console.log("Well done! You've won! Your stick guy has been saved!\n");
}
else
{
console.log("Game over! The word was " + y);
}
///console.log(lettersUsed);
How do I write the for loop? Any help would be appreciated.
You can use the Array.includes(item) method. It will return true if the item is in the array. For example:
let lettersUsed = ['a', 'b', 'c'];
let newLetter = 'b';
if (lettersUsed.includes(newLetter)) {
console.log('letter already used');
} else {
console.log('letter not used yet');
}
Edit in response to question from OP:
You could add this after you check the input length:
else if (guess.length !== 1)
{
console.log("Enter a single letter\n");
}
else if (lettersUsed.includes(guess))
{
console.log('Letter already used');
}
else
{
numberOfGuesses--;

Attempting to nest if/else statement in while loop

I'm setting up the following while loop to continue to print a message for each even number entered but print a different message for an odd number and stop:
userEnteredNumber = prompt("Please enter a number:");
while (userEnteredNumber%2 === 0) {
if (userEnteredNumber%2 === 0) {
document.write(userEnteredNumber + EVEN_MESSAGE);
} else if (userEnteredNumber%2 !== 0) {
document.write(userEnteredNumber + NOT_EVEN_MESSAGE);
}
userEnteredNumber = prompt("Please enter a number:");
console.log(userEnteredNumber);
}
Right now it will continue to print with even number entry and stop if an odd number is entered, but the odd number message won't print. Not really understanding why the odd message won't print. Hoping someone can help clarify it for me!
More like this:
while (true) {
userEnteredNumber = prompt("Please enter a number:");
if (userEnteredNumber == null) { // they clicked cancel
break;
}
if (userEnteredNumber%2 === 0) {
document.write(userEnteredNumber + EVEN_MESSAGE);
} else if (userEnteredNumber%2 !== 0) {
document.write(userEnteredNumber + NOT_EVEN_MESSAGE);
} else {
document.write(NOT_VALID_MESSAGE + userEnteredNumber);
}
console.log(userEnteredNumber);
}
From your code, you can change it a bit to look like this:
while (true) {
userEnteredNumber = prompt("Please enter a number:");
if (userEnteredNumber%2 === 0) {
document.write(userEnteredNumber + EVEN_MESSAGE);
} else if (userEnteredNumber%2 !== 0) {
document.write(userEnteredNumber + NOT_EVEN_MESSAGE);
break;
}
console.log(userEnteredNumber);
}

What am i doing wrong? it wont run thru every condition

I'm trying to have someone guess a number from 1 to 6. I give them two tries if, by the end of the second try, they don't get it, then else will tell them what the number is but it just won't run. what am I doing wrong?
var number = Math.floor(Math.random() *6) +1;
var answer = false;
var guess = prompt('Take a guess, pick a number from 1 to 6');
if(parseInt(guess) === number) {
answer === true;
} else if (parseInt(guess) > number) {
var guessLess = prompt('To high! Guess less');
if (parseInt(guessLess) === number) {
answer === true;
} else if (parseInt(guess) < number) {
var guessMore = prompt('Guess more');
if(parseInt(guessMore) === number) {
answer = true;
}
}
}
if (answer) {
alert('You got it')
} else {
alert('No. The number was ' + number);
}
}
You are using comparison instead of assignment in the below segment
if (parseInt(guessLess) === number) {
answer === true;
Change it to
if (parseInt(guessLess) === number) {
answer = true;

simple algorithm with indexOf not working in JS

my mission is to find and output, where the tabs/word entered, is placed in the sentence.
the console gives me back that place var is not defined. What should I do? Thank you very much!
var sentence = prompt("Enter you sentence");
var word = prompt("Enter the tabs/word you looking for");
var counter = 0;
var place = stntence.indexOf(word, counter);
if (stntence.indexOf(word) != -1) {
while (place != -1) {
if (place != -1) {
console.log("The place of the word/tab is: " + place);
counter = place++;
} else {
console.log("That's all")
}
}
} else {
console.log("the word/tabs are not exist in the sentence");
}
Beside the typo of stntence !== sentence, you could take the advantage of the counter and use a shortened approach by assigning the place directly in the while condition.
var sentence = prompt("Enter you sentence"),
word = prompt("Enter the tabs/word you looking for"),
counter = 0,
place = -1;
while ((place = sentence.indexOf(word, place + 1)) != -1) {
console.log("The place of the word/tab is: " + place);
counter++;
}
if (counter) {
console.log("That's all");
} else {
console.log("the word/tabs are not exist in the sentence");
}

How to make sure user input is a valid string in js

I am very new to JS,
how do I make sure that the user input is a valid string?
If the string is inside of the array, the game should continue.
if the string is outside of the array, the game should ask user to input their guess again.
var color = ["AliceBlue","Black","FireBrick","GreenYellow","LightBlue","Ivory","MediumBlue","Indigo","SpringGreen","Moccasin"];
var target;
var guess_input_text;
var guess_input;
var finished = false;
var guesses = 0;
var rightAnswer;
var i = 0;
function do_game() {
var random_number = Math.random()* color.length;
var random_number_interger = Math.floor(random_number);
target = random_number_interger + 1;
rightAnswer = color[target];
while(!finished) {
guess_input_text = prompt("I am thinking of one of these colors:\n\n" + color.sort()+ "\n\n The right answer is\n" + rightAnswer);
guess_input = guess_input_text;
guesses +=1;
finished = check_guess();
}
}
function check_guess() {
if(guess_input < rightAnswer){
console.log("Hint: your color is alphabetically lower than mine")
return false;
}
else if( guess_input > rightAnswer) {
console.log("Hint: your color is alphabetically higher than mine ")
return false;
}
else (guess_input == rightAnswer)
{
console.log("Congrats!!!")
return true;
}
)
}
You can use indexOf to check the position of guess_input in the color array. It will return -1 if it is not present.
So:
function check_guess() {
if (color.indexOf(guess_input) < 0) {
console.log("Not a valid colour, try again.");
return false;
}
return true;
}
You can use Array.prototype.find function with ES6 arrow functions to make it even snappier.
if(color.findIndex(e => e === guess_input) === -1){
alert("Please guess again!);
}
The above code alerts the user to guess again if the guess_input isn't found in the array.

Categories

Resources