SlideShare a Scribd company logo
1 of 16
Download to read offline
Objective:
Create a graphical game of minesweeper IN JAVA. The board should consist of 10x10 buttons.
Of the 100 spaces there should be at least 20 randomly placed mines. If the button is clicked and
it is not a mine then it clears itself. If a space has been cleared then it should indicate how many
of its eight neighbors are mines. If a space is clicked and it is a mine then the game is over and
the player is asked if they want to play again. Finally, if all the non-mine spaces have been
clicked then the player is prompted that they won.
Solution
2 files need to be made.
First Game.Java which will have the gaming logic and User Interface and Main.Java which will
have have the main method and object of Game.java Number of rows and cols is customizable so
user can change that as and when needed.
import java.awt.*;
import java.awt.Dimension;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class Game 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;
Game() {
super("Game");
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.createEmptyBorde
r(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();
//Game ob=new Game(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());
//Game ms=new Game();
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;
}
}
}
}

More Related Content

Similar to Create a 10x10 Minesweeper Game in Java

package com.tictactoe; public class Main {public void play() {.pdf
package com.tictactoe; public class Main {public void play() {.pdfpackage com.tictactoe; public class Main {public void play() {.pdf
package com.tictactoe; public class Main {public void play() {.pdfinfo430661
 
The Ring programming language version 1.9 book - Part 60 of 210
The Ring programming language version 1.9 book - Part 60 of 210The Ring programming language version 1.9 book - Part 60 of 210
The Ring programming language version 1.9 book - Part 60 of 210Mahmoud Samir Fayed
 
Making Games in JavaScript
Making Games in JavaScriptMaking Games in JavaScript
Making Games in JavaScriptSam Cartwright
 
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdfimport java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdfaoneonlinestore1
 
The Ring programming language version 1.5.3 book - Part 79 of 184
The Ring programming language version 1.5.3 book - Part 79 of 184The Ring programming language version 1.5.3 book - Part 79 of 184
The Ring programming language version 1.5.3 book - Part 79 of 184Mahmoud Samir Fayed
 
The Ring programming language version 1.10 book - Part 71 of 212
The Ring programming language version 1.10 book - Part 71 of 212The Ring programming language version 1.10 book - Part 71 of 212
The Ring programming language version 1.10 book - Part 71 of 212Mahmoud Samir Fayed
 
The Ring programming language version 1.8 book - Part 56 of 202
The Ring programming language version 1.8 book - Part 56 of 202The Ring programming language version 1.8 book - Part 56 of 202
The Ring programming language version 1.8 book - Part 56 of 202Mahmoud Samir Fayed
 
Why am I getting an out of memory error and no window of my .pdf
Why am I getting an out of memory error and no window of my .pdfWhy am I getting an out of memory error and no window of my .pdf
Why am I getting an out of memory error and no window of my .pdfaakarcreations1
 
import java.util.Scanner;public class Main {    public static in.pdf
import java.util.Scanner;public class Main {    public static in.pdfimport java.util.Scanner;public class Main {    public static in.pdf
import java.util.Scanner;public class Main {    public static in.pdfanwarsadath111
 
The Ring programming language version 1.10 book - Part 70 of 212
The Ring programming language version 1.10 book - Part 70 of 212The Ring programming language version 1.10 book - Part 70 of 212
The Ring programming language version 1.10 book - Part 70 of 212Mahmoud Samir Fayed
 
The Ring programming language version 1.3 book - Part 52 of 88
The Ring programming language version 1.3 book - Part 52 of 88The Ring programming language version 1.3 book - Part 52 of 88
The Ring programming language version 1.3 book - Part 52 of 88Mahmoud Samir Fayed
 
Mobile Game and Application with J2ME
Mobile Gameand Application with J2MEMobile Gameand Application with J2ME
Mobile Game and Application with J2MEJenchoke Tachagomain
 
Mobile Game and Application with J2ME - Collision Detection
Mobile Gameand Application withJ2ME  - Collision DetectionMobile Gameand Application withJ2ME  - Collision Detection
Mobile Game and Application with J2ME - Collision DetectionJenchoke Tachagomain
 
public interface Game Note interface in place of class { .pdf
public interface Game  Note interface in place of class { .pdfpublic interface Game  Note interface in place of class { .pdf
public interface Game Note interface in place of class { .pdfkavithaarp
 

Similar to Create a 10x10 Minesweeper Game in Java (20)

J2 me 07_5
J2 me 07_5J2 me 07_5
J2 me 07_5
 
package com.tictactoe; public class Main {public void play() {.pdf
package com.tictactoe; public class Main {public void play() {.pdfpackage com.tictactoe; public class Main {public void play() {.pdf
package com.tictactoe; public class Main {public void play() {.pdf
 
Mouse and Cat Game In C++
Mouse and Cat Game In C++Mouse and Cat Game In C++
Mouse and Cat Game In C++
 
The Ring programming language version 1.9 book - Part 60 of 210
The Ring programming language version 1.9 book - Part 60 of 210The Ring programming language version 1.9 book - Part 60 of 210
The Ring programming language version 1.9 book - Part 60 of 210
 
Flappy bird
Flappy birdFlappy bird
Flappy bird
 
Making Games in JavaScript
Making Games in JavaScriptMaking Games in JavaScript
Making Games in JavaScript
 
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdfimport java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
 
The Ring programming language version 1.5.3 book - Part 79 of 184
The Ring programming language version 1.5.3 book - Part 79 of 184The Ring programming language version 1.5.3 book - Part 79 of 184
The Ring programming language version 1.5.3 book - Part 79 of 184
 
The Ring programming language version 1.10 book - Part 71 of 212
The Ring programming language version 1.10 book - Part 71 of 212The Ring programming language version 1.10 book - Part 71 of 212
The Ring programming language version 1.10 book - Part 71 of 212
 
Cocos2dx 7.1-7.2
Cocos2dx 7.1-7.2Cocos2dx 7.1-7.2
Cocos2dx 7.1-7.2
 
The Ring programming language version 1.8 book - Part 56 of 202
The Ring programming language version 1.8 book - Part 56 of 202The Ring programming language version 1.8 book - Part 56 of 202
The Ring programming language version 1.8 book - Part 56 of 202
 
Why am I getting an out of memory error and no window of my .pdf
Why am I getting an out of memory error and no window of my .pdfWhy am I getting an out of memory error and no window of my .pdf
Why am I getting an out of memory error and no window of my .pdf
 
import java.util.Scanner;public class Main {    public static in.pdf
import java.util.Scanner;public class Main {    public static in.pdfimport java.util.Scanner;public class Main {    public static in.pdf
import java.util.Scanner;public class Main {    public static in.pdf
 
Ocr code
Ocr codeOcr code
Ocr code
 
The Ring programming language version 1.10 book - Part 70 of 212
The Ring programming language version 1.10 book - Part 70 of 212The Ring programming language version 1.10 book - Part 70 of 212
The Ring programming language version 1.10 book - Part 70 of 212
 
The Ring programming language version 1.3 book - Part 52 of 88
The Ring programming language version 1.3 book - Part 52 of 88The Ring programming language version 1.3 book - Part 52 of 88
The Ring programming language version 1.3 book - Part 52 of 88
 
Mobile Game and Application with J2ME
Mobile Gameand Application with J2MEMobile Gameand Application with J2ME
Mobile Game and Application with J2ME
 
Mobile Game and Application with J2ME - Collision Detection
Mobile Gameand Application withJ2ME  - Collision DetectionMobile Gameand Application withJ2ME  - Collision Detection
Mobile Game and Application with J2ME - Collision Detection
 
public interface Game Note interface in place of class { .pdf
public interface Game  Note interface in place of class { .pdfpublic interface Game  Note interface in place of class { .pdf
public interface Game Note interface in place of class { .pdf
 
Of class2
Of class2Of class2
Of class2
 

More from rajkumarm401

Having issues with passing my values through different functions aft.pdf
Having issues with passing my values through different functions aft.pdfHaving issues with passing my values through different functions aft.pdf
Having issues with passing my values through different functions aft.pdfrajkumarm401
 
Explain the characterstic of web service techonolgy.SolutionT.pdf
Explain the characterstic of web service techonolgy.SolutionT.pdfExplain the characterstic of web service techonolgy.SolutionT.pdf
Explain the characterstic of web service techonolgy.SolutionT.pdfrajkumarm401
 
Executive Summary i. Provide a succinct overview of your strategic p.pdf
Executive Summary i. Provide a succinct overview of your strategic p.pdfExecutive Summary i. Provide a succinct overview of your strategic p.pdf
Executive Summary i. Provide a succinct overview of your strategic p.pdfrajkumarm401
 
eee230 Instruction details Answer the following questions in a typed.pdf
eee230 Instruction details Answer the following questions in a typed.pdfeee230 Instruction details Answer the following questions in a typed.pdf
eee230 Instruction details Answer the following questions in a typed.pdfrajkumarm401
 
Essay questionPorter Combining business strategy What is itmeani.pdf
Essay questionPorter Combining business strategy What is itmeani.pdfEssay questionPorter Combining business strategy What is itmeani.pdf
Essay questionPorter Combining business strategy What is itmeani.pdfrajkumarm401
 
During oogenesis, will the genotypes of the first and second polar b.pdf
During oogenesis, will the genotypes of the first and second polar b.pdfDuring oogenesis, will the genotypes of the first and second polar b.pdf
During oogenesis, will the genotypes of the first and second polar b.pdfrajkumarm401
 
Does personal information available on the Internet make an employee.pdf
Does personal information available on the Internet make an employee.pdfDoes personal information available on the Internet make an employee.pdf
Does personal information available on the Internet make an employee.pdfrajkumarm401
 
Determine whether each series is convergent or divergent..pdf
Determine whether each series is convergent or divergent..pdfDetermine whether each series is convergent or divergent..pdf
Determine whether each series is convergent or divergent..pdfrajkumarm401
 
Describe the primary differences between WEP, WPA, and WPA2 protocol.pdf
Describe the primary differences between WEP, WPA, and WPA2 protocol.pdfDescribe the primary differences between WEP, WPA, and WPA2 protocol.pdf
Describe the primary differences between WEP, WPA, and WPA2 protocol.pdfrajkumarm401
 
Complete the provided partial C++ Linked List program. Main.cpp is g.pdf
Complete the provided partial C++ Linked List program. Main.cpp is g.pdfComplete the provided partial C++ Linked List program. Main.cpp is g.pdf
Complete the provided partial C++ Linked List program. Main.cpp is g.pdfrajkumarm401
 
Click the desktop shortcut icon that you created in this module, and .pdf
Click the desktop shortcut icon that you created in this module, and .pdfClick the desktop shortcut icon that you created in this module, and .pdf
Click the desktop shortcut icon that you created in this module, and .pdfrajkumarm401
 
YOU DO IT 4! create an named YouDolt 4 and save it in the vB 2015Chap.pdf
YOU DO IT 4! create an named YouDolt 4 and save it in the vB 2015Chap.pdfYOU DO IT 4! create an named YouDolt 4 and save it in the vB 2015Chap.pdf
YOU DO IT 4! create an named YouDolt 4 and save it in the vB 2015Chap.pdfrajkumarm401
 
What was the causes of the Vietnam war What was the causes of .pdf
What was the causes of the Vietnam war What was the causes of .pdfWhat was the causes of the Vietnam war What was the causes of .pdf
What was the causes of the Vietnam war What was the causes of .pdfrajkumarm401
 
Transactions costs are zero in financial markets. zero in financial i.pdf
Transactions costs are zero in financial markets. zero in financial i.pdfTransactions costs are zero in financial markets. zero in financial i.pdf
Transactions costs are zero in financial markets. zero in financial i.pdfrajkumarm401
 
This is for an homework assignment using Java code. Here is the home.pdf
This is for an homework assignment using Java code. Here is the home.pdfThis is for an homework assignment using Java code. Here is the home.pdf
This is for an homework assignment using Java code. Here is the home.pdfrajkumarm401
 
Question 34 (1 point) D A check is 1) not money because it is not off.pdf
Question 34 (1 point) D A check is 1) not money because it is not off.pdfQuestion 34 (1 point) D A check is 1) not money because it is not off.pdf
Question 34 (1 point) D A check is 1) not money because it is not off.pdfrajkumarm401
 
Program Structure declare ButtonState Global variable holding statu.pdf
Program Structure declare ButtonState Global variable holding statu.pdfProgram Structure declare ButtonState Global variable holding statu.pdf
Program Structure declare ButtonState Global variable holding statu.pdfrajkumarm401
 
Need help in assembly. Thank you Implement the following expression .pdf
Need help in assembly. Thank you Implement the following expression .pdfNeed help in assembly. Thank you Implement the following expression .pdf
Need help in assembly. Thank you Implement the following expression .pdfrajkumarm401
 
mine whether the following s are true or false False A parabola has e.pdf
mine whether the following s are true or false False A parabola has e.pdfmine whether the following s are true or false False A parabola has e.pdf
mine whether the following s are true or false False A parabola has e.pdfrajkumarm401
 
Locate an article where the technique of Polymerase chain reaction (.pdf
Locate an article where the technique of Polymerase chain reaction (.pdfLocate an article where the technique of Polymerase chain reaction (.pdf
Locate an article where the technique of Polymerase chain reaction (.pdfrajkumarm401
 

More from rajkumarm401 (20)

Having issues with passing my values through different functions aft.pdf
Having issues with passing my values through different functions aft.pdfHaving issues with passing my values through different functions aft.pdf
Having issues with passing my values through different functions aft.pdf
 
Explain the characterstic of web service techonolgy.SolutionT.pdf
Explain the characterstic of web service techonolgy.SolutionT.pdfExplain the characterstic of web service techonolgy.SolutionT.pdf
Explain the characterstic of web service techonolgy.SolutionT.pdf
 
Executive Summary i. Provide a succinct overview of your strategic p.pdf
Executive Summary i. Provide a succinct overview of your strategic p.pdfExecutive Summary i. Provide a succinct overview of your strategic p.pdf
Executive Summary i. Provide a succinct overview of your strategic p.pdf
 
eee230 Instruction details Answer the following questions in a typed.pdf
eee230 Instruction details Answer the following questions in a typed.pdfeee230 Instruction details Answer the following questions in a typed.pdf
eee230 Instruction details Answer the following questions in a typed.pdf
 
Essay questionPorter Combining business strategy What is itmeani.pdf
Essay questionPorter Combining business strategy What is itmeani.pdfEssay questionPorter Combining business strategy What is itmeani.pdf
Essay questionPorter Combining business strategy What is itmeani.pdf
 
During oogenesis, will the genotypes of the first and second polar b.pdf
During oogenesis, will the genotypes of the first and second polar b.pdfDuring oogenesis, will the genotypes of the first and second polar b.pdf
During oogenesis, will the genotypes of the first and second polar b.pdf
 
Does personal information available on the Internet make an employee.pdf
Does personal information available on the Internet make an employee.pdfDoes personal information available on the Internet make an employee.pdf
Does personal information available on the Internet make an employee.pdf
 
Determine whether each series is convergent or divergent..pdf
Determine whether each series is convergent or divergent..pdfDetermine whether each series is convergent or divergent..pdf
Determine whether each series is convergent or divergent..pdf
 
Describe the primary differences between WEP, WPA, and WPA2 protocol.pdf
Describe the primary differences between WEP, WPA, and WPA2 protocol.pdfDescribe the primary differences between WEP, WPA, and WPA2 protocol.pdf
Describe the primary differences between WEP, WPA, and WPA2 protocol.pdf
 
Complete the provided partial C++ Linked List program. Main.cpp is g.pdf
Complete the provided partial C++ Linked List program. Main.cpp is g.pdfComplete the provided partial C++ Linked List program. Main.cpp is g.pdf
Complete the provided partial C++ Linked List program. Main.cpp is g.pdf
 
Click the desktop shortcut icon that you created in this module, and .pdf
Click the desktop shortcut icon that you created in this module, and .pdfClick the desktop shortcut icon that you created in this module, and .pdf
Click the desktop shortcut icon that you created in this module, and .pdf
 
YOU DO IT 4! create an named YouDolt 4 and save it in the vB 2015Chap.pdf
YOU DO IT 4! create an named YouDolt 4 and save it in the vB 2015Chap.pdfYOU DO IT 4! create an named YouDolt 4 and save it in the vB 2015Chap.pdf
YOU DO IT 4! create an named YouDolt 4 and save it in the vB 2015Chap.pdf
 
What was the causes of the Vietnam war What was the causes of .pdf
What was the causes of the Vietnam war What was the causes of .pdfWhat was the causes of the Vietnam war What was the causes of .pdf
What was the causes of the Vietnam war What was the causes of .pdf
 
Transactions costs are zero in financial markets. zero in financial i.pdf
Transactions costs are zero in financial markets. zero in financial i.pdfTransactions costs are zero in financial markets. zero in financial i.pdf
Transactions costs are zero in financial markets. zero in financial i.pdf
 
This is for an homework assignment using Java code. Here is the home.pdf
This is for an homework assignment using Java code. Here is the home.pdfThis is for an homework assignment using Java code. Here is the home.pdf
This is for an homework assignment using Java code. Here is the home.pdf
 
Question 34 (1 point) D A check is 1) not money because it is not off.pdf
Question 34 (1 point) D A check is 1) not money because it is not off.pdfQuestion 34 (1 point) D A check is 1) not money because it is not off.pdf
Question 34 (1 point) D A check is 1) not money because it is not off.pdf
 
Program Structure declare ButtonState Global variable holding statu.pdf
Program Structure declare ButtonState Global variable holding statu.pdfProgram Structure declare ButtonState Global variable holding statu.pdf
Program Structure declare ButtonState Global variable holding statu.pdf
 
Need help in assembly. Thank you Implement the following expression .pdf
Need help in assembly. Thank you Implement the following expression .pdfNeed help in assembly. Thank you Implement the following expression .pdf
Need help in assembly. Thank you Implement the following expression .pdf
 
mine whether the following s are true or false False A parabola has e.pdf
mine whether the following s are true or false False A parabola has e.pdfmine whether the following s are true or false False A parabola has e.pdf
mine whether the following s are true or false False A parabola has e.pdf
 
Locate an article where the technique of Polymerase chain reaction (.pdf
Locate an article where the technique of Polymerase chain reaction (.pdfLocate an article where the technique of Polymerase chain reaction (.pdf
Locate an article where the technique of Polymerase chain reaction (.pdf
 

Recently uploaded

Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxAnaBeatriceAblay2
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 

Recently uploaded (20)

Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 

Create a 10x10 Minesweeper Game in Java

  • 1. Objective: Create a graphical game of minesweeper IN JAVA. The board should consist of 10x10 buttons. Of the 100 spaces there should be at least 20 randomly placed mines. If the button is clicked and it is not a mine then it clears itself. If a space has been cleared then it should indicate how many of its eight neighbors are mines. If a space is clicked and it is a mine then the game is over and the player is asked if they want to play again. Finally, if all the non-mine spaces have been clicked then the player is prompted that they won. Solution 2 files need to be made. First Game.Java which will have the gaming logic and User Interface and Main.Java which will have have the main method and object of Game.java Number of rows and cols is customizable so user can change that as and when needed. import java.awt.*; import java.awt.Dimension; import javax.swing.*; import java.awt.event.*; import java.util.*; public class Game 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;
  • 2. Point framelocation; Stopwatch sw; MouseHendeler mh; Point p; Game() { super("Game"); 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) {
  • 3. 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();
  • 4. 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.createEmptyBorde r(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();
  • 5. 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();
  • 6. 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();
  • 7. Customizetion cus = new Customizetion(); reset(); panelb.revalidate(); panelb.repaint(); //Game ob=new Game(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); }
  • 8. 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') {
  • 9. 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); }
  • 10. 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;
  • 11. 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'; }
  • 12. } } } 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");
  • 13. } 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 {
  • 14. 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");
  • 15. 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()); //Game ms=new Game(); 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) {
  • 16. 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; } } } }