import java.util.InputMismatchException; import java.util.Scanner; import java.util.Random; class Game { protected int secretNumber; protected int maxChoices; protected int choicesLeft; public Game(int maxChoices) { this.maxChoices = maxChoices; choicesLeft = maxChoices; } public void generateSecretNumber() { Random random = new Random(); secretNumber = random.nextInt(100) + 1; } public void play() { Scanner scanner = new Scanner(System.in); for (int i = 0; i < maxChoices; i++) { System.out.print("\nEnter the number: "); int playerChoice; try { playerChoice = scanner.nextInt(); } catch (InputMismatchException e) { System.out.println("Invalid input. Please enter an integer."); scanner.nextLine(); // Clear the buffer continue; } if (playerChoice == secretNumber) { System.out.println("Well played! You won, " + playerChoice + " is the secret number"); System.out.println("\t\t\t Thanks for playing...."); System.out.println("Play the game again with us!!\n"); return; } else { System.out.println("Nope, " + playerChoice + " is not the right number"); if (playerChoice > secretNumber) { System.out.println("The secret number is smaller than the number you have chosen"); } else { System.out.println("The secret number is greater than the number you have chosen"); } choicesLeft--; System.out.println(choicesLeft + " choices left."); if (choicesLeft == 0) { System.out.println("You couldn't find the secret number, it was " + secretNumber + ", You lose!!"); System.out.println("Play the game again to win!!!\n"); return; } } } } } class EasyGame extends Game { public EasyGame() { super(10); } } class MediumGame extends Game { public MediumGame() { super(7); } } class DifficultGame extends Game { public DifficultGame() { super(5); } } public class GuessTheNumber { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("\n\t\t\tWelcome to GuessTheNumber game!"); System.out.println("You have to guess a number between 1 and 100. " + "You'll have limited choices based on the level you choose. Good Luck!\n"); while (true) { System.out.println("Enter the difficulty level: "); System.out.println("1 for easy!\t" + "2 for medium!\t" + "3 for difficult!\t" + "0 for ending the game!\n"); int difficultyChoice; try { difficultyChoice = scanner.nextInt(); } catch (InputMismatchException e) { System.out.println("Invalid input. Please enter an integer."); scanner.nextLine(); // Clear the buffer continue; } Game game; switch (difficultyChoice) { case 1: game = new EasyGame(); break; case 2: game = new MediumGame(); break; case 3: game = new DifficultGame(); break; case 0: System.out.println("Thanks for playing. Goodbye!"); return; default: System.out.println("Invalid choice. Please enter a valid choice (0, 1, 2, 3)."); continue; } game.generateSecretNumber(); game.play(); } } }