// Tim Hutcheson // COP 4331 Mon. & Wed. 3:30 // Stud. ID. 999-99-9999 // Homework #4 // MindReader.java // --------------- import java.util.*; // the MindReader class encapsulates a simple data base (hashTable), a time series // prediction method and shift buffer, and a table update method for associating the // plays of the game and their values in the hashtable. public class MindReader { private ShiftBuffer sb; private Hashtable ht = new Hashtable (); // The following variables are used to store the information of the game // for use by either a command line version or an applet version of the game. private String guess; private char prediction; private int playerScore, Score; public boolean Won; public MindReader( int size ) { sb = new ShiftBuffer( size ); } public void reset() { playerScore = 0; Score = 0; sb.reset(); } public int Score() { return Score; } public int playerScore() { return playerScore; } public String getBuffer() { return sb.toString(); } public String toString() { int matchScore = Math.abs(Score - playerScore); String str = (Score-playerScore>0)?" down ":" up "; return( matchScore + str + "with " + (25 - (Score + playerScore)) + " to go" ); } // play() handles the actual play of the game and can be used by either // a command line implementation or an applet implementation. Interface // and implementation are separated about the variables guess and // predicition. public char play( String guess ) { prediction = getPrediction(); storePlayerGuess( guess.charAt(0) ); Won = (guess.charAt(0) == prediction); if( Won ) Score++; else playerScore++; return prediction; } // getPrediction will return the computers best guess at the expected // value of the players move using time sereis prediction methods. public char getPrediction() { HTcounter query = new HTcounter(); query = (HTcounter)ht.get(sb.toString()); // If the current shifBuffer exists in the database, use its // HTcounter object to decide what the best guess is. If the // key is not present, just use a random guess. if( query != null ) { int heads = query.getHead(); int tails = query.getTail(); if( heads != tails ) return heads > tails ? 'h' : 't'; } return Math.random() > .5 ? 'h' : 't'; } // storePlayerGuess updates the data base at each round of play. public void storePlayerGuess( char guess ) { String key = sb.toString(); HTcounter counter; // If the key exists in the hashtable, get handle to its counter. // Otherwise create a counter object and insert it in table. Then // use the handle to update the counter values. Finally shift the // shiftbuffer to insert the guess for the next round. if( ht.containsKey(key) ) counter = (HTcounter)ht.get( key ); else { counter = new HTcounter(); ht.put( key, counter ); } if( guess == 'h' ) counter.incrHead(); if( guess == 't' ) counter.incrTail(); sb.shift( guess ); } }