import java.util.*; public class HangmanGame { private String word; private Set guessed = new HashSet<>(); private int errors = 0; private int maxErrors = 9; public HangmanGame(List words) { this.word = words.get(new Random().nextInt(words.size())).toUpperCase(); } public void setMaxErrors(int max) { this.maxErrors = max; } public int getErrors() { return errors; } public int getMaxErrors() { return maxErrors; } public boolean guess(char c) { c = Character.toUpperCase(c); if (guessed.contains(c)) return true; guessed.add(c); if (!word.contains(String.valueOf(c))) errors++; return isWon() || !isLost(); } public String getMaskedWord() { StringBuilder sb = new StringBuilder(); for (char c : word.toCharArray()) { sb.append(guessed.contains(c) ? c : '_'); sb.append(' '); } return sb.toString(); } public String getHistory() { List list = new ArrayList<>(guessed); Collections.sort(list); StringBuilder sb = new StringBuilder(); for (char c : list) sb.append(c).append(' '); return sb.toString(); } public boolean isWon() { for (char c : word.toCharArray()) if (!guessed.contains(c)) return false; return true; } public boolean isLost() { return errors >= maxErrors; } public String getWord() { return word; } }