Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

PLEASE REFERENCE THE FOLLOWING CLASSES TO ANSWER QUESTION , THE FOLLOWING INFORM

ID: 3751797 • Letter: P

Question

PLEASE REFERENCE THE FOLLOWING CLASSES TO ANSWER QUESTION , THE FOLLOWING INFORMATION ARE ALL I WAS GIVEN:

MineSweeperBoardBase Class:

package cs2114.minesweeper;

// -------------------------------------------------------------------------
/**
* <p>
* A MineSweeperBoard holds a representation of the contents of the playing
* field for a Mine Sweeper game. The playing field is represented using a
* 2-dimensional array of values from the enumerated type
* {@link MineSweeperCell}. The value stored in each cell of the array
* indicates the icon which will appear in the corresponding cell of the
* graphical user interface for the game.
* </p><p>
* This abstract base class defines the basic features of a MineSweeperBoard,
* which you must create.
* </p>
*
*/
public abstract class MineSweeperBoardBase
{

* Construct a new MineSweeperBoard object.
*/
public MineSweeperBoardBase()
{
//
}

* Get the number of columns in this MineSweeperBoard.
*
* @return the number of columns in this MineSweeperBoard.
*/
public abstract int width();

* Get the number of rows in this MineSweeperBoard.
*
* @return the number of rows in this MineSweeperBoard
*/
public abstract int height();

* Get the contents of the specified cell on this MineSweeperBoard. The
* value returned from this method must be one of the values from the
* {@link MineSweeperCell} enumerated type.
*
* @param x the column containing the cell.
* @param y the row containing the cell.
* @return the value contained in the cell specified by x and y, or
* INVALID_CELL if the specified cell does not exist.
*/
public abstract MineSweeperCell getCell(int x, int y);


// ----------------------------------------------------------
/**
* Uncover the specified cell. If the cell already contains a flag it
* should not be uncovered. If there is not a mine under the specified
* cell then the value in that cell is changed to the number of mines
* that appear in adjacent cells. If there is a mine under the specified
* cell the game is over and the player has lost. If the specified cell
* is already uncovered or is invalid, no change is made to the board.
*
* @param x the column of the cell to be uncovered.
* @param y the row of the cell to be uncovered.
*/
public abstract void uncoverCell(int x, int y);


// ----------------------------------------------------------
/**
* Place or remove a flag from the specified cell. If the cell currently
* covered then place a flag on the cell. If the cell currently contains
* a flag, remove that flag but do not uncover the cell. If the cell has
* already been uncovered or is invalid, no change is made to the board.
*
* @param x the column of the cell to be flagged/unflagged
* @param y the row of the cell to be flagged/unflagged
*/
public abstract void flagCell(int x, int y);


// ----------------------------------------------------------
/**
* Determine if the player has lost the current game. The game is lost if
* the player has uncovered a mine.
*
* @return true if the current game has been lost and false otherwise
*/
public abstract boolean isGameLost();


// ----------------------------------------------------------
/**
* Determine if the player has won the current game. The game is won when
* three conditions are met:
*
* <ol>
* <li>Flags have been placed on all of the mines.</li>
* <li>No flags have been placed incorrectly.</li>
* <li>All non-flagged cells have been uncovered.</li>
* </ol>
*
* @return true if the current game has been won and false otherwise.
*/
public abstract boolean isGameWon();


// ----------------------------------------------------------
/**
* Count the number of mines that appear in cells that are adjacent to
* the specified cell.
*
* @param x the column of the cell.
* @param y the row of the cell.
* @return the number of mines adjacent to the specified cell.
*/
public abstract int numberOfAdjacentMines(int x, int y);


// ----------------------------------------------------------
/**
* Uncover all of the cells on the board.
*/
public abstract void revealBoard();


// ----------------------------------------------------------
/**
* Check whether two boards have the same cell contents.
* @param other the other object to compare with
*/
public boolean equals(Object other)
{
boolean result = false;

if (other == this)
{
result = true;
}
else if (other != null && other instanceof MineSweeperBoardBase)
{
MineSweeperBoardBase b = (MineSweeperBoardBase) other;

if (b.height() == height()
&& b.width() == width())
{
result = true;
for (int y = 0; y < height(); y++)
{
for (int x = 0; x < width(); x++)
{
if (b.getCell(x, y) != getCell(x, y))
{
return false;
}
}
}
}
}

return result;
}


// ----------------------------------------------------------
/**
* Generate a simple, human-readable representation of the contents of
* this MineSweeperBoard. This method is intended to be a useful tool for
* testing purposes. The board is surrounded by dashes, with cells marked
* using the following conventions:
*
* <pre>
* O = covered cell
* F = flag
* M = flagged mine
* + = covered mine
* * = uncovered mine (about to explode!)
* 1..9 or space = uncovered cell
* </pre>
*/
public String toString()
{
StringBuffer buffer = new StringBuffer(
(height() + 2) * (width() + 3));
for (int x = 0; x < width(); x++)
{
buffer.append('-');
}
buffer.append("-- ");
for (int y = 0; y < height(); y++)
{
buffer.append('|');
for (int x = 0; x < width(); x++)
{
switch (getCell(x, y))
{
case COVERED_CELL: buffer.append('O'); break;
case FLAG: buffer.append('F'); break;
case FLAGGED_MINE: buffer.append('M'); break;
case MINE: buffer.append('+'); break;
case UNCOVERED_MINE: buffer.append('*'); break;
case ADJACENT_TO_0: buffer.append(' '); break;
default:
int num = getCell(x, y).ordinal()
- MineSweeperCell.ADJACENT_TO_0.ordinal();
buffer.append(num);
break;
}
}
buffer.append("| ");
}
for (int x = 0; x < width(); x++)
{
buffer.append('-');
}
buffer.append("-- ");
return buffer.toString();
}


// ----------------------------------------------------------
/**
* Reset the board using a given series of strings. This method takes
* a variable number of arguments, and should be called with one String
* per row, where each String represents one row on the board. The
* characters in each string are interpreted, one character per board
* cell, using the same conventions as in toString() (e.g., the character
* 'O' represents an empty covered cell, '+' represents a covered mine,
* etc.).
*
* @param rows the Strings to interpret; there must
* be the same number of Strings as the number of rows in
* this board, and each string's length must be the same as
* the number of columns in this board.
*/
public void loadBoardState( String... rows )
{
if (rows.length != height())
{
throw new IllegalArgumentException(
"loadBoardState() was called with "
+ rows.length
+ " Strings when the board has "
+ height()
+ " rows");
}

for (int y = 0; y < height(); y++)
{
if (rows[y].length() != width())
{
throw new IllegalArgumentException(
"loadBoardState() was called with row "
+ y
+ " = ""
+ rows[y]
+ "" (only "
+ rows[y].length()
+ " characters) when the board has "
+ width()
+ " columns");
}

for (int x = 0; x < width(); x++)
{
switch (rows[y].charAt(x))
{
case 'O':
setCell(x, y, MineSweeperCell.COVERED_CELL);
break;

case 'F':
setCell(x, y, MineSweeperCell.FLAG);
break;

case 'M':
setCell(x, y, MineSweeperCell.FLAGGED_MINE);
break;

case '+':
setCell(x, y, MineSweeperCell.MINE);
break;

case '*':
setCell(x, y, MineSweeperCell.UNCOVERED_MINE);
break;

case ' ':
setCell(x, y, MineSweeperCell.ADJACENT_TO_0);
break;

case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
setCell(x, y, MineSweeperCell.adjacentTo(
rows[y].charAt(x) - '0'));
break;

default:
throw new IllegalArgumentException(
"loadBoardState() was called with row "
+ y
+ " = ""
+ rows[y]
+ "", but '"
+ rows[y].charAt(x)
+ "' is not a recognized cell state");
}
}
}
}


//~ Protected Methods .....................................................

// ----------------------------------------------------------
/**
* Set the contents of the specified cell on this MineSweeperBoard. The
* value passed in should be one of the defined constants in the
* {@link MineSweeperCell} enumerated type.
*
* @param x the column containing the cell
* @param y the row containing the cell
* @param value the value to place in the cell
*/
protected abstract void setCell(int x, int y, MineSweeperCell value);
}

MINESWEEPERCELL CLASS:

public enum MineSweeperCell
{
//~ Constants .............................................................

/**
* Represents the contents of an invalid cell. This value can be returned
* by the {@link MineSweeperBoardBase#getCell(int, int)} method when an
* invalid cell is specified.
*/
INVALID_CELL,

/**
* Represents a covered cell -- any cell which does not contains a mine,
* has not been flagged and has not yet been uncovered.
*/
COVERED_CELL,

/**
* Represents a cell that does not contain a mine but has had a flag placed
* on it.
*/
FLAG,

/**
* Represents a cell that has not been uncovered yet but contains a mine.
*/
MINE,

/**
* Represents a cell that contains a mine and has had a flag placed on it.
*/
FLAGGED_MINE,

/**
* Represents a cell containing a mine that has been uncovered.
*/
UNCOVERED_MINE,

/**
* Represents a cell that has been uncovered and has 0 mines around it.
*/
ADJACENT_TO_0,

/**
* Represents a cell that has been uncovered and has 1 mine around it.
*/
ADJACENT_TO_1,

/**
* Represents a cell that has been uncovered and has 2 mines around it.
*/
ADJACENT_TO_2,

/**
* Represents a cell that has been uncovered and has 3 mines around it.
*/
ADJACENT_TO_3,

/**
* Represents a cell that has been uncovered and has 4 mines around it.
*/
ADJACENT_TO_4,

/**
* Represents a cell that has been uncovered and has 5 mines around it.
*/
ADJACENT_TO_5,

/**
* Represents a cell that has been uncovered and has 6 mines around it.
*/
ADJACENT_TO_6,

/**
* Represents a cell that has been uncovered and has 7 mines around it.
*/
ADJACENT_TO_7,

/**
* Represents a cell that has been uncovered and has 8 mines around it.
*/
ADJACENT_TO_8;


//~ Methods ...............................................................

// ----------------------------------------------------------
/**
* Gets the {@code ADJACENT_TO_*} constant that represents the specified
* number of adjacent mines. This method is useful when you want to get the
* cell value for a number of mines that was computed at runtime.
*
* @param number the number of adjacent mines; must be between 0 and 8
* @return the corresponding {@code ADJACENT_TO_*} constant
* @throws IllegalArgumentException if {@code number} was not between
* 0 and 8
*/
public static MineSweeperCell adjacentTo(int number)
{
if (0 <= number && number <= 8)
{
// This code only works as long as the values ADJACENT_TO_0 up to
// ADJACENT_TO_8 are placed in numerical order in the enum
// definitions.

return values()[ADJACENT_TO_0.ordinal() + number];
}
else
{
throw new IllegalArgumentException("MineSweeperCell.adjacentTo "
+ "only accepts values from 0 to 8.");
}
}
}

QUESTION TO BE ANSWERED:

Your assignment is to complete the implementation of the Mine Sweeper game. To do so, you will need to write a class in thecs2114.minesweeperpackage calledMineSweeperBoard, and make it extend theMineSweeperBoardBaseabstract base class. You will have to implement all of the abstract methods required by the base class. In addition,you may need to design and implement your own helper methods to keep your code clean and easy to understand.Think carefully about the internal design of your class. Glance over the project that you were given. The "src" folder is where you will do all your work.

(To create the class in the correct package, expand the "src" folder and then right-click on cs2114.minesweeper and choose "New > Class" from the menu.)

You do not need to implement the non-abstract methods in MineSweeperBoardBase, namely equals, toString, and loadBoardState. These are already implemented for you to support testing and debugging, so don't waste valuable time reinventing the wheel.

The MineSweeperBoard class is responsible for keeping track of the contents of the Mine Sweeper board as the game is being played. Many of the details you will need to perform this implementation can be found in the Java Documentation for the MineSweeperBoardBase class. The following sections contain some additional information about the MineSweeperBoardBase class and give an outline for how to approach this assignment.

In addition to the abstract methods that you must implement, you must also provide a MineSweeperBoard constructor that takes three arguments: the width of the board, the height of the board, and the number of mines to place on the board, in that order. In addition to creating the space to store the cells, your constructor should randomly place the specified number of mines on the board.

To randomly place mines, you can use the  java.util.Random class .

Representing the Board

In this assignment, each cell on the game board is represented by an enumerated type named MineSweeperCell. As a quick review, an enumerated type (or enum for short), is a type that represents a small fixed set of choices that you can refer to by name. So, for example, MineSweeperCell.COVERED_CELL would represent a cell on the board that is covered; we'll discuss the types in more detail below.

We will use a two-dimensional array of MineSweeperCell values to represent the current state of the playing board inside your MineSweeperBoard class. In fact, you are required to use a two-dimensional array in your representation to ensure you get more practice with this low-level feature (you may not use ArrayLists or other java.util structures to store the board grid in this assignment).

When you model the board state as a two-dimensional array of MineSweeperCell values, the value contained in each cell indicates the contents of the cell and whether or not it has been uncovered or has had a flag placed on it. The following table gives a list of the values that may appear in such an array:

MineSweeperCell.COVERED_CELL

An array entry containing the value COVERED_CELL indicates an empty cell on the board that has not yet been uncovered by the player.

MineSweeperCell.MINE

An array entry containing the value MINE indicates a cell containing a mine which has neither been uncovered by the player nor has it had a flag placed on it.

MineSweeperCell.FLAG

An array entry containing the value FLAG indicates a cell that does not contain a mine, but which has had a flag (incorrectly) placed on it.

MineSweeperCell.FLAGGED_MINE

An array entry containing the value FLAGGED_MINE indicates a cell that does contain a mine and has had a flag (correctly) placed on it.

MineSweeperCell.UNCOVERED_MINE

An array entry containing the value UNCOVERED_MINE indicates a cell containing a mine which has been uncovered by the player.

MineSweeperCell.ADJACENT_TO_0...MineSweeperCell.ADJACENT_TO_8

An array entry containing one of these values indicates an empty cell which has been uncovered. The specific value between 0 and 8 indicates the number of mines which appear in the adjacent cells.

The MineSweeperCell enumerated type also has a helper method named adjacentTo that takes an integer between 0 and 8 and returns the appropriate enum value. For example, MineSweeperCell.adjacentTo(4) returns MineSweeperCell.ADJACENT_TO_4. You should use this helper method where appropriate to avoid complex if/switch logic when you need to convert a number of adjacent mines into the matching enum value.

To help clarify the meaning of these values consider the following examples. When a new MineSweeperBoard is created it will contain only COVERED_CELLs and MINEs. The MINEs will be placed randomly in the array. For example if the new array has width 4 and height 3 it might look as follows:

If the player were to left click on the upper right hand cell of the board then the MineSweeperBoard class would change cell (0,3) of its array to ADJACENT_TO_0 as shown below:

Cell (0,3) was changed to ADJACENT_TO_0 reflecting the fact that the cell has been uncovered and that there are no mines adjacent to this cell. When the Mine Sweeper game sees ADJACENT_TO_0 in this location it will display a sunken blank icon in the upper-right corner.

If the player were now to click in the center cell in the left-most column, the MineSweeperBoard would change cell (1,0) in its array to ADJACENT_TO_2, indicating that there are two mines adjacent to that cell. When the Mine Sweeper game see ADJACENT_TO_2 in this location it will display a sunken icon containing the number 2. The array would now appear as follows:

If the player were now to right click on the cell in the lower-left corner of the board to place a flag on that cell, the MineSweeperBoard would change cell (2,0) of its array to FLAG. Recall that the value FLAG indicates that a flag has been (incorrectly) placed on a cell which does not contain a mine. The array would now appear as shown below:

If the player now right clicks on the cell in the upper-left corner of the board, the MineSweeperBoard would change cell (0,0) of its array to a FLAGGED_MINE. The value FLAGGED_MINE indicates that a flag has been (correctly) placed on a cell containing a mine. The array would now appear as shown below:

Imagine now that player, having decided that the cell in the lower-left corner of the board should not be flagged, right-clicks again on the lower-left corner cell. The MineSweeperBoard must now change cell (2,0) of its array back to an UNCOVERED_CELL. Similarly, if the player were to decide to remove the flag from the upper-left corner, the MineSweeperBoard class would have to change cell (0,0) of its array back to a MINE. Finally, if after removing the flag from the upper-left corner of the board, the poor unsuspecting player left clicks that cell, the MineSweeperBoard will change cell (0,0) to a UNCOVERED_MINE, effectively causing the game to end.

To Do

Take time to understand the methods provided by the MineSweeperBoardBase abstract class. You don't have the code for this class, but you have the JavaDoc documentation. Your job is to write your own MineSweeperBoard class that extends MineSweeperBoardBase and implements all of the methods it declares and capitalizes on the design aspects already in place.

In addition, you will also need to test your work. Don't save testing until the end - instead start writing tests for each piece of behavior as you add it in order to get the most benefit.

When you are done, you will have an almost complete, working Mine Sweeper game!

Testing Tips

For this project you are responsible for testing the MineSweeperBoard class. The testing can be based on a simple test fixture - perhaps a 4x4 board with explicit characteristics.

Note that the base class provides the loadBoardState() method, which you can use to set up specific testing situations. The toString() method can be used to print the current state of the board to the terminal window:

Here is a sample test case for the setCell() method:

This example uses a helper function called assertBoard() as a useful building block for simplifying test cases. You can use it as a model in your own code (with some care in your design, you can simplify it even further!). Note that it uses a variable number of arguments, taking a board followed by any number of strings. The entire group of arguments representing the variable part of the method's signature are accessible inside the method's body as a raw array.

Most of your testing will use loadBoardState(), which means any mine placement in your constructor won't affect your tests. However, to write a test case that exercises your random mine placement, read the page on Testing Tips for Random Numbers.

Notes

The uncoverCell() method should only change the single cell specified. It is not necessary to attempt to replicate the behavior of the Windows version of mine sweeper where uncovering an empty cell causes a cascaded "auto-uncovering" of all adjacent empty cells as well. Instead, only uncover the one cell specified, which makes the assignment easier for everyone.

Running Your Tests

To run your tests, right-click "Assignment01-Minesweeper" in your workspace and choose "Run As > JUnit Test" from the menu. When they're done, the JUnit view will automatically be brought to the front and show your test results.

*please help*

COVERED COVERED COVERED CELL CELLCELL MINE COVERED COVERED COVERED COVERED CELL CELLCELL CELL COVERED CELL MINE COVERED COVERED CELL CELL

Explanation / Answer

Minesweeper.java :

import java.awt.*;
import java.awt.Dimension;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;

class Minesweeper extends JFrame implements ActionListener, ContainerListener {

int fw, fh, blockr, blockc, var1, var2, num_of_mine, detectedmine = 0, savedlevel = 1,
savedblockr, savedblockc, savednum_of_mine = 10;
int[] r = {-1, -1, -1, 0, 1, 1, 1, 0};
int[] c = {-1, 0, 1, 1, 1, 0, -1, -1};
JButton[][] blocks;
int[][] countmine;
int[][] colour;
ImageIcon[] ic = new ImageIcon[14];
JPanel panelb = new JPanel();
JPanel panelmt = new JPanel();
JTextField tf_mine, tf_time;
JButton reset = new JButton("");
Random ranr = new Random();
Random ranc = new Random();
boolean check = true, starttime = false;
Point framelocation;
Stopwatch sw;
MouseHendeler mh;
Point p;

Minesweeper() {
super("Minesweeper");
setLocation(400, 300);

setic();
setpanel(1, 0, 0, 0);
setmanue();

sw = new Stopwatch();

reset.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent ae) {
try {
sw.stop();
setpanel(savedlevel, savedblockr, savedblockc, savednum_of_mine);
} catch (Exception ex) {
setpanel(savedlevel, savedblockr, savedblockc, savednum_of_mine);
}
reset();

}
});
setDefaultCloseOperation(EXIT_ON_CLOSE);
show();
}

