|
| 1 | +import java.util.Scanner; |
| 2 | +import java.util.Random; |
| 3 | + |
| 4 | +public class HangmanGame { |
| 5 | + public static void main(String[] args) { |
| 6 | + String[] words = { "java", "programming", "hangman", "computer", "algorithm", "developer" }; |
| 7 | + Random random = new Random(); |
| 8 | + String wordToGuess = words[random.nextInt(words.length)]; |
| 9 | + |
| 10 | + int maxAttempts = 6; |
| 11 | + int attemptsLeft = maxAttempts; |
| 12 | + boolean[] guessedLetters = new boolean[wordToGuess.length()]; |
| 13 | + |
| 14 | + Scanner scanner = new Scanner(System.in); |
| 15 | + |
| 16 | + System.out.println("Welcome to Hangman!"); |
| 17 | + char[] displayWord = new char[wordToGuess.length()]; |
| 18 | + for (int i = 0; i < wordToGuess.length(); i++) { |
| 19 | + displayWord[i] = '_'; |
| 20 | + } |
| 21 | + |
| 22 | + while (attemptsLeft > 0) { |
| 23 | + System.out.println("Word to guess: " + new String(displayWord)); |
| 24 | + System.out.println("Attempts left: " + attemptsLeft); |
| 25 | + System.out.print("Guess a letter: "); |
| 26 | + char guess = scanner.next().charAt(0); |
| 27 | + |
| 28 | + boolean found = false; |
| 29 | + for (int i = 0; i < wordToGuess.length(); i++) { |
| 30 | + if (wordToGuess.charAt(i) == guess) { |
| 31 | + displayWord[i] = guess; |
| 32 | + guessedLetters[i] = true; |
| 33 | + found = true; |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + if (!found) { |
| 38 | + System.out.println("Incorrect guess."); |
| 39 | + attemptsLeft--; |
| 40 | + } |
| 41 | + |
| 42 | + boolean isComplete = true; |
| 43 | + for (boolean guessed : guessedLetters) { |
| 44 | + if (!guessed) { |
| 45 | + isComplete = false; |
| 46 | + break; |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + if (isComplete) { |
| 51 | + System.out.println("Congratulations! You've guessed the word: " + wordToGuess); |
| 52 | + break; |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + if (attemptsLeft == 0) { |
| 57 | + System.out.println("Out of attempts. The word was: " + wordToGuess); |
| 58 | + } |
| 59 | + |
| 60 | + scanner.close(); |
| 61 | + } |
| 62 | +} |
0 commit comments