C SC 160 Project 4: Mastermind GUI

25 points
Due: anytime before the final exam (6 pm November 25)

For this capstone lab project, you will develop a GUI interface for the MMGame class you developed in the previous project. I will provide a working MMGame class for you to use. The GUI will provide game management and also display a history of guesses and responses. All user interaction will be through the mouse and all guesses and responses will use colors instead of digits. When you run the program, the GUI should look something like this:

As you can see from this figure, the GUI has four basic sections. They are, from top to bottom,

  1. Frame Title: This is the title bar area across the top. It is easily configured using JFrame methods and you have several examples both from handouts and the textbook.
  2. Menu Bar: The menu bar contains two menus. We did not cover menus in lecture but textbook section 14.7 contains everything you need to implement a menu bar. One correction to note: the Java statement in the middle of page 824, setMenuBar(menuBar); should be setJMenuBar(menuBar);
  3. Game History: This is a numbered list of previous moves and responses. It is configured using nested panels with the outermost panel placed into a scrolling pane. See JScrollPane on textbook page 786. The figure shows its initial configuration so each move is shown as a gray box with no response.
  4. Guess Input: This is the row of four boxes with the button beneath. The four boxes are actually buttons that have no text. Each time one is clicked on, its background color changes. This is how the user specifies the sequence of colors for guessing. I have initialized each to the default color white.

The next figures show a game in progress, just before the user presses "Make Guess" for the fourth guess, and the menu items. To see the real colors, view this document on the web rather than the printout.

How to play the game as shown in these figures

To play the game shown here,

Getting Started

Two Java files are needed to make the project work:
  1. MasterMind.java, which contains the main()method and implements the GUI. This is the class in which you will do all your programming. Skeletal solution provided.
  2. MMGame.class, the class that implements the Mastermind game evaluation. I have added another method public String getSolution() that you will need for implementing the "View Solution" menu item. I have also added another constructor described in the Saving and Opening In-Progress Games section below. Documentation and bytecode solution provided.
I've also provided the bytecode file Master.class containing a substantially complete solution. Run it using the provided MasterMain.java, to see how the application works.

All files are located in the Project4 folder that I've copied into your course repository myFiles folder.

Development Details

Principles you should follow for development

1. Start with the basic frame - No Points

  1. The basic frame is provided. Feel free to resize as needed later on.
  2. You should be able to compile and run MasterMind.java as provided.
  3. It will display a titled frame with grayed-out History pane.
  4. I gave the content pane a FlowLayout but you are free to use a different layout manager, or change it to null to use absolute positioning as is done in the textbook.
  5. The frame also has a Game menu with the Exit menu item implemented. Try it!
You're off and running!

2. Create additional menus and menu items - 3 Points

  1. Define all menu-related objects as local variables in the menuSetup() method.
  2. The menu bar, Game menu and Exit menu item are provided and fully operational.
  3. Add the additional menu and menu items as illustrated in the diagrams.
  4. The horizontal separators within a menu are created by the addSeparator() method, as shown in the textbook.

3. Define "stub" action listeners for menu items - 2 Points

An action listener is defined for "Exit". You can follow this pattern to create and add "stub" action listeners for the menu items you just created. A stub listener just prints an informative message.
  1. A stub action listener is one whose actionPerformed() method only prints a message containing the menu item name to System.out.
  2. Create a private inner class MenuItemStubListener that implements ActionListener, to handle events for remaining menu items.
  3. Inside its actionPerformed() method, call event.getActionCommand(), where e is the parameter, to retrieve a String containing the menu item text for the selected menu item. Then print this text in an appropriate message to System.out. Example message: Menu item Save is not implemented.
  4. Back in menuSetup(), create a MenuItemStubListener object and add it to each of the menu items. The same object can be added to all the menu items.
STOP! Test all the above to make sure it works before proceeding. Each each menu item should be connected to the action listener and display an appropriate message when selected.

4. GUI objects for obtaining user guess - 14 Points (allocated as indicated)

4.1 (2 Points) The guess input technique shown in the figure may be poor from a usability standpoint, but is straightforward to program. Here's what you need to do.
  1. Declare two instance variables:
  2. Define two action listener classes:
  3. Define a private method, private JPanel inputSetup(). This method will set up the JPanel containing the input buttons for entering a guess. Note: a stub version is provided.
