001package edu.pdx.cs410J.security;
002
003import java.io.*;
004
005/**
006 * This is a little guessing game that counts the number of times it
007 * takes the user to guess a number between one and ten.
008 */
009public class GuessingGame implements Game {
010
011  private PrintStream out = System.out;
012  private BufferedReader in = 
013    new BufferedReader(new InputStreamReader(System.in));
014
015  public String getName() {
016    return "GuessingGame";
017  }
018
019  /**
020   * Plays the game
021   */
022  public void play(GameConsole console) {
023    int number = ((int) (Math.random() * 10.0)) + 1;
024
025    out.println("I'm thinking of a number between 1 and 10");
026
027    // First get the preferences
028    String prefs = console.readPreferences(this);
029    if (prefs == null) {
030      System.err.println("** Couldn't read preferences");
031      return;
032    }
033
034    int highScore = -1;
035    try {
036      highScore = Integer.parseInt(prefs.trim());
037      out.println("The high score is: " + highScore);
038    } catch (NumberFormatException ex) {
039      // Ignore
040    }
041
042    // Guess the number
043    int guesses = 1;
044    while (true) {
045      out.print("Your guess: ");
046      int guess = getGuess();
047      if ((guess < 1) || (guess > 10)) {
048        out.println("Guess a number between 1 and 10");
049
050      } else if (guess > number) {
051        out.println("Too high!");
052
053      } else if (guess < number) {
054        out.println("Too low!");
055
056      } else {
057        out.println("You guessed right!");
058        break;
059      }
060
061      guesses++;
062    }
063
064    out.println("It took you " + guesses + " guesses");
065    
066    if ((highScore == -1) || (guesses < highScore)) {
067      out.println("A new high score!");
068      prefs = guesses + "";
069      if (!console.writePreferences(this, prefs)) {
070        System.err.println("** Couldn't write preferences");
071      }
072    }
073
074    out.println("Thanks for playing");
075  }
076
077  /**
078   * Reads an <code>int</code> from System.in
079   */
080  private int getGuess() {
081    try {
082      return Integer.parseInt(in.readLine());
083
084    } catch (NumberFormatException ex) {
085      return -1;
086
087    } catch (IOException ex) {
088      return -1;
089    }
090  }
091  
092  /**
093   * Test program
094   */
095  public static void main(String[] args) {
096    GameConsole console = new GameConsole();
097    Game game = new GuessingGame();
098    game.play(console);
099  }
100
101}
102