public void reset() {
check = true;
starttime = false;
for (int i = 0; i < blockr; i++) {
for (int j = 0; j < blockc; j++) {
colour[i][j] = 'w';
}
}
}

public void setpanel(int level, int setr, int setc, int setm) {
if (level == 1) {
fw = 200;
fh = 300;
blockr = 10;
blockc = 10;
num_of_mine = 10;
} else if (level == 2) {
fw = 320;
fh = 416;
blockr = 16;
blockc = 16;
num_of_mine = 70;
} else if (level == 3) {
fw = 400;
fh = 520;
blockr = 20;
blockc = 20;
num_of_mine = 150;
} else if (level == 4) {
fw = (20 * setc);
fh = (24 * setr);
blockr = setr;
blockc = setc;
num_of_mine = setm;
}

savedblockr = blockr;
savedblockc = blockc;
savednum_of_mine = num_of_mine;

setSize(fw, fh);
setResizable(false);
detectedmine = num_of_mine;
p = this.getLocation();

blocks = new JButton[blockr][blockc];
countmine = new int[blockr][blockc];
colour = new int[blockr][blockc];
mh = new MouseHendeler();

getContentPane().removeAll();
panelb.removeAll();

tf_mine = new JTextField("" + num_of_mine, 3);
tf_mine.setEditable(false);
tf_mine.setFont(new Font("DigtalFont.TTF", Font.BOLD, 25));
tf_mine.setBackground(Color.BLACK);
tf_mine.setForeground(Color.RED);
tf_mine.setBorder(BorderFactory.createLoweredBevelBorder());
tf_time = new JTextField("000", 3);
tf_time.setEditable(false);
tf_time.setFont(new Font("DigtalFont.TTF", Font.BOLD, 25));
tf_time.setBackground(Color.BLACK);
tf_time.setForeground(Color.RED);
tf_time.setBorder(BorderFactory.createLoweredBevelBorder());
reset.setIcon(ic[11]);
reset.setBorder(BorderFactory.createLoweredBevelBorder());

panelmt.removeAll();
panelmt.setLayout(new BorderLayout());
panelmt.add(tf_mine, BorderLayout.WEST);
panelmt.add(reset, BorderLayout.CENTER);
panelmt.add(tf_time, BorderLayout.EAST);
panelmt.setBorder(BorderFactory.createLoweredBevelBorder());

panelb.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10), BorderFactory.createLoweredBevelBorder()));
panelb.setPreferredSize(new Dimension(fw, fh));
panelb.setLayout(new GridLayout(0, blockc));
panelb.addContainerListener(this);

