|
| 1 | +import java.util.Scanner; |
| 2 | + |
| 3 | +public class HangmanGame { |
| 4 | + private static String[] words = {"java", "programming", "hangman", "computer", "algorithm"}; |
| 5 | + private static String selectedWord; |
| 6 | + private static String guessedWord; |
| 7 | + private static int maxAttempts = 6; |
| 8 | + private static int attemptsLeft = maxAttempts; |
| 9 | + |
| 10 | + public static void main(String[] args) { |
| 11 | + Scanner scanner = new Scanner(System.in); |
| 12 | + selectWord(); |
| 13 | + |
| 14 | + while (true) { |
| 15 | + System.out.println("Word: " + guessedWord); |
| 16 | + System.out.println("Attempts left: " + attemptsLeft); |
| 17 | + System.out.print("Enter a letter or the entire word: "); |
| 18 | + String guess = scanner.nextLine().toLowerCase(); |
| 19 | + |
| 20 | + if (guess.length() == 1) { |
| 21 | + processLetterGuess(guess.charAt(0)); |
| 22 | + } else if (guess.length() == selectedWord.length()) { |
| 23 | + processWordGuess(guess); |
| 24 | + } else { |
| 25 | + System.out.println("Invalid input. Please enter a single letter or the entire word."); |
| 26 | + } |
| 27 | + |
| 28 | + if (guessedWord.equals(selectedWord)) { |
| 29 | + System.out.println("Congratulations! You've guessed the word: " + selectedWord); |
| 30 | + break; |
| 31 | + } else if (attemptsLeft == 0) { |
| 32 | + System.out.println("You've run out of attempts. The word was: " + selectedWord); |
| 33 | + break; |
| 34 | + } |
| 35 | + } |
| 36 | + scanner.close(); |
| 37 | + } |
| 38 | + |
| 39 | + private static void selectWord() { |
| 40 | + selectedWord = words[(int) (Math.random() * words.length)]; |
| 41 | + guessedWord = new String(new char[selectedWord.length()]).replace('\0', '_'); |
| 42 | + } |
| 43 | + |
| 44 | + private static void processLetterGuess(char letter) { |
| 45 | + boolean found = false; |
| 46 | + for (int i = 0; i < selectedWord.length(); i++) { |
| 47 | + if (selectedWord.charAt(i) == letter) { |
| 48 | + guessedWord = guessedWord.substring(0, i) + letter + guessedWord.substring(i + 1); |
| 49 | + found = true; |
| 50 | + } |
| 51 | + } |
| 52 | + if (!found) { |
| 53 | + attemptsLeft--; |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + private static void processWordGuess(String word) { |
| 58 | + if (word.equals(selectedWord)) { |
| 59 | + guessedWord = selectedWord; |
| 60 | + } else { |
| 61 | + attemptsLeft--; |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments