help with hangman game

Get help with Code for Teens
jturq
Posts: 4
Joined: Sat Jan 05, 2019 1:07 am

help with hangman game

Post by jturq » Sat Jan 05, 2019 1:27 am

I have typed in the code from pages 174-183 and 211-213 into the console in about:blank. I typed from the optional words all the way to the part with the TODO comments. There, I can type playHangman(); and it says "This page says GAME OVER." With it is the hangman and "The correct answer was 'skateboard'" or any other word. I know this is what is supposed to happen right now. Then when I start typing the other things to try to finish it, it gives me errors like " Unexpected identifier, Uncaught ReferenceError: solution is not defined, Invalid or unexpected token, Illegal return statement, etc. I looked through the Code For Teens book to find out how to fix those errors and everything I try doesn't work. Can you give me some tips on what to fix? Thanks!

JeremyMoritz
Site Admin
Posts: 14
Joined: Mon May 14, 2018 10:19 pm
Location: Kansas
Contact:

Re: help with hangman game

Post by JeremyMoritz » Sat Jan 05, 2019 6:34 am

I would be happy to help you out with this. Can you please copy and paste the code that you are trying to run?
Jeremy Moritz
Author of Code for Teens
www.CodeForTeens.com

jturq
Posts: 4
Joined: Sat Jan 05, 2019 1:07 am

Re: help with hangman game

Post by jturq » Sat Jan 05, 2019 9:28 pm

Here it is. Could you send it back corrected from any mistakes that I might have made? Thanks so much!!
p.s. did you code this website yourself?


