Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

UserInterface.java QuestionMain.java This program focuses on binary trees and recursion. Turn in files QuestionTree.java and QuestionNode.java. You will need support files User Interface.java, QuestionMain.java, VaderMain.java,

image text in transcribed
image text in transcribed
image text in transcribed
image text in transcribed
UserInterface.java
image text in transcribed
QuestionMain.java
image text in transcribed
image text in transcribed
image text in transcribed
image text in transcribed
This program focuses on binary trees and recursion. Turn in files QuestionTree.java and QuestionNode.java. You will need support files User Interface.java, QuestionMain.java, VaderMain.java, and input text files from Canvas; place them in the same folder as your class. The Game of 20 Questions: In this assignment you will implement a yeso guessing game called "20 Questions." Each round of the game begins by you (the human player) thinking of an object. The computer will try to guess your object by asking you a series of yes or no questions. Eventually the computer will have asked enough questions that it thinks it knows what object you are thinking of. It will make a guess about what your object is. If this guess is correct, the computer wins; if not, you win. The computer keeps track of a binary tree whose nodes represent questions and answers. (Every node's data is a string representing the text of the question or answer.) A "question" node contains a left "yes" subtree and a right "no" subtree. An "answer" node is a leaf. The idea is that this tree can be traversed to ask the human player a series of questions. (Through the game is called "20 Questions," out game will not limit the tree to a height of 20. Any height is allowed.) For example, in the tree below, the computer would begin the game by asking the player, "Is it an animal?" If the player says "yes," the computer goes left to the "yes" subtree and then asks the user, "Can it fly?" If the user had instead said "no" the computer would go right to the "no" subtree and then ask the user, "Does it have wheels?" This pattern continues until the game reaches a leaf "answer" node. Upon reaching an answer node, the computer asks whether that answer is the correct answer. If so, the computer wins. (left = "yes") overall root (right = "no" Is it an animal? Can it fly? Does it have wheels? bird Does it have a tail? bicycle Is it nice? mouse spider TA teacher The following partial output log shows one game being played on the above tree: Is it an animal? yes Can it fly? no Does it have a tail? yes Would your object happen to be mouse? yes I win! Initially the computer is not very intelligent, but it grows more intelligent cach time it loses a game. If the computer's answer guess is incorrect, you must give it a new question it can ask to help it in future games. For example, suppose in the preceding log that the player was not thinking of a mouse, but of a cat. The game log might look like this: Is it an animal? yes Can it fly? no Does it have a tail? yes Would your object happen to be mouse? no I lose. What is your object? cat Type a yeso question to distinguish your item from mouse: Does it meow? And what is the answer for your object? yes The computer takes the new information from a lost game and use it to replace the old incorrect answer node with a new question node that has the old incorrect answer and new correct answer as its children. For example, after the game represented by the preceding log, the computer's overall game tree would be the following: (left="yes") overall roor (right -"no" Is it an animal? Can it fly? Does it have wheels? bird Does it have a tail? bicycle Is it nice? Does it meow? spider TA teacher cat mouse In this assignment, you will create classes QuestionTree and QuestionNode to represent the computer's tree of yeso questions and answers for playing games of 20 Questions. You are provided with a client Question Main that handles user interaction and calls your tree's methods to play games. Below are two logs of execution (user input is underlined): Log of execution #1 Log of execution #2 Welcome to the game of 20 Questions! Welcome to the game of 20 Questions! Shall I recall our previous games? Shall I recall our previous games? yes What is the file name? question2.txt Think of an item, and I will guess it. Think of an item, and I will guess it. Would your object happen to be Jedi? n I lose. What is your object? hobbit Is it an animal? no Type a yeso question to distinguish your Does it have wheels? yes item from Jedi : Does it use the force? Would your object happen to be bicycle? yes And what is the answer for your object? n I win! Challenge me again? Y Challenge me again? yes Does it use the Force? Is it an animal? yes Would your object happen to be hobbit? Can it fly? no I lose. What is your object? droid Does it have a tail? yes Type a yeso question to distinguish your Would your object happen to be mouse? no item from hobbit: Is it metal? I lose. What is your object? cat And what is the answer for your object? Y Type a yeso question to distinguish your Challenge me again? Y item from mouse: Does it meow? And what is the answer to your object? yes Does it use the Force? Challenge me again? yes Is it metal? Y Would your object happen to be droid? Y Is it an animal? yes I win! Can it fly? no Challenge me again? Does it have a tall? yes Does it meow? yes Games played: 3 Would your object happen to be cat? yes I won: 1 I win! Shall I remember these games? What is the file name? questioni. txt Challenge me again? no Games played: 3 I won: 2 Shall I remember these games? no The program can instruct your question tree to read its input from different text files. You should initially test with the provided questioni.txt or an even smaller file of your own creation. As your code runs, you will be able to create larger files by saving them at the end of the program. Once your code works with questioni.txt, you can test it with a larger input such as the provided animals.txt, which comes with permission from the Animal Game web site at http://animalgame.com/. Check your output using our Output Comparison Tool from the course web site. Implementation Details: The contents of the Questionnode class are up to you. Though we have studied trees of ints, in this assignment you can create nodes specific to solving this problem. Your node class should have at least one constructor used by your tree. Your node's fields can be public. QuestionNode should not perform a large share of the overall game algorithm. Your QuestionTree must have the following members. You may add extra private methods. You should throw an IllegalArgumentException if the parameter passed to any method below is null public QuestionTree (User Interface ui) In this constructor you should initialize your new question tree. You are passed an object representing the user interface for input/output. Your tree will use this user interface for printing output messages and asking questions in the game (see next page). Initially the tree starts out containing only a single answer leaf node with the word "Jedi" in it. The tree will grow larger as games are played or as a new tree is loaded with the load method described below. public void play() A call to this method should play one complete guessing game with the user, asking yeso questions until reaching an answer object to guess. A game begins with the root node of the tree and ends upon reaching an answer leaf node. If the computer wins the game, print a message saying so. Otherwise your tree must ask the user what object he/she was thinking of a question to distinguish that object from the player's guess, and whether the player's object is the yes or no answer for that question. The two boxed partial logs on the first page are examples of output from single calls to play. All user input/output should be done through the User Interface object passed to your tree's constructor. After the game is over, the provided client program will prompt the user whether or not to play again; this is not part of your play method. Leave this functionality to the client program. public void save (PrintStream output) In this method you should store the current tree state to an output file represented by the given PrintStream. In this way your question tree can grow each time the user runs the program. (You don't save the number of games played won) A tree is specified by a sequence of lines, one for each node. Each line must start with either Q: to indicate a question node or A: to indicate an answer (a leaf). All characters after these first two should represent the text for that node (the question or answer). The nodes should appear in the order produced by a preorder traversal of the tree. For example, the two trees shown in the diagram and logs on the preceding pages would be represented by the following contents question1.txt question2.txt Q: Does it use the Force? Q:Is it an animal? A: Jedi Q:Can it fly2 Q:Is it metal? Arbird A droid Q:Does it have a tail? A: hobbit A mouse A:spider Q: Does it have wheels? A:bicycle Q:Is it nice? A:TA A:teacher public void load(Scanner input) In this method you should replace the current tree by reading another tree from a file. Your method will be passed a Scanner that reads from a file and should replace the current tree nodes with a new tree using the information in the file. Assume the file exists and is in proper standard format. Read entire lines of input using calls on Scanner's nextLine. (You don't load the number of games played won, just the tree. Calling this method doesn't change games played won.) public int totalGamen() public int game won(). In these methods you should respectively return the total number of games that have been played on this tree so far, and the number of games the computer has won by correctly guessing your object, during the current execution of the program. Initially 0 games have been played and won, but the games played increase by 1 for each game that is played (each time play is called), and the games won increase by 1 each time the computer guesses your object correctly. User Interface: Your tree should be designed to be usable with many user interfaces. We have provided a class QuestionMain with a text user interface and a class VaderMain with a graphical user interface. Both of these classes need to display output to the user and read input from the keyboard, but they do so in different ways (console vs. graphic). In order for your code to work with both programs, we provide you with a Java interface for the common behavior of both user interfaces: public interface User Interface public void print(String message); W displays an output message to the user public void println(String message); Il displays an output message and new-line public String nextLine(); 17 waits for user to type a string; returns it public boolean nextBoolean(); // waits for user to choose yes (true) / no (false) For example, if you had a variable us that referred to an object that implements the User Interface interface, you could write the following code to ask the user a yeso question: ui.print("Are you having a nice day?"); boolean yesNo - ui.nextboolean(); if (yesno) ul.println("That is good to hear!"); // true means user said "yes" ) else? ui.println("Sorry to hear that."); // false means user said "no" } The following code would ask the user a more general question to which the user could type any string as a response: ui.print("What is your name?"); String answer - ui.nextLine(); You must use this user interface in your program. Programs that do not do so and try to handle user interaction directly will lose substantial credit on the assignment. Creative Aspect (my questions.txt): Along with your program, turn in a file myquestions.txt that represents a saved question tree in the format specified from your save method. For full credit, this must be in proper format, have a height of at least 5, and be your own work. 9 public interface User Interface { 10 /** 11 * Waits for the user to input a yeso answer (by typing, clicking, etc.), 12 * and returns that answer as a boolean value. 13 * @return the answer typed by the user as a boolean (yes is true, no is false) 14 */ 15 boolean nextBoolean(); 16 17 18 * Waits for the user to input a text value, and returns that answer as a String. 19 *ereturn the answer typed by the user as a string (empty string if no answer typed) 20 / 21 String nextLine(); 22 23 /** 24 * Displays the given output message to the user. 25 Oparam message The message to display. Assumes not null. 26 #/ 27 void print(String message); 28 29 /** * Displays the given output message to the user. 31 If the ur is a text UI, also inserts a line break ( ). 32 * @param message The message to display. Assumes not null. 33 */ 34 void println(String message); 35 36 11 various messages that are output by the user interface 37 11 (your QuestionTree does not need to refer to these messages) 38 final String PLAY_AGAIN_MESSAGE - "Challenge me again?", final String SAVE MESSAGE - "Shall I remember these games?", 40 final String LOAD_MESSAGE - "Shall I recall our previous games?", 41 final String SAVE_LOAD_FILENAME_MESSAGE - "What is the file name2", 42 final String STATUS_MESSAGE - "Games played: $d I won: 8d", 43 final String BANNER_MESSAGE - "Think of an item, and I will guess it.", 30 39 1 k 20 Questions 277 3/1 To use the jGRASP debugger with this program, set a breakpoint 471 and once the execution breaks, open 'this' or 'tg' on the left, 5 // then look at its variable 'tree'. That's your questionTree. 6 // Drag your 'tree' over to the right to see a visualization of it. 7 // 8/1 (Your QuestionTree is constructed by this file on line 30. 9 // The overall loop to play games is around line 68.) 10 11 import java.io.*; 12 import java.util.Scanner; 13 14 /** A basic text user interface for the 20 questions game. */ 15 public class QuestionMain implements User Interface { 16 public static void main(String[] args) { 17 QuestionMain ta = new QuestionMain(); 18 tq.run(); 19 } 20 21 22 // fields 23 private Scanner console; 24 private QuestionTree tree; 25 26 /** Constructs a text user interface and its question tree. */ 27 public QuestionMain() { 28 console - new Scanner(System.in); 29 tree = new QuestionTree (this); 30 } 31 32 /** 33 * Returns the user's response as a String. 34 */ 35 public String nextLine() { 36 return console.nextLine(); au PWNO } /** Prints the given string to the console. */ public void print(String message) { System.out.print(message); System.out.print(" "); } /** Prints the given string to the console. */ public void println(String message) { System.out.println(message); } /** Prints a blank line to the console. */ public void println() { System.out.println(); } 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 * Waits for the user to answer a yeso question on the console and returns the * user's response as a boolean (true for anything that starts with "y" or "Y"). */ public boolean nextBoolean() { String answer - console.nextLine(); return answer.trim().toLowerCase().startsWith("/"); } // private helper for overall game(s) loop private void run() { println("Welcome to the game of 20 Questions!"); load(); 11 "Think of an item, and I will guess it in N tries." println(" " + BANNER_MESSAGE); do { 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 // play one complete game println(); // blank line between games tree.play(); print (PLAY_AGAIN_MESSAGE) ; } while (nextBoolean()); // prompt to play again // print overall stats // Games played: N... I have won: M println("in" + String.format(STATUS_MESSAGE, tree.totalGames(), tree.gameswon())); save(); } 11 common code for asking the user whether they want to save or load private void load() { print(LOAD_MESSAGE); if (nextBoolean()) { print (SAVE_LOAD_FILENAME_MESSAGE); String filename - nextLine(); try { Scanner in - new Scanner (new File(filename)); tree.load(in); } catch (FileNotFoundException e) { System.out.println("Error: + e.getMessage()); } } 11 common code for asking the user whether they want to save or load private void save() { print (SAVE_MESSAGE); if (nextBoolean()) { print (SAVE_LOAD_FILENAME_MESSAGE); String filename = nextLine(); try { 109 110 111 112 113 114 115 116 117} 118 PrintStream out new PrintStream(new File(filename)); tree.save (out); out.close(); } catch (FileNotFoundException e) { System.out.println("Error: " + e.getMessage()); }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Records And Database Management

Authors: Jeffrey R Stewart Ed D, Judith S Greene, Judith A Hickey

4th Edition

0070614741, 9780070614741

More Books

Students also viewed these Databases questions