|
| 1 | +import java.util.Scanner; |
| 2 | + |
| 3 | +public class RiddleGame { |
| 4 | + public static void main(String[] args) { |
| 5 | + Scanner scanner = new Scanner(System.in); |
| 6 | + int score = 0; |
| 7 | + |
| 8 | + // Define an array of riddles and their corresponding answers. |
| 9 | + String[] riddles = { |
| 10 | + "I speak without a mouth and hear without ears. I have no body, but I come alive with the wind. What am I?", |
| 11 | + "The more you take, the more you leave behind. What am I?", |
| 12 | + "I'm not alive, but I can grow; I don't have lungs, but I need air; I don't have a mouth, but water kills me. What am I?" |
| 13 | + }; |
| 14 | + |
| 15 | + String[] answers = { |
| 16 | + "An echo", |
| 17 | + "Footsteps", |
| 18 | + "A fire" |
| 19 | + }; |
| 20 | + |
| 21 | + // Define hints for each riddle. |
| 22 | + String[] hints = { |
| 23 | + "Hint: This thing is known for its ability to reflect sound.", |
| 24 | + "Hint: Think about what you leave behind when you walk.", |
| 25 | + "Hint: It produces heat and light." |
| 26 | + }; |
| 27 | + |
| 28 | + int numRiddles = riddles.length; |
| 29 | + |
| 30 | + while (true) { |
| 31 | + int randomIndex = (int) (Math.random() * numRiddles); |
| 32 | + String selectedRiddle = riddles[randomIndex]; |
| 33 | + String correctAnswer = answers[randomIndex]; |
| 34 | + String hint = hints[randomIndex]; |
| 35 | + |
| 36 | + // Display the riddle to the user. |
| 37 | + System.out.println("Riddle: " + selectedRiddle); |
| 38 | + |
| 39 | + // Get user's answer. |
| 40 | + String userAnswer = scanner.nextLine(); |
| 41 | + |
| 42 | + if (userAnswer.equalsIgnoreCase(correctAnswer)) { |
| 43 | + System.out.println("Correct!"); |
| 44 | + score++; |
| 45 | + } else { |
| 46 | + // If the answer is incorrect, offer a hint. |
| 47 | + System.out.println("Wrong! Would you like a hint? (yes/no)"); |
| 48 | + String giveHint = scanner.nextLine().toLowerCase(); |
| 49 | + if (giveHint.equals("yes")) { |
| 50 | + System.out.println(hint); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + // Allow the user to continue or exit. |
| 55 | + System.out.println("Continue playing? (yes/no)"); |
| 56 | + String playAgain = scanner.nextLine().toLowerCase(); |
| 57 | + if (!playAgain.equals("yes")) { |
| 58 | + break; |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + // Display final score. |
| 63 | + System.out.println("Your final score: " + score); |
| 64 | + System.out.println("Thanks for playing!"); |
| 65 | + } |
| 66 | +} |
0 commit comments