Simple Hangman game in Java
Below is a simple implementation of the Hangman game in Java. This code assumes a console-based interaction.
import java.util.Scanner; public class HangmanGame { private static final String[] WORDS = {"java", "python", "hangman", "programming", "computer"}; private static final int MAX_TRIES = 6; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String secretWord = getRandomWord(); char[] guessedLetters = new char[secretWord.length()]; int tries = 0; while (true) { displayHangman(tries); displayGuessedWord(guessedLetters); System.out.println("Enter a letter: "); char guess = scanner.next().charAt(0); if (isLetterAlreadyGuessed(guess, guessedLetters)) { System.out.println("You've already guessed that letter. Try again."); continue; } if (secretWord.contains(String.valueOf(guess))) { updateGuessedLetters(secretWord, guessedLetters, guess); } else { tries++; } if (isWordGuessed(guessedLetters)) { System.out.println("Congratulations! You guessed the word: " + secretWord); break; } if (tries == MAX_TRIES) { displayHangman(MAX_TRIES); System.out.println("Sorry, you ran out of tries. The correct word was: " + secretWord); break; } } scanner.close(); } private static String getRandomWord() { int randomIndex = (int) (Math.random() * WORDS.length); return WORDS[randomIndex]; } private static void displayHangman(int tries) { // Add hangman drawing logic based on the number of tries // You can customize the ASCII art for the hangman as needed. } private static void displayGuessedWord(char[] guessedLetters) { System.out.print("Current word: "); for (char letter : guessedLetters) { if (letter == '\0') { System.out.print("_ "); } else { System.out.print(letter + " "); } } System.out.println(); } private static boolean isLetterAlreadyGuessed(char guess, char[] guessedLetters) { for (char letter : guessedLetters) { if (letter == guess) { return true; } } return false; } private static void updateGuessedLetters(String secretWord, char[] guessedLetters, char guess) { for (int i = 0; i < secretWord.length(); i++) { if (secretWord.charAt(i) == guess) { guessedLetters[i] = guess; } } } private static boolean isWordGuessed(char[] guessedLetters) { for (char letter : guessedLetters) { if (letter == '\0') { return false; } } return true; } }