for (int i = 0; i < blockr; i++) {
for (int j = 0; j < blockc; j++) {
blocks[i][j] = new JButton("");

//blocks[i][j].addActionListener(this);
blocks[i][j].addMouseListener(mh);

panelb.add(blocks[i][j]);

}
}
reset();

panelb.revalidate();
panelb.repaint();
//getcontentpane().setOpaque(true);

getContentPane().setLayout(new BorderLayout());
getContentPane().addContainerListener(this);
//getContentPane().revalidate();
getContentPane().repaint();
getContentPane().add(panelb, BorderLayout.CENTER);
getContentPane().add(panelmt, BorderLayout.NORTH);
setVisible(true);
}

public void setmanue() {
JMenuBar bar = new JMenuBar();

JMenu game = new JMenu("GAME");

JMenuItem menuitem = new JMenuItem("new game");
final JCheckBoxMenuItem beginner = new JCheckBoxMenuItem("Begineer");
final JCheckBoxMenuItem intermediate = new JCheckBoxMenuItem("Intermediate");
final JCheckBoxMenuItem expart = new JCheckBoxMenuItem("Expart");
final JCheckBoxMenuItem custom = new JCheckBoxMenuItem("Custom");
final JMenuItem exit = new JMenuItem("Exit");
final JMenu help = new JMenu("Help");
final JMenuItem helpitem = new JMenuItem("Help");

ButtonGroup status = new ButtonGroup();

menuitem.addActionListener(
new ActionListener() {

public void actionPerformed(ActionEvent e) {

//panelb.removeAll();
//reset();
setpanel(1, 0, 0, 0);
//panelb.revalidate();
//panelb.repaint();
}
});

beginner.addActionListener(
new ActionListener() {

public void actionPerformed(ActionEvent e) {
panelb.removeAll();
reset();
setpanel(1, 0, 0, 0);
panelb.revalidate();
panelb.repaint();
beginner.setSelected(true);
savedlevel = 1;
}
});
intermediate.addActionListener(
new ActionListener() {

public void actionPerformed(ActionEvent e) {
panelb.removeAll();
reset();
setpanel(2, 0, 0, 0);
panelb.revalidate();
panelb.repaint();
intermediate.setSelected(true);
savedlevel = 2;
}
});
expart.addActionListener(
new ActionListener() {

public void actionPerformed(ActionEvent e) {
panelb.removeAll();
reset();
setpanel(3, 0, 0, 0);
panelb.revalidate();
panelb.repaint();
expart.setSelected(true);
savedlevel = 3;
}
});

custom.addActionListener(
new ActionListener() {

public void actionPerformed(ActionEvent e) {
//panelb.removeAll();
Customizetion cus = new Customizetion();
reset();
panelb.revalidate();
panelb.repaint();

//Minesweeper ob=new Minesweeper(4);
custom.setSelected(true);
savedlevel = 4;
}
});

exit.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});