STOP! Do not proceed until everything compiles correctly!

4.2 (4 Points) The next 6 steps describe code in the inputSetup() method.

  1. Note that I have declared and created a JPanel object called inputButtonPanel to hold all the buttons.
  2. Create the inputButtons array to have NUM_PEGS JButton elements. NUM_PEGS is provided and is currently set to 4.
  3. Compose a loop to create the NUM_PEGS JButton objects. In each iteration of this loop, a JButton object will be created and assigned to an element of the inputButtons array. The button will have no label. Add an InputButtonListener object to the button (all buttons can share the same listener object, so create it above the loop). Set its background to colors[DEFAULT_COLORS_INDEX]. The array colors is provided.
  4. Create and assign the "Make Guess" JButton. Add a MakeGuessListener to it.
  5. I used the JPanel default layout manager FlowLayout. You can make a very good argument for using absolute positioning in this JPanel. I will provide basic instructions here for both.
  6. Add all the buttons to inputButtonPanel.
STOP! Test all the above to make sure it works so far before proceeding! The input buttons should be white, and the two stub action listeners should respond with whatever messages you have programmed into them.

4.3 (3 Points) This is a good time to fill in the actionPerformed() for the InputButtonListener class. Here's what it needs to do:

  1. Get a reference to the button that was clicked. Use the event's getSource() to do this, like you did in the lab exercise. Note: you will need to use type-casting to assign the return value to a JButton variable.
  2. Get the button's background color using getBackground().
  3. Determine which index in the colors array contains this background color. I strongly recommend you write a private method that has one parameter to receive the background color, and returns the array index for that color. Its algorithm will require a small loop to find the match. This method will also be needed below.
  4. Change the button's background color, using setBackground(), to the next color in the array. Don't forget to wrap around when you get to array index NUM_COLORS! The '%' operator is good for this.
STOP! Test all the above to make sure it works so far before proceeding! Each of the input buttons should independently cycle through the array of colors. It should only cycle through the first NUM_COLORS elements of the array.

4.4 (5 Points) Finally, write the action listener for the "Make Guess" button. Take it in phases:

  1. Start by transforming the state of the input buttons into a suitable string for the MMGame's guess() method. Do that by composing a loop to traverse the inputButtons array. In each loop iteration:
  2. After completing the loop, you should have a string containing the guess in a format that the MMGame class understands. Now you can interact with MMGame and produce some test output. The provided code includes an MMGame object called game. Invoke its methods and print the return values to System.out, in particular getSolution(), guess(), numComplete(), numPartial(). Test everything thoroughly until you are convinced it works correctly.
  3. Add the logic and interaction for finishing a game. Call game.isGameOver() and if it returns true, then show a congratulatory JOptionPane.showMessageDialog() to the user! If game.isGameOver() returns false and game.getNumGuesses() returns MAX_GUESSES then show a conciliatory JOptionPane.showMessageDialog() to the user. In either of these situations, disable the "Make Guess" button using its setEnabled() method with argument false.
  4. Reset the input button colors to all white after each move is processed.
STOP! Test all the above to make sure it works properly before proceeding! This is a major milestone! Pat yourself on the back and get ready for more.

5. GUI objects for displaying response and game history - No Points

These are provided, so I will simply describe them here. At this point you have done some major GUI programming and this part does not introduce any new concepts other than 2-D arrays. As shown in the figures, I have programmed the GUI to display each guess in a numbered row, with the game's response to the right of the guess.

I defined a private JPanel historySetup() method that returns a JPanel containing all the rows. Back in the constructor, I called historySetup() then created a JScrollPane using the returned JPanel as its constructor argument. This is what gave you the ability to scroll through the history rather than display it entirely.

So there is a JPanel to contain the entire grid. Within this JPanel, I added a separate JPanel for each row. And within each row's JPanel, I added:

The easiest way to program this is to create all the JButtons and JLabels with a default background and foreground color and place them into a hierarchical structure of JPanels. Thus they are displayed all the time. When a guess is made and evaluated, all I have to do is change the colors of JButtons and JLabels in the appropriate row!

Each row number is simply a JLabel.

For the guess history, I chose to use disabled JButtons having the same size as the input buttons. This contributes to a simple and consistent look. They are initially drawn using a gray background then as each guess is registered the colors in the appropriate row are changed to match those of the input buttons.