function generateHangmanSolution() {
const possibleSolutions = [
'watermelon',
'volleyball',
'homecoming',
'strawberry',
'retirement',
'television',
'friendship',
'cinderella',
'restaurant',
'helicopter',
'skateboard',
'leadership',
'antarctica',
];
const randomIndex = Math.floor(Math.random() * possibleSolutions.length);

return possibleSolutions[randomIndex].toUpperCase();

function gameOver(solution, won) {
const asciiHangman = '____\n|/ |\n| @\n| /|\\\n| / \\\n|\n=====';
let message = '';
if (won) {
message = 'YOU WIN!';
} else {
message = 'GAME OVER\n\n' + asciiHangman;
}
message += '\n\nThe correct answer was ' + solution + '!';
alert(message);
return message;
}

/*************************************
* Main Function for Playing Hangman! *
*************************************/
function playHangman() {
const solution = generateHangmanSolution();
const solutionLetters = solution.split('');
const wrongGuesses = [];
const maxWrongGuesses = 7;
const progressSoFar = '_'.repeat(solution.length).split('');

const confirmPlay = confirm("Let's play Hangman!\n\n"
+ "Pick letters to guess the word I'm thinking of.\n"
+'Are you ready to play?');
if (!confirmplay) {
return gameOver(solution, false);
}

while (wrongGuesses.length < maxWrongGuesses) {
const promptMessage = 'Here is your progress on the word so far: \n'
+ progressSoFar.join(' ') + '\n'
+ 'Wrong Guesses: [' + wrongGuesses.toString() + ']\n\n'
+ 'Pick a letter!';
const userInput = prompt(promptMessage);

if (!userInput) {
return gameOver(solution);
}

//TODO: process user's guess here
}

const guess = userInput.toUpperCase();
let goodGuess = false;

for (let i = 0; i < solutionLetters.length; i++) {
if (solutionLetters === guess) {
goodGuess = true;
progressSoFar = guess;
}
}

//TODO: Add logic for right or wrong guess here

if (goodGuess) {
if (progressSoFar.join(' ') === solution) {
return gameOver(solution, true);
}

alert('Good guess!');
} elst {
wrongGuesses.push(guess);
alert('Sorry, ' + guess + ' is incorrect.\nYou have '
+ (maxWrongGuesses - wrongGuesses.length) + ' strikes left.');
}

JeremyMoritz
Site Admin
Posts: 14
Joined: Mon May 14, 2018 10:19 pm
Location: Kansas
Contact:

Re: help with hangman game

Post by JeremyMoritz » Sat Jan 05, 2019 11:27 pm

Hi @jturq !

First off, thank you for working through my book! I'm proud of you for getting all the way to the last chapter!

To answer your later question, i did code some parts of my website (others were from wordpress) and all of the projects in my book, but i didn't code this forum. I found an online one and just plugged it into my website. (no need to re-invent something that already exists!)

I looked through your code and noticed a few different errors. All of them were small, but each one of them would break the code. A good way to find these is to paste your code into an online javascript validator (google for one). I didn't try that yet because i wanted to see if i could just notice the issues at first glance. Here are the ones i found:

1. You had 13 opening curly braces and only 11 closing curly braces. This is guaranteed to be a failure somewhere. EVERY opening curly brace, opening paren, and opening square bracket MUST have a corresponding closing curly brace, paren, or square bracket.
2. You used the term "elst" instead of "else"
3. You used a variable called "confirmplay" when you had initialized one called "confirmPlay" (remember that capitalization always counts!)

If you're not already doing it, it's important that you indent (tab) your code properly. By organizing your code with proper tabs, you can easily see when you are missing a closing curly brace.

Here is your same code with proper indentation and those few small fixes made.

Code: Select all


function generateHangmanSolution() {
  const possibleSolutions = [
    'watermelon',
    'volleyball',
    'homecoming',
    'strawberry',
    'retirement',
    'television',
    'friendship',
    'cinderella',
    'restaurant',
    'helicopter',
    'skateboard',
    'leadership',
    'antarctica'
  ];
  const randomIndex = Math.floor(Math.random() * possibleSolutions.length);

  return possibleSolutions[randomIndex].toUpperCase();
}

function gameOver(solution, won) {
  const asciiHangman = '____\n|/ |\n| @\n| /|\\\n| / \\\n|\n=====';
  let message = '';

  if (won) {
    message = 'YOU WIN!';
  } else {
    message = 'GAME OVER\n\n' + asciiHangman;
  }

  message += '\n\nThe correct answer was ' + solution + '!';
  alert(message);

  return message;
}

/*************************************
* Main Function for Playing Hangman! *
*************************************/
function playHangman() {
  const solution = generateHangmanSolution();
  const solutionLetters = solution.split('');
  const wrongGuesses = [];
  const maxWrongGuesses = 7;
  const progressSoFar = '_'.repeat(solution.length).split('');

  const confirmPlay = confirm("Let's play Hangman!\n\n"
  + "Pick letters to guess the word I'm thinking of.\n"
  +'Are you ready to play?');
  
  if (!confirmPlay) {
    return gameOver(solution, false);
  }

  while (wrongGuesses.length < maxWrongGuesses) {
    const promptMessage = 'Here is your progress on the word so far: \n'
    + progressSoFar.join(' ') + '\n'
    + 'Wrong Guesses: [' + wrongGuesses.toString() + ']\n\n'
    + 'Pick a letter!';
    const userInput = prompt(promptMessage);

    if (!userInput) {
      return gameOver(solution);
    }

    //TODO: process user's guess here
  }

  const guess = userInput.toUpperCase();
  let goodGuess = false;

  for (let i = 0; i < solutionLetters.length; i++) {
    if (solutionLetters === guess) {
      goodGuess = true;
      progressSoFar = guess;
    }
  }

  //TODO: Add logic for right or wrong guess here

  if (goodGuess) {
    if (progressSoFar.join(' ') === solution) {
      return gameOver(solution, true);
    }

    alert('Good guess!');
  } else {
    wrongGuesses.push(guess);

    alert('Sorry, ' + guess + ' is incorrect.\nYou have '
      + (maxWrongGuesses - wrongGuesses.length) + ' strikes left.');
  }
}

You got so many things right that I hope your small errors don't discourage you. Little errors like yours happen all the time to professionals. The important thing to note is that it's not about how few errors you can make or how consistently you get it right on your first try, it's about how well you stick with it until you get it right! With coding, it's only the final version that matters!

Hope this helps! Happy coding!
Jeremy Moritz
Author of Code for Teens
www.CodeForTeens.com

jturq
Posts: 4
Joined: Sat Jan 05, 2019 1:07 am

Re: help with hangman game

Post by jturq » Mon Jan 07, 2019 4:08 pm

Dear Jeremy,
I'm sorry to keep bugging you about this. The code you sent me was sooooooo helpful! When I pasted it into the console, I got the thing that says "this page says Let's play hangman! Pick the letters to guess the word I'm thinking of. Are you ready to play?" I click OK and it shows "Here is your progress on the word so far: _ _ _ _ _ _ _ _ _ _ Wrong Guesses:[] Pick a letter!"
I type in the letter "e" because it has to be in the word since all the optional words have an e. I click ok and then the e disappears and the progress on my word never changes. In the [] for wrong guesses, there is never even a change. Also I never run out of guesses.
I noticed that when I sent the code that I tried to run to you earlier, I forgot to put in this part.
return gameOver(solution, false); // if player gets here, Game Over (fail)
}

It is logical that this is the problem that is stopping me now. However, when i put it with the code in the console, I get, "Uncaught SyntaxError: Illegal return statement."
could you please send me the right code for this part?
Thank You for sending that other code. It was very useful. I was glad to be able to do your book. It was very useful to understand how to code.

Thanks again!

JeremyMoritz
Site Admin
Posts: 14
Joined: Mon May 14, 2018 10:19 pm
Location: Kansas
Contact:

Re: help with hangman game

Post by JeremyMoritz » Mon Jan 07, 2019 4:20 pm

I don't mind helping at all. If you have this question, maybe others do too.

First off, keep in mind that your code was only partially finished, so i would expect behavior like what you described (not the syntax error, but the repetition stuff).

Please copy all of your code, and paste it in a reply. And be sure to use the "code" button so that it will be wrapped in a code block (you can find the code button in the formatting bar next to the "bold", "italic", "underline", and "quote" buttons).
Jeremy Moritz
Author of Code for Teens
www.CodeForTeens.com

jturq
Posts: 4
Joined: Sat Jan 05, 2019 1:07 am

Re: help with hangman game

Post by jturq » Mon Jan 07, 2019 5:30 pm

Code: Select all

function generateHangmanSolution() {
  const possibleSolutions = [
    'watermelon',
    'volleyball',
    'homecoming',
    'strawberry',
    'retirement',
    'television',
    'friendship',
    'cinderella',
    'restaurant',
    'helicopter',
    'skateboard',
    'leadership',
    'antarctica'
  ];
  const randomIndex = Math.floor(Math.random() * possibleSolutions.length);

  return possibleSolutions[randomIndex].toUpperCase();
}

function gameOver(solution, won) {
  const asciiHangman = '____\n|/ |\n| @\n| /|\\\n| / \\\n|\n=====';
  let message = '';

  if (won) {
    message = 'YOU WIN!';
  } else {
    message = 'GAME OVER\n\n' + asciiHangman;
  }

  message += '\n\nThe correct answer was ' + solution + '!';
  alert(message);

  return message;
}

/*************************************
* Main Function for Playing Hangman! *
*************************************/
function playHangman() {
  const solution = generateHangmanSolution();
  const solutionLetters = solution.split('');
  const wrongGuesses = [];
  const maxWrongGuesses = 7;
  const progressSoFar = '_'.repeat(solution.length).split('');

  const confirmPlay = confirm("Let's play Hangman!\n\n"
  + "Pick letters to guess the word I'm thinking of.\n"
  +'Are you ready to play?');
  
  if (!confirmPlay) {
    return gameOver(solution, false);
  }

  while (wrongGuesses.length < maxWrongGuesses) {
    const promptMessage = 'Here is your progress on the word so far: \n'
    + progressSoFar.join(' ') + '\n'
    + 'Wrong Guesses: [' + wrongGuesses.toString() + ']\n\n'
    + 'Pick a letter!';
    const userInput = prompt(promptMessage);

    if (!userInput) {
      return gameOver(solution);
    }

    //TODO: process user's guess here
  }

  const guess = userInput.toUpperCase();
  let goodGuess = false;

  for (let i = 0; i < solutionLetters.length; i++) {
    if (solutionLetters === guess) {
      goodGuess = true;
      progressSoFar = guess;
    }
  }

  //TODO: Add logic for right or wrong guess here

  if (goodGuess) {
    if (progressSoFar.join(' ') === solution) {
      return gameOver(solution, true);
    }

    alert('Good guess!');
  } else {
    wrongGuesses.push(guess);

    alert('Sorry, ' + guess + ' is incorrect.\nYou have '
      + (maxWrongGuesses - wrongGuesses.length) + ' strikes left.');
  }
}	return gameOver(solution, false); // if player gets here, Game Over (fail)
}
I think that this was a code block. if not, sorry. i clicked the box that showed "</>"

JeremyMoritz
Site Admin
Posts: 14
Joined: Mon May 14, 2018 10:19 pm
Location: Kansas
Contact:

Re: help with hangman game

Post by JeremyMoritz » Mon Jan 07, 2019 6:17 pm

If you don't indent your code properly, you'll run into lots of little errors like this and you won't know why. Start by always indenting your code consistently. If you had done so this time, it would've been obvious that your return statement was outside of any function.

A return statement belongs inside of a function.

And do you notice how you have two closing curly braces lined up with one another at the end? That's a giveaway that you're not using proper pairing of opening/closing curly braces. Count the number of closing curly braces (using Ctrl+F, Cmd+F or an online word checker). it needs to be the same as the number of opening curly braces.

Lastly, try doing this from now on:
go to http://esprima.org/demo/validate.html and paste your code into the syntax validator. This will show you where you have syntax errors.

I hope this helps!
Jeremy Moritz
Author of Code for Teens
www.CodeForTeens.com

Post Reply