helpitem.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "instruction");

}
});

setJMenuBar(bar);

status.add(beginner);
status.add(intermediate);
status.add(expart);
status.add(custom);

game.add(menuitem);
game.addSeparator();
game.add(beginner);
game.add(intermediate);
game.add(expart);
game.add(custom);
game.addSeparator();
game.add(exit);
help.add(helpitem);

bar.add(game);
bar.add(help);

}

public void componentAdded(ContainerEvent ce) {
}

public void componentRemoved(ContainerEvent ce) {
}

public void actionPerformed(ActionEvent ae) {
}

class MouseHendeler extends MouseAdapter {

public void mouseClicked(MouseEvent me) {
if (check == true) {
for (int i = 0; i < blockr; i++) {
for (int j = 0; j < blockc; j++) {
if (me.getSource() == blocks[i][j]) {
var1 = i;
var2 = j;
i = blockr;
break;
}
}
}

setmine();
calculation();
check = false;

}

showvalue(me);
winner();

if (starttime == false) {
sw.Start();
starttime = true;
}

}
}

public void winner() {
int q = 0;
for (int k = 0; k < blockr; k++) {
for (int l = 0; l < blockc; l++) {
if (colour[k][l] == 'w') {
q = 1;
}
}
}


if (q == 0) {
//panelb.hide();
for (int k = 0; k < blockr; k++) {
for (int l = 0; l < blockc; l++) {
blocks[k][l].removeMouseListener(mh);
}
}

sw.stop();
JOptionPane.showMessageDialog(this, "u R a lover");
}
}