For the response history, I chose to use JLabels. Each JLabel has the value "o". I then manipulate its visibility and meaning by setting the foreground color (e.g. the color used to render the text). To make it invisible at the start of a new game, I set its foreground color the same as its background color. To display a "complete" match, I set its foreground color to black. To display a "partial" match, I set its foreground color to white.

Again, the layout manager choice is yours. I used the default FlowLayout manager for all the JPanels, in conjunction with setPreferredSize() to make everything line up pretty.

Another issue is data structures. Since the guess JButtons and the response JLabels will have their colors manipulated by action listeners:

6. Moving a Guess into the History - 3 points

Program the "Make Guess" action listener to record each guess and the game's response into the history by manipulating the colors of the JButtons and JLabels in the appropriate row of the history and response arrays. These are described in Section 5 above, so read it now if you haven't yet done so. You'll know what row to use by retrieving the number of guesses from the provided MMGame object called game.

For each button in the selected row of history, set the background color to the background color of the corresponding guess input button. For labels in the selected row of response, set the foreground color to Color.black for each of game.numComplete() and set it to Color.white for each of game.numPartial(). In other words, if the number complete is 1 and number partial is 2, set one of them to black, two to white, and leave the fourth one alone.

7. Reset the History when Game Ends - 3 Points

Section 4.4 above, described what to do when a game is over (due to correct guess or out of guesses). In particular, the program is to display a message dialog. For this section, you are to extend your program to visually reset the history and response elements after the user responds from the message dialog. For all the history buttons, set their background color to Color.gray. For all the response labels, set their foreground color to be the same as their background color.

8. Minor menu items - Up to 5 Points Extra Credit

If you are ready for something not so taxing, implement a few menu item action listeners. The easy ones are:

The remaining menu items relate to file input and output.

9. Saving and Opening in-progress games -- Up To 10 Points Extra Credit

It should be possible to save an in-progress game to disk and later open it and continue playing. Swing provides a very convenient class called JFileChooser to facilitate filename specification for saving or opening files. There are good examples of its usage in textbook section 12.1.
Dialogs for selecting file names

Implement the "Open" menu option by creating a JFileChooser object, invoking its showOpenDialog() method then accessing the filename (if the action was not canceled) using its getSelectedFile() method.

Implement the "Save As" menu option similarly except use showSaveDialog() instead of showOpenDialog.

Implement the "Save" menu option by first checking to see if there is a "current" file name (a name under which it has already been "Open"-ed, or "Save As"-ed since the last New) -- use a String variable for this. If there is, use it. If not, treat this as a "Save As" as described above. This is good incentive to use the same action listener for both "Save" and "Save As".

Optional feature: If you have time, consider the following. For "New" and "Open", maintain and test a variable that indicates whether there is a current game that has not been saved since the last move. If there is, give the user an opportunity to save it before doing the New or Open.

Reading and writing game states
Once you have the filename, you need to open the file (create a File object) then perform the read or write operations to handle the "Open" or "Save" function. It will be sufficient to save the game state as all integers, so you can use the DataInputStream and DataOutputStream classes for input and output, respectively. There are good examples of their usage in textbook section 12.3.

Here are the values that need to be stored in the file. You may add to this list if necessary for your particular implementation.

  1. Number of positions that need to be guessed *
  2. Number of different colors that each may take *
  3. Maximum number of guesses permitted *
  4. The solution
  5. Number of guesses made so far
  6. The guess and response for each guess
* Include these even if the user is not able to change them via menu selection (this ability is not part of the assignment), in which case they can be discarded once read.

I suggest you store the guess as an integer (i.e. the index of the colors array) sequence.

Changes needed to MMGame class

The ability to open and resume a saved game means the GUI client has to have the ability to set both the solution and the number of guesses made so far, in the MMGame object. I have added another constructor to the MMGame class to permit this.

    public MMGame(int n, int k, String solution, int guesses)

You should use this to create a new game whenever the user elects to resume a saved game through the "Open" menu item.

To Turn In

When you are finished, email MasterMind.java as an attachment to me, psanderson@otterbein.edu


[ CSC 160 schedule | C SC 160 | Peter Sanderson | Math Sciences server  | Math Sciences home page | Otterbein ]

Last updated:
Peter Sanderson (PSanderson@otterbein.edu)