1. Create a quiz game that displays, in turn, five questions about any topic of your choice. All five questions should have the same three possible multiplechoice answers. For example, you might ask trivia questions about U.S. states for which the correct response is either California, Florida, or New York. After each question is displayed, allow the user to choose one, two, or all three answers by selecting JCheckBoxes. In other words, if the user is sure of an answer, he will select just one box, but if he is uncertain, he might select two or three boxes. When the user is ready to submit the answer(s), he clicks a button. If the user’s answer to the question is correct and he has selected just one box, award 5 points. If the user is correct but has selected two boxes, award 2 points. If the user has selected all three boxes, award 1 point. If the user has selected fewer than three boxes but is incorrect, the user receives 0 points. A total of 25 points is possible. If the user has accumulated more than 21 points at the end of the quiz, display the message Fantastic! If the user has accumulated more than 15 points, display the message Very good, and if the user has accumulated fewer points, display OK. Save the file as HedgeYourBet.java.

      import java.awt.*; import javax.swing.*; import java.awt.event.*; public class HedgeYourBet extends JFrame implements ItemListener, ActionListener { final int QUESTIONS = 5; final int CHOICES = 3; final int CA = 0; final int FL = 1; final int NY = 2; FlowLayout flow = new FlowLayout(); JLabel greeting = new JLabel("Quiz - choose 1, 2 or 3 answers"); Font serifBold = new Font("Serif", Font.BOLD, 20); JCheckBox[] choice = new JCheckBox[CHOICES]; JLabel[] label = new JLabel[CHOICES]; JTextArea outArea = new JTextArea(""); int x, y; String[] stateName = {"California", "Florida", "New York"}; String[] question = {" Which state has the oldest cattle ranch in the U.S?", " Which state has a bear on its flag?", " What state's state bird is the mockingbird?", " Which state's flower is the golden poppy?", "Which state has the highest number of \nlightning strikes per capita?"}; int[] answers = {NY, CA, FL, CA, FL}; int questionNum = 0; int numChosen; JButton doneButton = new JButton("OK"); boolean[] isChosen = new boolean[CHOICES]; int points = 0; final int HIGHPOINTS = 5; final int MEDPOINTS = 2; final int LOWPOINTS = 1; String msg = new String(""); final int HIGHMARK = 21; final int MEDMARK = 15; public HedgeYourBet() { super("Hedge Your Best"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(flow); add(greeting); greeting.setFont(serifBold); outArea.setText(question[questionNum]); add(outArea); for(x = 0; x < CHOICES; ++x) { choice[x] = new JCheckBox(); label[x] = new JLabel(" " + stateName[x]); add(label[x]); add(choice[x]); choice[x].addItemListener(this); } doneButton.addActionListener(this); add(doneButton); } public static void main(String[] arguments) { HedgeYourBet hFrame = new HedgeYourBet(); hFrame.setSize(300,300); hFrame.setVisible(true); } @Override public void itemStateChanged(ItemEvent check) { Object source = check.getItem(); for(x= 0; x < CHOICES; ++x) { if(source == choice[x]) { int select = check.getStateChange(); if(select == ItemEvent.SELECTED) isChosen[x] = true; else isChosen[x] = false; } } } @Override public void actionPerformed(ActionEvent e) { //Object source = e.getSource(); numChosen = 0; for(x = 0; x < CHOICES; ++x) if(isChosen[x]) ++numChosen; if(isChosen[answers[questionNum]]) { if(numChosen == 1) points += HIGHPOINTS; else if(numChosen == 2) points += MEDPOINTS; else if(numChosen == 3) points += LOWPOINTS; } outArea.setText("\nTotal points earned: " + points); ++questionNum; if(questionNum == QUESTIONS) { outArea.append("\nGame over\n"); doneButton.setEnabled(false); if(points > HIGHMARK) msg = "Fantastic!"; else if(points > MEDMARK) msg = "Very good"; else msg = "OK"; outArea.append(msg); } else outArea.append("\n" + question[questionNum]); } }
    2. Modify the HedgeYourBet game so that it stores the player’s score from the last game in a file and displays the previous score at the start of each new game. (The first time you play the game, the previous score should be 0.) Save the game as HedgeYourBetUsingFile.java.

      import java.io.*; import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.nio.file.*; import static java.nio.file.StandardOpenOption.*; public class HedgeYourBetUsingFile extends JFrame implements ItemListener, ActionListener { Path file = Paths.get("C:\\Java\\Chapter.14\\Scores.txt"); InputStream input = null; String s; final int QUESTIONS = 5; final int CHOICES = 3; final int CA = 0; final int FL = 1; final int NY = 2; FlowLayout flow = new FlowLayout(); JLabel greeting = new JLabel("Quiz - choose 1, 2 or 3 answers"); Font serifBold = new Font("Serif", Font.BOLD, 20); JCheckBox[] choice = new JCheckBox[CHOICES]; JLabel[] label = new JLabel[CHOICES]; JTextArea outArea = new JTextArea(""); int x, y; String[] stateName = {"California", "Florida", "New York"}; String[] question = {" Which state has the oldest cattle ranch in the U.S?", " Which state has a bear on its flag?", " What state's state bird is the mockingbird?", " Which state's flower is the golden poppy?", "Which state has the highest number of \nlightning strikes per capita?"}; int[] answers = {NY, CA, FL, CA, FL}; int questionNum = 0; int numChosen; int prevScore = 0; JLabel scoreLabel = new JLabel(""); JButton doneButton = new JButton("OK"); boolean[] isChosen = new boolean[CHOICES]; int points = 0; final int HIGHPOINTS = 5; final int MEDPOINTS = 2; final int LOWPOINTS = 1; String msg = new String(""); final int HIGHMARK = 21; final int MEDMARK = 15; DataOutputStream ostream; DataInputStream istream; File scoreFile = new File("Scores.txt"); public HedgeYourBetUsingFile() { super("Hedge Your Best"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel pane = new JPanel(); pane.setLayout(flow); pane.add(greeting); greeting.setFont(serifBold); pane.add(scoreLabel); outArea.setText(question[questionNum]); pane.add(outArea); for(x = 0; x < CHOICES; ++x) { choice[x] = new JCheckBox(); label[x] = new JLabel(" " + stateName[x]); pane.add(label[x]); pane.add(choice[x]); choice[x].addItemListener(this); } setContentPane(pane); doneButton.addActionListener(this); pane.add(doneButton); try { input = Files.newInputStream(file); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); s = reader.readLine(); prevScore = Integer.parseInt(s); input.close(); } catch (IOException e) { System.out.println(e); } scoreLabel.setText("score on previous game was " + prevScore); } public static void main(String[] args) { HedgeYourBetUsingFile hFrame = new HedgeYourBetUsingFile(); hFrame.setSize(340,300); hFrame.setVisible(true); } @Override public void itemStateChanged(ItemEvent check) { Object source = check.getItem(); for(x= 0; x < CHOICES; ++x) { if(source == choice[x]) { int select = check.getStateChange(); if(select == ItemEvent.SELECTED) isChosen[x] = true; else isChosen[x] = false; } } } @Override public void actionPerformed(ActionEvent e) { //Object source = e.getSource(); numChosen = 0; for(x = 0; x < CHOICES; ++x) if(isChosen[x]) ++numChosen; if(isChosen[answers[questionNum]]) { if(numChosen == 1) points += HIGHPOINTS; else if(numChosen == 2) points += MEDPOINTS; else if(numChosen == 3) points += LOWPOINTS; } outArea.setText("\nPoints earned " + points); ++questionNum; if(questionNum == QUESTIONS) { outArea.append("\nGame over\n"); doneButton.setEnabled(false); if(points > HIGHMARK) msg = "Fantastic!"; else if(points > MEDMARK) msg = "Very good"; else msg = "OK"; outArea.append(msg); if(points > prevScore) s = "" + points; else s = "" + points; byte data[] = s.getBytes(); OutputStream output = null; try { output = new BufferedOutputStream(Files.newOutputStream(file, WRITE, TRUNCATE_EXISTING)); output.write(data); output.flush(); output.close(); } catch(Exception ex) { System.out.println("Message: " + ex); } } else outArea.append("\n" + question[questionNum]); } }
  1. In Chapter 5, you created a lottery game application. Create a similar game using check boxes. For this game, generate six random numbers, each between 0 and 30 inclusive. Allow the user to choose six check boxes to play the game. (Do not allow the user to choose more than six boxes.) After the player has chosen six numbers, display the randomly selected numbers, the player’s numbers, and the amount of money the user has won, as follows: Matching Numbers Award ($) Three matches 100 Four matches 10,000 Five matches 50,000 Six matches 1,000,000 Zero, one, or two matches 0 Save the file as JLottery2.java.
    import java.awt.*; import javax.swing.*; import java.awt.event.*; public class JLottery2 extends JFrame implements ItemListener { final int NUM = 31; final int PICKS = 6; FlowLayout flow = new FlowLayout(); JLabel greeting = new JLabel ("Play the lottery - Select " + PICKS + " numbers"); Font serifBold = new Font("Serif", Font.BOLD, 20); JCheckBox[] choice = new JCheckBox[NUM]; JLabel[] label = new JLabel[NUM]; String winningsString = "The winning numbers are: "; String youPickedString = "You chose: "; JTextArea outArea = new JTextArea(""); int x, y; int[] ran = new int[PICKS]; int[] chosen = new int[PICKS]; int chosenCount = 0; int matches = 0; int[] winDollars = {0, 0, 0, 100, 10000, 50000, 1000000}; public JLottery2() { super("Lottery Game"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(flow); add(greeting); greeting.setFont(serifBold); for(x = 0; x < NUM; ++x) { choice[x] = new JCheckBox(); label[x] = new JLabel(" " + x); add(label[x]); add(choice[x]); choice[x].addItemListener(this); } add(outArea); for(x = 0; x < PICKS; ++x) { ran[x] = (int)Math.floor(Math.random()*NUM); for(y = 0; y < x; ++y) if(ran[x] == ran[y]) --x; } for(x = 0; x < PICKS; ++x) { winningsString += ran[x] + " "; } // System.out.println(winningsString); // Useful while testing } public static void main(String[] arguments) { JLottery2 lotFrame = new JLottery2(); lotFrame.setSize(380,300); lotFrame.setVisible(true); } @Override public void itemStateChanged(ItemEvent check) { Object source = check.getItem(); if(chosenCount == PICKS) { for(x= 0; x < NUM; ++x) { if(source == choice[x]) choice[x].setSelected(false); } } else { for(x= 0; x < NUM; ++x) { if(source == choice[x]) { int select = check.getStateChange(); if(select == ItemEvent.SELECTED) { chosen[chosenCount] = x; youPickedString += x + " "; ++chosenCount; } } } if(chosenCount == PICKS) { for(x = 0; x < PICKS; ++x) for(y = 0; y < PICKS; ++y) if(chosen[x] == ran[y]) ++matches; outArea.append(winningsString); outArea.append("\n"); outArea.append(youPickedString); outArea.append("\nYou matched " + matches + " numbers"); outArea.append("\nYou win $" + winDollars[matches]); } } } }
    1. Create a game called Last Man Standing in which the objective is to select the last remaining JCheckBox. The game contains 10 JCheckBoxes. The player can choose one, two, or three boxes, and then click a JButton to indicate the turn is complete. The computer then randomly selects one, two, or three JCheckBox objects. When the last JCheckBox is selected, display a message indicating the winner. Save the game as LastManStanding.java.

      import java.awt.*; import javax.swing.*; import java.awt.event.*; public class LastManStanding extends JFrame implements ItemListener, ActionListener { final int BOXES = 10; final int MAXCHOICES = 3; FlowLayout flow = new FlowLayout(); JLabel greeting = new JLabel("Select 1, 2 or 3 boxes"); Font serifBold = new Font("Serif", Font.BOLD, 20); JCheckBox[] box = new JCheckBox[BOXES]; JButton button = new JButton("Done"); boolean[] isChosen = new boolean[BOXES]; boolean computersTurn = false; boolean allDone = false; int x, y; int ran; int numChosen; public LastManStanding() { super("LastManStanding"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(flow); add(greeting); greeting.setFont(serifBold); for(x = 0; x < BOXES; ++x) { box[x] = new JCheckBox(); add(box[x]); box[x].addItemListener(this); } add(button); button.addActionListener(this); } public static void main(String[] arguments) { LastManStanding frame = new LastManStanding(); frame.setSize(300,120); frame.setVisible(true); } @Override public void itemStateChanged(ItemEvent check) { if(!computersTurn) { Object source = check.getItem(); for(x= 0; x < BOXES; ++x) { if(source == box[x]) { box[x].setSelected(true); if(numChosen < MAXCHOICES) { isChosen[x] = true; ++numChosen; } else box[x].setSelected(false); x = BOXES; } } } } @Override public void actionPerformed(ActionEvent e) { if(allDone()) { String winner = "You win"; finishUp(winner); } else { computersTurn = true; ran = ((int)(Math.random() * 100) % MAXCHOICES); for(x = 0; x <= ran; ++x) { for(y = 0; y < BOXES; ++y) { if(!isChosen[y]) { isChosen[y] = true; box[y].setSelected(true); y = BOXES; } } } computersTurn = false; if(allDone()) { String winner = "Computer wins"; finishUp(winner); } numChosen = 0; } } public boolean allDone() { boolean isDone = true; for(x = 0; x < BOXES; ++x) { if(!isChosen[x]) isDone = false; } return isDone; } public void finishUp(String winner) { button.setEnabled(false); for(x = 0; x < BOXES; ++x) remove(box[x]); JLabel done = new JLabel("Game over - " + winner); add(done); validate(); repaint(); } }
    2. In the current version of the Last Man Standing game, the computer might seem to make strategic mistakes because of its random selections. For example, when only two JCheckBox objects are left, the computer might randomly choose to check only one, allowing the player to check the last one and win. Modify the game to make it as smart as possible, using a random value for the number of the computer’s selections only when there is no superior alternative. Save the improved game as SmarterLastManStanding.java.

      import java.awt.*; import javax.swing.*; import java.awt.event.*; public class SmarterLastManStanding extends JFrame implements ItemListener, ActionListener { final int BOXES = 10; final int MAXCHOICES = 3; FlowLayout flow = new FlowLayout(); JLabel greeting = new JLabel("Select 1, 2 or 3 boxes"); Font serifBold = new Font("Serif", Font.BOLD, 20); JCheckBox[] box = new JCheckBox[BOXES]; JButton button = new JButton("Done"); boolean[] isChosen = new boolean[BOXES]; boolean computersTurn = false; boolean allDone = false; int x, y; int ran; int numChosen; public SmarterLastManStanding() { super("LastManStanding"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(flow); add(greeting); greeting.setFont(serifBold); for(x = 0; x < BOXES; ++x) { box[x] = new JCheckBox(); add(box[x]); box[x].addItemListener(this); } add(button); button.addActionListener(this); } public static void main(String[] arguments) { SmarterLastManStanding frame = new SmarterLastManStanding(); frame.setSize(300,120); frame.setVisible(true); } @Override public void itemStateChanged(ItemEvent check) { if(!computersTurn) { Object source = check.getItem(); for(x = 0; x < BOXES; ++x) { if(source == box[x]) { box[x].setSelected(true); if(numChosen < MAXCHOICES) { isChosen[x] = true; ++numChosen; } else box[x].setSelected(false); x = BOXES; } } } } @Override public void actionPerformed(ActionEvent e) { if(allDone()) { String winner = "You win"; finishUp(winner); } else { computersTurn = true; int boxesRemaining = howManyFreeBoxes(); boxesRemaining = boxesRemaining % 4; if(boxesRemaining == 1) ran = 0; else if(boxesRemaining == 2) ran = 1; else if(boxesRemaining == 3) ran = 2; else ran = ((int)(Math.random() * 100) % MAXCHOICES); for(x = 0; x <= ran; ++x) { for(y = 0; y < BOXES; ++y) { if(!isChosen[y]) { isChosen[y] = true; box[y].setSelected(true); y = BOXES; } } } computersTurn = false; if(allDone()) { String winner = "Computer wins"; finishUp(winner); } numChosen = 0; } } public boolean allDone() { boolean isDone = true; for(x = 0; x < BOXES; ++x) { if(!isChosen[x]) isDone = false; } return isDone; } public void finishUp(String winner) { button.setEnabled(false); for(x = 0; x < BOXES; ++x) remove(box[x]); JLabel done = new JLabel("Game over - " + winner); add(done); validate(); repaint(); } public int howManyFreeBoxes() { int count = 0; for(x = 0; x < BOXES; ++x) if(!isChosen[x]) ++count; return count; } }