Answer to Question #280108 in Java | JSP | JSF for Jacob

Question #280108

Create a simple text-based console game that implements at least three (3) interfaces.


1
Expert's answer
2021-12-17T18:18:21-0500
public interface Counter {

    boolean addPoints();

    boolean subtractPoints();

}


public interface Printer {
    void showScore();

    void showPrompt();
}


public interface Generator {
    int getNumber();
}


import java.util.Random;
import java.util.Scanner;

public class Game implements Counter, Printer, Generator {
    private Random random;
    private int score;
    private int maxNumber = 5;

    public Game() {
        random = new Random();
        score = 10;
    }

    @Override
    public boolean addPoints() {
        score += 2;
        return score > 19;
    }

    @Override
    public boolean subtractPoints() {
        score -= 1;
        return score < 0;
    }

    @Override
    public void showPrompt() {
        System.out.println("Enter a number in range 1 - " + maxNumber + ": ");
    }

    @Override
    public void showScore() {
        System.out.println("Score: " + score);
    }

    @Override
    public int getNumber() {
        return random.nextInt(maxNumber) + 1;
    }

    public static void main(String[] args) {
        Game game = new Game();
        Scanner in = new Scanner(System.in);
        while (true) {
            int number = game.getNumber();
            while (true) {
                game.showPrompt();
                int guess = in.nextInt();
                if (guess == number) {
                    break;
                }
                System.out.println("Incorrect");
                if (game.subtractPoints()) {
                    System.out.println("YOU LOSE!");
                    return;
                }
                game.showScore();
            }
            System.out.println("Correct");
            if (game.addPoints()) {
                System.out.println("YOU WIN!");
            }
            game.showScore();
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog