Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Assignment Scope For this assignment students will finalize developing the front end, or User Interface, portion of the MasterMind game. Based on my professional experience

Assignment Scope

For this assignment students will finalize developing the front end, or User Interface, portion of the MasterMind game. Based on my professional experience working in the industry I have always had to develop a UI for every application, therefore I translate that experience to students so they can have the same opportunity and be prepared professionally.

Typically, there is a one-to-one correlation of back end functionality to front end UI component. Depending upon the design of the application it doesnt always correlate perfectly, however with MasterMind, it works well.

Back-end functionality

Front-end UI component

Codemaker.java

CodemakerUi.java

Codebreaker.java

CodebreakerUi.java

Game.java

MasterMindUi.java

The goal is to develop the front-end components of the game MasterMind by creating classes:

CodebreakerUi.java

CodemakerUi.java

MasterMindUi.java

Students will modify existing source code to add more functionality.

The UI will be developed in multiple assignments, it is not expected that for Assignment 6 the fully functioning UI is complete.

The image that follows is a prototype of what the UI will look like. It does not have to be an exact match. The rubric will provide guidance and recommendations on how to accomplish this, however feel free to be creative in developing the look and feel of the UI.

To accomplish this:

Reference the tasks below for the specifics of the source code requirements.

Compress a project and submit to Webcourses

Decompress compressed project and verify it is a Netbeans project

References

Netbeans.docx

Setting up a project in Netbeans.docx

Netbeans right click menu help.docx

Deliverables

To complete this assignment you must submit your compressed Netbeans project to Webcourses.

Please keep in mind that the tasks are guidance to accomplish the goals of the assignment. At times students will be required to do additional research (e.g. Google That S**T (GTS)!) to find implementation options. In the industry, software engineers are expected to be very self-sufficient to find the best solution for the task at hand.

I have provided multiple code examples on Webcourses that shows how to implement numerous of the tasks below, please reference those code examples prior to asking me for help.

Tasks and Rubric

Activity

mastermind package

core package

Codebreaker.java

Write public method removeAll() that removes all elements of the member variable codebreakerAttempt of class ArrayList

Update method getCodebreakerAttempt() to comment out the call to method consoleAttempt()

userInterface package

CodebreakerUi.java

Add member variables of type:

Color colorSelected;

Updated method initComponents() where it is instantiating the RoundButtons for the 2D array; it should add the following

Add client property row to each RoundButton set to the current iteration of the outer loop

Write an inner class to create an ActionListener that is registered to each of the colored buttons on the Codebreakers JPanel that displays the eight available colors; it should

Explicitly type cast the ActionEvent object to an instance of RoundButton; all method getSource() on the ActionEvent object

Set member variable colorSelected to the color stored in the client property color of the clicked RoundButton instance; it will need to be explicitly type cast to class Color

Write an inner class to create an ActionListener that is registered to each of the RoundButtons in the 2D array on the Codebreakers JPanel that displays the codebreakers attempt; it should

Explicitly type cast the ActionEvent object to an instance of RoundButton

Check if the member variable codebreakerAttempt in class Codebreaker already contains the selected color; if false

Set the background color of the RoundButton instance to the value stored in member variable colorSelected

Add to member variable codebreakerAttempt in class Codebreakers the value stored in member variable colorSelected

Check if the size of member variable codebreakerAttempt in class Codebreaker is equal to the maximum number of pegs (i.e. 4); if true

Create a variable of type int set equal to the client property row of the clicked RoundButton instance; it will need to be explicitly type cast to primitive data type int

Call method enableDisableButtons() passing the int variable from step i. above as an argument

Write public method clearBoard() to reset the background color and the Codebreakers member variable codebreakerAttempt; it shouldLoop through the 2D array of RoundButton instances

Set the background color to null

Enable only the bottom row of RoundButton

Remove all elements in the codebreakerAttempt in class Codebreaker by calling method removeAll()