public void showvalue(MouseEvent e) {
for (int i = 0; i < blockr; i++) {
for (int j = 0; j < blockc; j++) {

if (e.getSource() == blocks[i][j]) {
if (e.isMetaDown() == false) {
if (blocks[i][j].getIcon() == ic[10]) {
if (detectedmine < num_of_mine) {
detectedmine++;
}
tf_mine.setText("" + detectedmine);
}

if (countmine[i][j] == -1) {
for (int k = 0; k < blockr; k++) {
for (int l = 0; l < blockc; l++) {
if (countmine[k][l] == -1) {

//blocks[k][l].setText("X");
blocks[k][l].setIcon(ic[9]);
//blocks[k][l].setBackground(Color.BLUE);
//blocks[k][l].setFont(new Font("",Font.CENTER_BASELINE,8));
blocks[k][l].removeMouseListener(mh);
}
blocks[k][l].removeMouseListener(mh);
}
}
sw.stop();
reset.setIcon(ic[12]);
JOptionPane.showMessageDialog(null, "sorry u R loser");
} else if (countmine[i][j] == 0) {
dfs(i, j);
} else {
blocks[i][j].setIcon(ic[countmine[i][j]]);
//blocks[i][j].setText(""+countmine[i][j]);
//blocks[i][j].setBackground(Color.pink);
//blocks[i][j].setFont(new Font("",Font.PLAIN,8));
colour[i][j] = 'b';
//blocks[i][j].setBackground(Color.pink);
break;
}
} else {
if (detectedmine != 0) {
if (blocks[i][j].getIcon() == null) {
detectedmine--;
blocks[i][j].setIcon(ic[10]);
}
tf_mine.setText("" + detectedmine);
}


}
}

}
}

}

