Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Complete Hangman Game code

Hello!

I would like to request for complete Hangman Game Code by our Instructor Craig Dennis . I have lost my track in workspace and currently in a mess with the code.

2 Answers

Hi Vidit,

here my code of the Hangman game. You can ignore my comments or use them if they are helpful.

Hangman class

public class Hangman {
    public static void main(String[] args) {
        Game game = new Game("Treehouse");
        Prompter prompter = new Prompter(game); // pass the game object from above into the prompter
        prompter.play();
    }
}

Prompter class:

import java.util.Scanner;

public class Prompter { //make Prompter to be able to except guesses
    private Game mGame;

    public Prompter(Game game) { //constructor takes the game logic object
        mGame = game;
    }

    public void play() {
        while (mGame.getRemainingTries() > 0 && !mGame.isSolved()) {
            displayProgress();
            promptForGuess();
        }
        if (mGame.isSolved()) {
            System.out.printf("Congratulations you won the game with %s remaining tries", mGame.getRemainingTries());
        } else {
            System.out.printf("Bummer the answer was %s", mGame.getAnswer());
        }
    }

    public boolean promptForGuess() {
        Scanner s = new Scanner(System.in);
        char guess;
        boolean isHit = false;
        // there is no valid guess yet, so isValidGuess false in the beginning
        boolean isValidGuess = false;

        // if you scip the !
        // the while loop will never be reached
        // because the condition expects that isValidGuess is true and this is not the case
        // the promptForGuess method will do nothing
        while (!isValidGuess) {
            System.out.println("Enter a letter: ");
            String guessAsString = s.nextLine();

            try {
                isHit = mGame.applyGuess(guessAsString);
                // condition of the while loop is false from here
                // and after input the valid guess mHit or mMIss can be returned
                // without a "boot loop"
                isValidGuess = true;
            } catch (IllegalArgumentException iae) {
                System.out.printf("%s. Please try again. \n", iae.getMessage());
            }
        }
        return isHit;// returns isHit true if guess is true
    }

    public void displayProgress() {
        System.out.printf("You have %s tries to solve : %s\n",
                mGame.getRemainingTries(),
                mGame.getCurrentProgress());
    }
}

Game class:

public class Game {
    public static final int MAX_MISSES = 7;
    private String mAnswer;
    private String mHits;
    private String mMisses;

    public Game(String answer) {
        mAnswer = answer;
        mHits = " ";
        mMisses = " ";
    }


    public boolean applyGuess(String letters) {
        if (letters.length() == 0) {
            throw new IllegalArgumentException("There aro no letters!");
        }
        // applies the other applyGuess method that takes a char
        return applyGuess(letters.charAt(0));
    }


    //stores sHit as true or adds a count on mMisses
    public boolean applyGuess(char letter) {
        letter = validateGuess(letter);
        boolean isHit = mAnswer.indexOf(letter) >= 0;
        if (isHit) {
            mHits += letter;
        } else {
            mMisses += letter;
        }
        return isHit;
    }

    private char validateGuess(char letter) {
        if (!Character.isLetter(letter)) {
            throw new IllegalArgumentException("A letter is required");
        }
        if (mHits.indexOf(letter) >= 0 || mMisses.indexOf(letter) >= 0) {
            throw new IllegalArgumentException(letter + " is already been guessed");
        }
        return letter;
    }

    public String getCurrentProgress() {
        String progress = " ";
        // mAnswer is the word that Game constructor is taken "treehouse"
        for (char letter : mAnswer.toCharArray()) {
            char display = '-';

            if (mHits.indexOf(letter) >= 0) {
                display = letter; //char concatenation to String
            }
            progress += display;
        }
        return progress;
    }

    public int getRemainingTries() {
        return MAX_MISSES - mMisses.length();
    }

    public String getAnswer() {
        return mAnswer;
    }

    public boolean isSolved() {
        return getCurrentProgress().indexOf('-') == -1;
    }
}

Grigorij

Hi Vidit,

You can pull down my version of Hangman from Github here. You should be able to clone it directly into IntelliJ or download the zip file and go from there. I'm pretty sure this is the final version of the project ... let me know if not and I'll update the code.

Steve.