Write private method enableDisableButtons() to disable the last row of the codebreakers attempt and enable the next row of the codebreakers attempt; it should

Have a return type of void

Receive one parameter of type int representing the current row

Loop through the passed in row value, for each column

Disable the current row and associated columns

If the current row isnt zero (0), then enable the next row and associated columns

Remove all elements in the codebreakerAttempt in class Codebreaker by calling method removeAll()

MastermindUi.java

Write an inner class to create an ActionListener that is registered to the JMenuItem with the text New Game; it should

Call method clearBoard() in class CodebreakerUi

Mastermind application

Test Case 1

Test Case 1 passes

Test Case 2

Test Case 2 passes

Test Case 3

Test Case 3 passes

Test Case 4

Test Case 4 passes

Test Case 5

Test Case 5 passes

Source compiles with no errors

Source runs with no errors

Source includes comments

Total

Perform the following test cases

Test Cases

Action

Expected outcome

Test Case 1

Selected color populates selected button in bottom row

Button should change color, similar to figure 1

Test Case 2

Cannot add the same color

Button should not change color

Test Case 3

All four buttons in previous row are populated with selected colors and disabled

Similar to figure 2 and 3

Test Case 4

Next row is enabled and can be populated with color selections

Similar to figure 4

Test Case 5

Menu option New Game is selected, the board clears, bottom row is enabled

Similar to figure 5

image text in transcribed

Figure 1 Test Case 1

image text in transcribed

Figure 2 Test Case 2/3

image text in transcribed

Figure 3 Previous row is disabled, next row is enabled

image text in transcribed

Figure 4 Test Case 4

image text in transcribed

Figure 5 Test Case 5

Code so far

Constants.java

/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */

package constants;

import java.awt.Color; import java.util.ArrayList; import java.util.Arrays; /** * * @author bryan tavarez */ public class Constants { // peg color options public static final ArrayList codeColors = new ArrayList(Arrays.asList(Color.BLUE, Color.BLACK, Color.ORANGE, Color.WHITE, Color.YELLOW, Color.RED, Color.GREEN, Color.PINK)); // response color options public static final ArrayList responseColors = new ArrayList(Arrays.asList(Color.RED, Color.WHITE)); public static final int MAX_ATTEMPTS = 10; public static final int MAX_PEGS = 4; public static final int COLORS = 8;

}

IGame.java

/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package core;

/** * * @author Bryan tavarez */ public interface IGame { public void play(); }

ICodebreaker.java

/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package core;

import java.awt.Color; import java.util.ArrayList; /** * * @author bryan tavarez */ public interface ICodebreaker { public void checkCode(ArrayList attempt); }

ICodemaker.java

/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package core;

import java.awt.Color; import java.util.ArrayList;

public interface ICodemaker{ public void generateSecretCode(); public void checkAttemptedCode(ArrayList codebreakerAttempt); }

Game.Java

//bryan tavarez

package core;

import java.awt.Color; import java.util.ArrayList; import constants.Constants;

