//A simple Human-Computer Number Guessing Game import java.util.Random; public class GuessingGame implements InteractiveGame { //Range of possible "secret" numbers public static final int MINIMUM = 1; public static final int MAXIMUM = 100; //Instance Variables private int secretNumber; //The secret number the players try to guess private boolean guessedRight; //false until player guesses the secret number private boolean playersTurn; //true when it's the human player's turn private boolean smartMode; //true if the computer plays smart, false otherwise private int rangeMin; //Current lowest possible smart guess private int rangeMax; //Current highest possible smart guess private String record; //Record of the game as it progresses //Constructor public GuessingGame(boolean computerSmart, boolean humanFirst) { this.secretNumber = randomInt(MINIMUM, MAXIMUM); this.guessedRight = false; this.playersTurn = humanFirst; this.smartMode = computerSmart; this.rangeMin = MINIMUM; this.rangeMax = MAXIMUM; this.record = "NUMBER GUESSING GAME"; } //Override: Display the state of the game public String toString() { return this.record; } //Return true if the game is decided, otherwise false public boolean isCompleted() { return this.guessedRight; } //Return true if it's the human player's turn, otherwise false public boolean isPlayersTurn() { return this.playersTurn; } //Return true if a move is legitimate, otherwise false public boolean isValidMove(String move) { try { int number = Integer.parseInt(move); return number >= MINIMUM && number <= MAXIMUM; } catch (NumberFormatException nfex) { return false; } } //Apply the human player's move to update the state of the game public void makePlayersMove(String move) { int guess = Integer.parseInt(move); updateGame("PLAYER", guess); } //Apply the computer player's move to update the state of the game public void makeComputersMove() { int guess = (this.smartMode ? this.rangeMin + (this.rangeMax - this.rangeMin)/2 : randomInt(MINIMUM, MAXIMUM) ); updateGame("COMPUTER", guess); } //Update the state of the game to reflect either player's move private void updateGame(String player, int guess) { this.record += "\n" + player + " guessed " + guess; if (guess > this.secretNumber) { this.record += " Too HIGH"; this.rangeMax = guess - 1; } else if (guess < this.secretNumber) { this.record += " Too LOW"; this.rangeMin = guess + 1; } else this.guessedRight = true; this.playersTurn = !this.playersTurn; } //Return true if the human player has won, otherwise false public boolean playerHasWon() { return this.guessedRight && !this.playersTurn; } //Prompt the human player for their next move public String movePrompt() { return this.record + "\nGuess a number " + MINIMUM + " .. " + MAXIMUM; } //Generate a random integer within a given range private static Random generator = new Random(); private static int randomInt(int lowest, int highest) { return generator.nextInt(highest - lowest + 1) + lowest; } }