public void calculation() {
int row, column;

for (int i = 0; i < blockr; i++) {
for (int j = 0; j < blockc; j++) {
int value = 0;
int R, C;
row = i;
column = j;
if (countmine[row][column] != -1) {
for (int k = 0; k < 8; k++) {
R = row + r[k];
C = column + c[k];

if (R >= 0 && C >= 0 && R < blockr && C < blockc) {
if (countmine[R][C] == -1) {
value++;
}

}

}
countmine[row][column] = value;

}
}
}
}

public void dfs(int row, int col) {

int R, C;
colour[row][col] = 'b';

blocks[row][col].setBackground(Color.GRAY);

blocks[row][col].setIcon(ic[countmine[row][col]]);
//blocks[row][col].setText("");
for (int i = 0; i < 8; i++) {
R = row + r[i];
C = col + c[i];
if (R >= 0 && R < blockr && C >= 0 && C < blockc && colour[R][C] == 'w') {
if (countmine[R][C] == 0) {
dfs(R, C);
} else {
blocks[R][C].setIcon(ic[countmine[R][C]]);
//blocks[R][C].setText(""+countmine[R][C]);

//blocks[R][C].setBackground(Color.pink);
//blocks[R][C].setFont(new Font("",Font.BOLD,));
colour[R][C] = 'b';

}
}


}
}