public final class Game implements IGame {

private int attempt; private Codebreaker codebreaker; private Codemaker codemaker;

public Game() { // instantiate the instances of the member variables codemaker = new Codemaker(); codebreaker = new Codebreaker() { @Override public void checkCode(ArrayList attempt) { throw new UnsupportedOperationException("Not supported yet."); // To } };

attempt = 0; // play(); }

public void play() { while (true) { // will loop again and again until codebreaker wins or // runs out of attempts if (attempt codeBreakerAttempt = codebreaker.getCodebreakerAttempt(); codemaker.checkAttemptedCode(codeBreakerAttempt); boolean win = codebreaker.CheckCode(codemaker.getCodemakerResponse()); /* * checkCode function of * ICodebreaker has been * modified,will return true * if codebreaker wins

*/

if (win) { System.out.println("Codebreaker wins"); break; // breaking the loop } } else { System.out.println("Codemaker wins"); // after max attempts and

// codebreaker couldn't // guess correctly attempt++; break; } } } //end play method

/** * @return the attempt */ public int getAttempt() { return attempt; }

/** * @param attempt the attempt to set */ public void setAttempt(int attempt) { this.attempt = attempt; }

/** * @return the codebreaker */ public Codebreaker getCodebreaker() { return codebreaker; }

/** * @param codebreaker the codebreaker to set */ public void setCodebreaker(Codebreaker codebreaker) { this.codebreaker = codebreaker; }

/** * @return the codemaker */ public Codemaker getCodemaker() { return codemaker; }

/** * @param codemaker the codemaker to set */ public void setCodemaker(Codemaker codemaker) { this.codemaker = codemaker; }

public void checkIfWon() {

}

}

Mastermind.java

/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ //bryan tavarez //Mastermind.java

package mastermind;

import core.Game; import userinterface.MasterMindUi; import javax.swing.JOptionPane;

public class MasterMind {

public static void main(String[] args) { // System.out.println("Welcome to MasterMind!"); JOptionPane.showMessageDialog(null, "Let's Play MasterMind!"); Game game = new Game(); MasterMindUi ui = new MasterMindUi(game); }

}

RoundedButton.Java

package userinterface;

import java.awt.Dimension; import java.awt.geom.Ellipse2D;

public class RoundButton extends RoundedCornerButton { protected RoundButton() { super(); } @Override public Dimension getPreferredSize() { Dimension d = super.getPreferredSize(); int s = Math.max(d.width, d.height); d.setSize(s, s); return d; } @Override protected void initShape() { if (!getBounds().equals(base)) { base = getBounds(); shape = new Ellipse2D.Double(0, 0, getWidth() - 1, getHeight() - 1); border = new Ellipse2D.Double(FOCUS_STROKE, FOCUS_STROKE, getWidth() - 1 - FOCUS_STROKE * 2, getHeight() - 1 - FOCUS_STROKE * 2); } } }

RoundedCornerButton.java

package userinterface;

import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.geom.RoundRectangle2D; import javax.swing.JButton;

public class RoundedCornerButton extends JButton { private static final double ARC_WIDTH = 16d; private static final double ARC_HEIGHT = 16d; protected static final int FOCUS_STROKE = 2; protected final Color fc = new Color(100, 150, 255, 200); protected final Color ac = new Color(230, 230, 230); protected final Color rc = Color.ORANGE; protected Shape shape; protected Shape border; protected Shape base; protected RoundedCornerButton() { super(); } @Override public void updateUI() { super.updateUI(); setContentAreaFilled(false); setFocusPainted(false); setBackground(new Color(250, 250, 250)); initShape(); } protected void initShape() { if (!getBounds().equals(base)) { base = getBounds(); shape = new RoundRectangle2D.Double(0, 0, getWidth() - 1, getHeight() - 1, ARC_WIDTH, ARC_HEIGHT); border = new RoundRectangle2D.Double(FOCUS_STROKE, FOCUS_STROKE, getWidth() - 1 - FOCUS_STROKE * 2, getHeight() - 1 - FOCUS_STROKE * 2, ARC_WIDTH, ARC_HEIGHT); } } private void paintFocusAndRollover(Graphics2D g2, Color color) { g2.setPaint(new GradientPaint(0, 0, color, getWidth() - 1, getHeight() - 1, color.brighter(), true)); g2.fill(shape); g2.setPaint(getBackground()); g2.fill(border); } @Override protected void paintComponent(Graphics g) { initShape(); Graphics2D g2 = (Graphics2D) g.create(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if (getModel().isArmed()) { g2.setPaint(ac); g2.fill(shape); } else if (isRolloverEnabled() && getModel().isRollover()) { paintFocusAndRollover(g2, rc); } else if (hasFocus()) { paintFocusAndRollover(g2, fc); } else { g2.setPaint(getBackground()); g2.fill(shape); } g2.dispose(); // super.paintComponent(g); } @Override protected void paintBorder(Graphics g) { initShape(); Graphics2D g2 = (Graphics2D) g.create(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setPaint(getForeground()); g2.draw(shape); g2.dispose(); } @Override public boolean contains(int x, int y) { initShape(); return shape != null && shape.contains(x, y); } }

Codebreaker.java

package userinterface;

import constants.Constants;

import core.Codebreaker;

import java.awt.Color;

import java.awt.Dimension;

import java.awt.GridLayout;

import java.util.ArrayList;

import javax.swing.BorderFactory;

import javax.swing.JPanel;

/**

*

* @author kwhiting

*/

public class CodebreakerUi {

private JPanel codebreakerAttempt;

private JPanel codebreakerColors;

private RoundButton[] buttons;

private RoundButton[][] attempts;

private Codebreaker codebreaker;

public CodebreakerUi(Codebreaker codebreaker) {

this.codebreaker = codebreaker;

initComponents();

}

private void initComponents() {

initCodebreakerColors();

initCodebreakerAttempt();

}

private void initCodebreakerColors() {

codebreakerColors = new JPanel();

codebreakerColors.setBorder(BorderFactory.createTitledBorder("Codebreaker Colors"));

codebreakerColors.setMinimumSize(new Dimension(200, 65));

codebreakerColors.setPreferredSize(new Dimension(200,65));

// instantiate the Array with the size

buttons = new RoundButton[Constants.COLORS];

// counter for enhanced for loop

int counter = 0;

// put client properties on the buttons so we

// know which one it is

for (RoundButton button : buttons) {

// create the buttons

button = new RoundButton();

Color color = Constants.codeColors.get(counter);

button.setBackground(color);

button.putClientProperty("color", color);

// set the tooltip

if(color == Color.BLUE)

button.setToolTipText("BLUE");

else if(color == Color.BLACK)

button.setToolTipText("BLACK");

else if(color == Color.GREEN)

button.setToolTipText("GREEN");

else if(color == Color.ORANGE)

button.setToolTipText("ORANGE");

else if(color == Color.PINK)

button.setToolTipText("PINK");

else if(color == Color.RED)

button.setToolTipText("RED");

else if(color == Color.YELLOW)

button.setToolTipText("YELLOW");

else if(color == Color.WHITE)

button.setToolTipText("WHITE");

// add an ActionListener

// add button to JPanel using FlowLayout

codebreakerColors.add(button);

// increment the counter

counter++;

}

}

private void initCodebreakerAttempt() {

codebreakerAttempt = new JPanel();

codebreakerAttempt.setBorder(BorderFactory.createTitledBorder("Codebreaker Attempt"));

codebreakerAttempt.setMinimumSize(new Dimension(375, 250));

codebreakerAttempt.setPreferredSize(new Dimension(375, 250));

// set the layout manager to use GridLayout

codebreakerAttempt.setLayout(new GridLayout(Constants.MAX_ATTEMPTS, Constants.MAX_PEGS));

// instantiate the Array with the size

attempts = new RoundButton[Constants.MAX_ATTEMPTS][Constants.MAX_PEGS];

// create the array of JButtons for the code breaker's attempts

for (int row = 0; row

for(int col = 0; col

// create the buttons

attempts[row][col] = new RoundButton();

// if it isn't the first row then disable the button

if(row != (Constants.MAX_ATTEMPTS - 1))

attempts[row][col].setEnabled(false);

// add the button to the UI

codebreakerAttempt.add(attempts[row][col]);

}

}

}

/**

* @return the codebreakerAttempt

*/

public JPanel getCodebreakerAttempt() {

return codebreakerAttempt;

}

/**

* @return the codebreakerColors

*/

public JPanel getCodebreakerColors() {

return codebreakerColors;

}

}

MastermindUI.java

//bryan tavarez

package userinterface; import core.Game; import constants.Constants; import java.awt.BorderLayout; import java.awt.Desktop; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane;

public class MasterMindUi extends JFrame {

// Instance variables private JButton RoundedButton; private Game game; private CodebreakerUi codebreakerUi; private CodemakerUi codemakerUi; private JFrame myframe; private JMenuBar menuBar; private JMenu gameMenu; private JMenu helpMenu; private JMenuItem newGameMenuItem; private JMenuItem exitMenuItem; private JMenuItem aboutMenuItem; private JMenuItem rulesMenuItem;

/** * Constructor * * @param game Game object */ public MasterMindUi(Game game) { this.game = game; // Instantiate CodemakerUI this.codemakerUi = new CodemakerUi(game.getCodemaker()); // Instantiate CodebreakerUI this.codebreakerUi = new CodebreakerUi(game.getCodebreaker()); initComponents(); }

/** * Initializes the UI components */ private void initComponents() { myframe = new JFrame("Mastermind"); JButton checkButton = new JButton (); checkButton.setText("Check"); checkButton.setSize(75,30); // Set the default size of the JFrame myframe.setSize(600, 500);

// Set the default close operation of the JFrame myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Use default layout manager BorderLayout myframe.setLayout(new BorderLayout(10, 0));

// Center frame to the screen myframe.setLocationRelativeTo(null);

// Set up the JMenuBar menuBar = new JMenuBar();

// Add JMenu Game to the JMenuBar gameMenu = new JMenu("Game");

menuBar.add(gameMenu);

// Add JMenuItems New Game and Exit the JMenu Game newGameMenuItem = new JMenuItem("New Game"); gameMenu.add(newGameMenuItem); exitMenuItem = new JMenuItem("Exit"); gameMenu.add(exitMenuItem);

// Add JMenu Help to the JMenuBar helpMenu = new JMenu("Help"); menuBar.add(helpMenu);

// Add JMenuItems About and Game Rules to the JMenu Help aboutMenuItem = new JMenuItem("About"); helpMenu.add(aboutMenuItem); rulesMenuItem = new JMenuItem("Game Rules"); helpMenu.add(rulesMenuItem);

// Add JMenuBar to the JFrame myframe.setJMenuBar(menuBar);

// Add the CodemakerUi JPanels to the JFrame using the getters defined myframe.add(this.codemakerUi.getSecretCode(), BorderLayout.NORTH); myframe.add(this.codemakerUi.getCodemakerResponse(), BorderLayout.EAST);

// Add the CodebreakerUi JPanels to the JFrame using the getters defined myframe.add(this.codebreakerUi.getCodebreakerAttempt(), BorderLayout.WEST); myframe.add(this.codebreakerUi.getCodebreakerColors(), BorderLayout.SOUTH);

// Add action listener to exit menu item exitMenuItem.addActionListener(new ExitActionListener());

// Add action listener to about menu item aboutMenuItem.addActionListener(new AboutActionListener());

// Add action listener to game rules menu item rulesMenuItem.addActionListener(new RulesActionListener());

// Set the visibility of the JFrame myframe.setVisible(true); }

// Inner class to create an ActionListener for Exit menu item class ExitActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent ae) { // Display a JOptionPane message confirming the user wants to exit // using method showConfirmDialog() int ans = JOptionPane.showConfirmDialog(null, "Confirm to exit Mastermind?", "Exit?", JOptionPane.YES_NO_OPTION); // If yes, exit the application by calling method System.exit() // passing the value of 0 as an argument // If no, do not exit the application if (ans == 0) System.exit(0); } } // Inner class to create an ActionListener for About menu item class AboutActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent ae) { // Display a JOptionPane message informing the user: // Application name and version // Author // Date of development JOptionPane.showMessageDialog(null, "Mastermind version 1.0 Karin Whiting Fall 2018"); } }

// Inner class to create an ActionListener for Game rules menu item class RulesActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent ae) { String rules = "Step 1: The codemaker selects a four color secret code, in any order, no duplicate colors. " + "Step 2: The codemaker places a guess in the bottom row, no duplicate colors. " + "Step 3: The codemaker gives feedback next to each guess row with four pegs " + "~Each red peg means that one of the guessed colors is correct, and is in the right location. " + "~Each white peg means that one of the guessed colors is correct, but is in the wrong location. " + "Step 4: Repeat with the next row, unless the secret code was guessed on the first turn " + "Step 5: Continue until the secret code is guessed or there are no more guesses left, there are 10 attempts"; // Display a JOptionPane message informing the user about the rules // of the game JOptionPane.showMessageDialog(null, rules); } } }

CodemakerUi.java

package userinterface;

import constants.Constants;

import core.Codemaker;

import java.awt.Color;

import java.awt.Dimension;

import java.awt.GridLayout;

import java.awt.Image;

import javax.swing.BorderFactory;

import javax.swing.ImageIcon;

import javax.swing.JButton;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.border.EtchedBorder;

public class CodemakerUi {

private JPanel codemakerResponse;

private JPanel secretCode;

private JLabel[] secretLabels;

private JLabel[][] responseLabels;

private ImageIcon question;

private final Codemaker codemaker;

public CodemakerUi(Codemaker codemaker) {

this.codemaker = codemaker;

initComponents();

}

private void initComponents() {

initCodemakerResponse();

initSecretCode();

}

private void initCodemakerResponse() {

codemakerResponse = new JPanel();

codemakerResponse.setBorder(BorderFactory.createTitledBorder("Codemaker Response"));

codemakerResponse.setMinimumSize(new Dimension(200, 100));

codemakerResponse.setPreferredSize(new Dimension(200,100));

codemakerResponse.setLayout(new GridLayout(Constants.MAX_ATTEMPTS, Constants.MAX_PEGS));

// instantiate the Array with the size

responseLabels = new JLabel[Constants.MAX_ATTEMPTS][Constants.MAX_PEGS];

// create the array of JLabels for the code maker's response

for (int row = 0; row

for(int col = 0; col

// create the buttons

responseLabels[row][col] = new JLabel();

responseLabels[row][col].setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));

// add the button to the UI

codemakerResponse.add(responseLabels[row][col]);

}

}

}

private void initSecretCode() {

secretCode = new JPanel();

secretCode.setBorder(BorderFactory.createTitledBorder("Secret Code"));

secretCode.setMinimumSize(new Dimension(200, 60));

secretCode.setPreferredSize(new Dimension(200,60));

secretCode.setAlignmentY(JPanel.TOP_ALIGNMENT);

// instantiate the Array with the size

secretLabels = new JLabel[Constants.MAX_PEGS];

question = new ImageIcon("question.jpg");

// counter for enhanced for loop

int counter = 0;

for (JLabel label : secretLabels) {

label = new JLabel();

label.setBackground(Color.LIGHT_GRAY);

label.setIcon(imageResize(question));

// add button to JPanel using FlowLayout

secretCode.add(label);

// increment the counter

counter++;

}

//spacing

JLabel space = new JLabel();

space.setMinimumSize(new Dimension(100, 35));

space.setPreferredSize(new Dimension(100, 35));

secretCode.add(space);

// add the check button

JButton check = new JButton("Check");

secretCode.add(check);

}

/**

* @return the codemakerResponse

*/

public JPanel getCodemakerResponse() {

return codemakerResponse;

}

/**

* @return the secretCode

*/

public JPanel getSecretCode() {

return secretCode;

}

private ImageIcon imageResize(ImageIcon icon) {

Image image = icon.getImage();

Image newImage = image.getScaledInstance(30, 30, java.awt.Image.SCALE_SMOOTH);

icon = new ImageIcon(newImage);

return icon;

}

}

Codemaker.java

//bryan tavarez

/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */

package core;

import constants.Constants; import java.awt.Color; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set;

public class Codemaker implements ICodemaker { // member variables private Set secretCode; private ArrayList codemakerResponse; private boolean codeGuessed; public Codemaker() { // instantiate the member variable codeGuessed = false; secretCode = new HashSet(); codemakerResponse = new ArrayList(); // call the method to generate the secret code generateSecretCode(); } public void generateSecretCode() { Random random = new Random(); //randomly select four of the eight colors to be the secret code, only // use each color once while(secretCode.size() attempt) { // correct color in correct position is a red peg int redPegs = 0; // correct color in the wrong position is a white peg int whitePegs = 0; // incorrect color has no peg // keep track of which pegs we already counted Set countedPegs = new HashSet(); System.out.println("Codemaker is checking codebreaker attempt"); // convert the Set to an ArrayList List secretList = new ArrayList(secretCode); // is it an exact match? if(secretList.equals(attempt)) { redPegs += 4; whitePegs = 0; System.out.println("You guessed it!"); } // not an exact match, is it even in the secret code else { // check for correct color and correct position for(int peg = 0; peg

if((secretList.get(peg) != attempt.get(peg)) && (secretList.contains(attempt.get(peg))) && !countedPegs.contains(attempt.get(peg))) { System.out.println("Found correct color in wrong position"); // add a white peg whitePegs++; countedPegs.add(attempt.get(peg)); } } } } } evaluatePegs(redPegs, whitePegs); }

private void evaluatePegs(int red, int white) { // clear the codemakerResponse codemakerResponse.removeAll(codemakerResponse); System.out.println("Red pegs " + red + " white pegs " + white); if(red == Constants.MAX_PEGS) { codeGuessed = true; } for(int r = 0; r getSecretCode() { return secretCode; }

/** * @param secretCode the secretCode to set */ public void setSecretCode(Set secretCode) { this.secretCode = secretCode; }

/** * @return the codemakerResponse */ public ArrayList getCodemakerResponse() { return codemakerResponse; }

/** * @param codemakerResponse the codemakerResponse to set */ public void setCodemakerResponse(ArrayList codemakerResponse) { this.codemakerResponse = codemakerResponse; }

/** * @return the codeGuessed */ public boolean isCodeGuessed() { return codeGuessed; }

/** * @param codeGuessed the codeGuessed to set */ public void setCodeGuessed(boolean codeGuessed) { this.codeGuessed = codeGuessed; } }

Codebreaker.java

/** * @return the codebreakerAttempt */ public ArrayList getCodebreakerAttempt() { consoleAttempt(); return codebreakerAttempt; } /** * @param codebreakerAttempt the codebreakerAttempt to set */ public void setCodebreakerAttempt(ArrayList codebreakerAttempt) { this.codebreakerAttempt = codebreakerAttempt; } /** * * @param attempt * @return */ public boolean CheckCode(ArrayList attempt) { boolean errorFlag=false; for (Color color : attempt) { if(color!=Color.RED) { //only if ALL the colors in the list are red, attempt is correct else wrong / partially correct errorFlag=true; } } if(errorFlag) { System.out.println(); System.out.println("Found correct color in right position!"); for (int i=0;i { System.out.print(" "+col); }); System.out.println(); } else { consoleAttempt(); } } private Color stringToColor(String colorString) { Color color; try { Field field=Class.forName("java.awt.Color").getField(colorString); color = (Color)field.get(null); } catch (Exception e) { color = null; } return color; }

}

Mastermind Game Help Secret Code Check Codebreaker Attempt Codemaker Response Codebreaker Colors Mastermind Game Help Secret Code Check Codebreaker Attempt Codemaker Response Codebreaker Colors

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

Building The Data Lakehouse

Authors: Bill Inmon ,Mary Levins ,Ranjeet Srivastava

1st Edition

1634629663, 978-1634629669

More Books

Students also viewed these Databases questions