import java.util.Scanner; /** * Builds a decision tree by playing a guessing game with a human. */ public class GuessingGame { /** * Utility method: read a line from the user and return whether * it was a "yes" (versus a "no") */ private static boolean answeredYes(Scanner human) { do { String response = human.nextLine().toLowerCase(); if (response.equals("yes")) { return true; } else if (response.equals("no")) { return false; } else { System.out.println("Answer yes or no: "); } } while (true); // loop until yes or no is given } /** * Make a decision (if at a leaf) or ask a question (if at an interior node) * using the given decision tree. */ public static void play(Scanner human, BinaryTree tree) { if (tree.isLeaf()) { // at leaf - must be single object left System.out.println("Is it a " + tree.value() + "?"); if (answeredYes(human)) { System.out.println("I'm so smart!"); } else { learn(human, tree); } } else { // further choices; must ask a question to distinguish them String nextQuestion = tree.value(); System.out.println(nextQuestion); if (answeredYes(human)) { play(human, tree.left()); } else { play(human, tree.right()); } } } /** * Respond to a wrong answer by updating the decision tree with new knowledge. */ public static void learn(Scanner human, BinaryTree leaf) { System.out.println("Darn. What were you thinking of?"); BinaryTree newObject = new BinaryTree(human.nextLine()); BinaryTree oldObject = new BinaryTree(leaf.value()); System.out.println("What yes/no question would distinguish a " + newObject.value() + " (yes) from a " + oldObject.value() + " (no)?"); String newQuestion = human.nextLine(); leaf.setValue(newQuestion); leaf.setLeft(newObject); // note: no longer a leaf leaf.setRight(oldObject); } /** * Initialize a new decision tree and play the guessing game. */ public static void main(String args[]) { Scanner human = new Scanner(System.in); BinaryTree tree = new BinaryTree("computer"); do { System.out.println("\n==================================="); System.out.println("Think of something...I'll guess it!"); System.out.println("Press enter when you're ready."); human.nextLine(); // wait for enter play(human, tree); } while (true); } }