public void setmine() {
int row = 0, col = 0;
Boolean[][] flag = new Boolean[blockr][blockc];


for (int i = 0; i < blockr; i++) {
for (int j = 0; j < blockc; j++) {
flag[i][j] = true;
countmine[i][j] = 0;
}
}

flag[var1][var2] = false;
colour[var1][var2] = 'b';

for (int i = 0; i < num_of_mine; i++) {
row = ranr.nextInt(blockr);
col = ranc.nextInt(blockc);

if (flag[row][col] == true) {

countmine[row][col] = -1;
colour[row][col] = 'b';
flag[row][col] = false;
} else {
i--;
}
}
}

public void setic() {
String name;

for (int i = 0; i <= 8; i++) {
name = i + ".gif";
ic[i] = new ImageIcon(name);
}
ic[9] = new ImageIcon("mine.gif");
ic[10] = new ImageIcon("flag.gif");
ic[11] = new ImageIcon("new game.gif");
ic[12] = new ImageIcon("crape.gif");
}

public class Stopwatch extends JFrame implements Runnable {

long startTime;
//final static java.text.SimpleDateFormat timerFormat = new java.text.SimpleDateFormat("mm : ss :SSS");
//final JButton startStopButton= new JButton("Start/stop");
Thread updater;
boolean isRunning = false;
long a = 0;
Runnable displayUpdater = new Runnable() {

public void run() {
displayElapsedTime(a);
a++;
}
};

public void stop() {
long elapsed = a;
isRunning = false;
try {
updater.join();
} catch (InterruptedException ie) {
}
displayElapsedTime(elapsed);
a = 0;
}

private void displayElapsedTime(long elapsedTime) {

if (elapsedTime >= 0 && elapsedTime < 9) {
tf_time.setText("00" + elapsedTime);
} else if (elapsedTime > 9 && elapsedTime < 99) {
tf_time.setText("0" + elapsedTime);
} else if (elapsedTime > 99 && elapsedTime < 999) {
tf_time.setText("" + elapsedTime);
}
}

public void run() {
try {
while (isRunning) {
SwingUtilities.invokeAndWait(displayUpdater);
Thread.sleep(1000);
}
} catch (java.lang.reflect.InvocationTargetException ite) {
ite.printStackTrace(System.err);
} catch (InterruptedException ie) {
}
}

public void Start() {
startTime = System.currentTimeMillis();
isRunning = true;
updater = new Thread(this);
updater.start();
}
}

