import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import javax.swing.*; @SuppressWarnings("serial") public class TwentyQuestionsGameGUI extends JFrame implements ActionListener { private ArrayList questions; private Question currentQuestion; private int count; private TextArea txtArea; private Button yesButton,noButton, restartButton; public TwentyQuestionsGameGUI() { txtArea=new TextArea(); txtArea.setFont(new Font("Helvetica", Font.BOLD,20)); txtArea.setForeground(new Color(251,182,0)); txtArea.setBackground(new Color(44,23,0)); txtArea.setEditable(false); yesButton=new Button("Yes"); yesButton.addActionListener(this); noButton=new Button("No"); noButton.addActionListener(this); restartButton=new Button("Start Over"); restartButton.addActionListener(this); //Add objects to this.setLayout(new BorderLayout()); this.add(txtArea, BorderLayout.CENTER); Panel buttonPanel=new Panel(new FlowLayout()); buttonPanel.add(yesButton); buttonPanel.add(noButton); buttonPanel.add(restartButton); this.add(buttonPanel, BorderLayout.NORTH); startOver(); setSize(800,600); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } private void startOver() { readQuestionFile(); currentQuestion=questions.get(0); count=1; txtArea.append("Twenty Questions!\n1. "+currentQuestion.getQuestion()); } @Override public void actionPerformed(ActionEvent e) { Object buttonPressed=e.getSource(); if (buttonPressed==yesButton){ if (currentQuestion.getYesLink() <0){ //computer guessed it txtArea.append(" YES !!!! I Guessed it with "+count+" questions!!\n"); }else{ currentQuestion=questions.get(currentQuestion.getYesLink()); count++; txtArea.append(" YES\n"+count+". "+currentQuestion.getQuestion()); } } else if (buttonPressed==noButton){ if (currentQuestion.getNoLink()<0){ //Make a new Question txtArea.append(" NO\nAfter "+count+" questions, I have no idea! What is it?"); getInfoDialog(currentQuestion.lastWord()); }else{ currentQuestion=questions.get(currentQuestion.getNoLink()); count++; txtArea.append(" NO\n"+count+". "+currentQuestion.getQuestion()); } } if (buttonPressed==restartButton) { txtArea.setText(""); startOver(); } } public void writeQuestionFile(){ //PrintWriter outFile; try { //outFile = new PrintWriter("questions.txt"); File f=new File("questions.txt"); BufferedWriter out = new BufferedWriter(new FileWriter(f,false)); for (int i=0; i(); try{ InputStream is=this.getClass().getResourceAsStream("questions.txt"); Scanner in = new Scanner(is); String line = null; while (in.hasNextLine()) { line = in.nextLine(); String[] part = line.split("\t"); int parent = Integer.parseInt(part[0]); int no = Integer.parseInt(part[1]); int yes = Integer.parseInt(part[2]); String quest = part[3]; questions.add(new Question(quest, parent, no, yes)); } in.close(); } catch(Exception e){ e.printStackTrace(); } } else {// questions.txt not found makeStarterQuestionFile(); } } public void makeStarterQuestionFile() { questions = new ArrayList(); questions.add(new Question( "Is it an animal?", -1, 1, 2) ); // 0 questions.add(new Question( "Is it a mineral?", 0, 3, 4) ); // 1 questions.add(new Question( "Is it poodle?", 0, -1, -1) ); // 2 questions.add(new Question( "Is it a vegitable?", 1, -1, 5) ); // 3 questions.add(new Question( "Is it a diamond?", 1, -1, -1) ); // 4 questions.add(new Question( "Is it a rose?", 3, -1, -1) ); // 5 writeQuestionFile(); } /** * CleanUpName cleans up user input so I can become part of the data base. * * @param thingName * @return the thing Name without a indefinite article, * lower case, and free of extra spaces in the beginning or end */ public String cleanUpName(String thingName) { thingName = thingName.toLowerCase(); // Remove the extra "a " if (thingName.substring(0,2).equals("a ")) thingName = thingName.substring(2); return thingName.trim(); } /** * CleanUpQuestion cleans up user input so it can * added to the data base. * @param qtn * @return The first Letter should be capitalized, and * adds a "?" only if it doesn't have one already */ public String cleanUpQuestion(String qtn) { //capitalize first Letter String quest = qtn.substring(0,1).toUpperCase()+ qtn.substring(1); // Make sure there is a "?" String lastLetter = quest.substring(quest.length()-1); if (!lastLetter.equals("?")) quest += "?"; return quest; } public void getInfoDialog(String lastThing){ JTextField thingTyped = new JTextField(); JLabel prompt = new JLabel("I give up! What is it?"); final JComponent[] newQ = new JComponent[] { prompt, thingTyped }; String dialogTitle = "New Object"; JOptionPane.showMessageDialog(this, newQ, dialogTitle, JOptionPane.PLAIN_MESSAGE); thingTyped.requestFocusInWindow(); String newThingName = cleanUpName( thingTyped.getText()); try{ txtArea.append(" A " + newThingName); getInfoDialog(lastThing, newThingName); }catch( Exception exception){ txtArea.append("\nI can't deal with this new object's name. Try again\n"); } } public void getInfoDialog(String lastThing, String thing){ JTextField textInput = new JTextField(); String prompt = "Type a yes/no question that would " + "distinguish between a " + lastThing + " and a " + thing; JLabel promptLable = new JLabel(prompt); final JComponent[] newQ = new JComponent[] { promptLable, textInput }; String title = "How is a "+thing+" different from a " +lastThing; JOptionPane.showMessageDialog(this, newQ, title, JOptionPane.PLAIN_MESSAGE); //textInput.requestFocus(); textInput.requestFocusInWindow(); try{ String quest = cleanUpQuestion(textInput.getText()); confirmDialog(thing, quest); }catch( Exception exception){ txtArea.append("\nI can't deal with this new question. Try again\n"); } } public void confirmDialog(String thing, String quest){ final JComponent[] newQ = new JComponent[] { new JLabel("And for a "+thing+", what is the answer to the question "), new JLabel("\""+quest+"\"") , new JLabel("(Press CANCEL if you are unsure)") }; int resp=JOptionPane.showConfirmDialog(this, newQ, "Tell me about It", JOptionPane.YES_NO_CANCEL_OPTION); try{ if (resp==JOptionPane.CANCEL_OPTION) { txtArea.append("\nDatabase unchanged\n"); return; } String newQuestAnswer="y"; if (resp==JOptionPane.YES_OPTION){ txtArea.append("\nAdding the question \""+quest+"\" \n(\"Yes\" for a "+thing+")\n"); } else if (resp==JOptionPane.NO_OPTION){ txtArea.append("\nAdding the question \""+quest+"\" \n(\"No\" for a "+thing+")\n"); newQuestAnswer="n"; } update( currentQuestion, thing, quest, newQuestAnswer); }catch( Exception exception){ txtArea.append("\nI can't deal with saving this new object. Try again\n"); } } private void update(Question currentQuestion, String thing, String newQuest, String newQuestAnswer) { int n = questions.size(); // New Question's index //Now have the previous question point to the question: Question currentQuestionRoot=questions.get(currentQuestion.getParentLink()); if (questions.indexOf(currentQuestion)==currentQuestionRoot.getYesLink()){ currentQuestionRoot.setYesLink(n); } else { currentQuestionRoot.setNoLink(n); } //Make an New Question Question q=new Question(); q.setQuestion(newQuest); q.setParentLink(currentQuestion.getParentLink()); //New Question is the parent of the thing it wasn't currentQuestion.setParentLink(n); newQuestAnswer=newQuestAnswer.toLowerCase(); if (newQuestAnswer.startsWith("y")){ q.setYesLink(n+1); q.setNoLink(questions.indexOf(currentQuestion)); } else { q.setYesLink(questions.indexOf(currentQuestion)); q.setNoLink(n+1); } Question t=new Question(); t.setParentLink(n); t.setNoLink(-1); t.setYesLink(-1); t.setQuestion("Is it a "+thing+"?"); questions.add(q); questions.add(t); writeQuestionFile(); } public static void main(String[] args) { TwentyQuestionsGameGUI app= new TwentyQuestionsGameGUI(); app.setVisible(true); } }