Header Ads

[OOP] Game Guess the Number



Let's create a game called "Guess the Number." In this game, the computer will generate a random number between 1 and 100, and the player will have to guess the number. The game will give hints to the player on whether their guess is too high or too low, and the player will continue to guess until they get the correct number.

To implement this game in OOP Java, we can create three classes:

  • Game: This class will manage the game flow and user input.
  • Player: This class will represent the player and their actions.
  • RandomNumberGenerator: This class will generate a random number for the player to guess.

1. Game class:

import java.util.Scanner;

public class Game {
    private RandomNumberGenerator rng;
    private Player player;
    private int maxGuesses;

    public Game() {
        rng = new RandomNumberGenerator();
        player = new Player();
        maxGuesses = 10;
    }

    public void start() {
        int randomNumber = rng.generate();
        int guessCount = 0;
        boolean correctGuess = false;

        while (guessCount < maxGuesses && !correctGuess) {
            int guess = player.guessNumber();

            if (guess == randomNumber) {
                System.out.println("Congratulations! You guessed the number.");
                correctGuess = true;
            } else if (guess < randomNumber) {
                System.out.println("Too low. Guess higher.");
            } else {
                System.out.println("Too high. Guess lower.");
            }

            guessCount++;
        }

        if (!correctGuess) {
            System.out.println("Sorry, you ran out of guesses. The number was " + randomNumber);
        }
    }
}

2. Player class:

import java.util.Scanner;

public class Player {
    private Scanner scanner;

    public Player() {
        scanner = new Scanner(System.in);
    }

    public int guessNumber() {
        System.out.print("Guess a number between 1 and 100: ");
        int guess = scanner.nextInt();
        return guess;
    }
}

3. RandomNumberGenerator class:

import java.util.Random;

public class RandomNumberGenerator {
    private Random random;

    public RandomNumberGenerator() {
        random = new Random();
    }

    public int generate() {
        return random.nextInt(100) + 1;
    }
}

To start the game, we can create an instance of the Game class and call the start method:

public static void main(String[] args) {
    Game game = new Game();
    game.start();
}

Nguồn: chatGPT

Không có nhận xét nào

Được tạo bởi Blogger.