class Customizetion extends JFrame implements ActionListener {

JTextField t1, t2, t3;
JLabel lb1, lb2, lb3;
JButton b1, b2;
int cr, cc, cm, actionc = 0;

Customizetion() {
super("CUSTOMIZETION");
setSize(180, 200);
setResizable(false);
setLocation(p);

t1 = new JTextField();
t2 = new JTextField();
t3 = new JTextField();

b1 = new JButton("OK");
b2 = new JButton("Cencel");

b1.addActionListener(this);
b2.addActionListener(this);

lb1 = new JLabel("Row");
lb2 = new JLabel("Column");
lb3 = new JLabel("mine");

getContentPane().setLayout(new GridLayout(0, 2));

getContentPane().add(lb1);
getContentPane().add(t1);
getContentPane().add(lb2);
getContentPane().add(t2);
getContentPane().add(lb3);
getContentPane().add(t3);

getContentPane().add(b1);
getContentPane().add(b2);

show();
}

public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
try {
cr = Integer.parseInt(t1.getText());
cc = Integer.parseInt(t2.getText());
cm = Integer.parseInt(t3.getText());
//Minesweeper ms=new Minesweeper();
setpanel(4, row(), column(), mine());
dispose();
} catch (Exception any) {
JOptionPane.showMessageDialog(this, "Wrong");
t1.setText("");
t2.setText("");
t3.setText("");
}
//Show_rcm();
}

if (e.getSource() == b2) {
dispose();
}
}

public int row() {
if (cr > 30) {
return 30;
} else if (cr < 10) {
return 10;
} else {
return cr;
}
}

public int column() {
if (cc > 30) {
return 30;
} else if (cc < 10) {
return 10;
} else {
return cc;
}
}

public int mine() {
if (cm > ((row() - 1) * (column() - 1))) {
return ((row() - 1) * (column() - 1));
} else if (cm < 10) {
return 10;
} else {
return cm;
}
}
}
}

Main.java

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Minesweeper ob=new Minesweeper();
}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote