Trying to implement text-based Hangman game in Java

Here’s a brief amount of code that is a complete hangman program:

static int MAX_MISSES = 5;
static String[] WORDS = { "QUICK", "BROWN", "JUMPS" }; // etc

public static void main(String[] args) throws Exception {
    String word = WORDS[new Random().nextInt(WORDS.length)], guesses = " ";
    int misses = -1;
    for (Scanner in = new Scanner(System.in); !word.matches("[" + guesses + "]+") & (misses += word.contains(guesses.substring(0, 1)) ? 0 : 1) <= MAX_MISSES; guesses = in.nextLine().toUpperCase().charAt(0) + guesses)
        System.out.println(word.replaceAll("(?<=.)", " ").replaceAll("[^" + guesses + "]", "_"));
    System.out.println(word + (misses > MAX_MISSES ? " not" : "") + " solved with " + misses + " incorrect guesses");
}

Some notes:

  • Regex is used to both check for solution and display the current guess status
  • & is used instead of && in the loop termination to force both sides of the logic to be executed – thus always updating the misses correctly
  • Various other tricks have been used to deliberately increase code density

There is no error checking for input. If more than one letter is input by the user, only the first is used. If no letters are input, it will explode. Error checking could be added without adding much more code, but the for line would be a whopper – I leave that as an exercise for the reader.

Also, there is no checking for erroneously guessing the same letter multiple times. With this code, if you guess a correct letter twice, nothing bad happens, but if you guess a wrong letter twice, it counts as a separate “miss”, so you’ll burn one of your chances.

Leave a Comment