SlideShare a Scribd company logo
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 ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdf (20)

PPT
J2 me 07_5
vanliemtb
 
PDF
package com.tictactoe; public class Main {public void play() {.pdf
info430661
 
PDF
Mouse and Cat Game In C++
Programming Homework Help
 
PDF
The Ring programming language version 1.9 book - Part 60 of 210
Mahmoud Samir Fayed
 
PDF
Flappy bird
SantiagoYepesSerna
 
PPTX
Making Games in JavaScript
Sam Cartwright
 
PDF
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
aoneonlinestore1
 
PDF
The Ring programming language version 1.5.3 book - Part 79 of 184
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.10 book - Part 71 of 212
Mahmoud Samir Fayed
 
PDF
Cocos2dx 7.1-7.2
Kyungryul KIM
 
PDF
The Ring programming language version 1.8 book - Part 56 of 202
Mahmoud Samir Fayed
 
PDF
Why am I getting an out of memory error and no window of my .pdf
aakarcreations1
 
PDF
import java.util.Scanner;public class Main {    public static in.pdf
anwarsadath111
 
DOC
Ocr code
wi7sonjoseph
 
PDF
The Ring programming language version 1.10 book - Part 70 of 212
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.3 book - Part 52 of 88
Mahmoud Samir Fayed
 
PPT
Mobile Game and Application with J2ME
Jenchoke Tachagomain
 
PPT
Mobile Game and Application with J2ME - Collision Detection
Jenchoke Tachagomain
 
PDF
public interface Game Note interface in place of class { .pdf
kavithaarp
 
PDF
Of class2
Janet Huang
 
J2 me 07_5
vanliemtb
 
package com.tictactoe; public class Main {public void play() {.pdf
info430661
 
Mouse and Cat Game In C++
Programming Homework Help
 
The Ring programming language version 1.9 book - Part 60 of 210
Mahmoud Samir Fayed
 
Flappy bird
SantiagoYepesSerna
 
Making Games in JavaScript
Sam Cartwright
 
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
aoneonlinestore1
 
The Ring programming language version 1.5.3 book - Part 79 of 184
Mahmoud Samir Fayed
 
The Ring programming language version 1.10 book - Part 71 of 212
Mahmoud Samir Fayed
 
Cocos2dx 7.1-7.2
Kyungryul KIM
 
The Ring programming language version 1.8 book - Part 56 of 202
Mahmoud Samir Fayed
 
Why am I getting an out of memory error and no window of my .pdf
aakarcreations1
 
import java.util.Scanner;public class Main {    public static in.pdf
anwarsadath111
 
Ocr code
wi7sonjoseph
 
The Ring programming language version 1.10 book - Part 70 of 212
Mahmoud Samir Fayed
 
The Ring programming language version 1.3 book - Part 52 of 88
Mahmoud Samir Fayed
 
Mobile Game and Application with J2ME
Jenchoke Tachagomain
 
Mobile Game and Application with J2ME - Collision Detection
Jenchoke Tachagomain
 
public interface Game Note interface in place of class { .pdf
kavithaarp
 
Of class2
Janet Huang
 

More from rajkumarm401 (20)

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

Recently uploaded (20)

PPTX
Views on Education of Indian Thinkers Mahatma Gandhi.pptx
ShrutiMahanta1
 
PPTX
PPT on the Development of Education in the Victorian England
Beena E S
 
PPTX
Latest Features in Odoo 18 - Odoo slides
Celine George
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PPTX
How to Manage Access Rights & User Types in Odoo 18
Celine George
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PPTX
Optimizing Cancer Screening With MCED Technologies: From Science to Practical...
i3 Health
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PPTX
SCHOOL-BASED SEXUAL HARASSMENT PREVENTION AND RESPONSE WORKSHOP
komlalokoe
 
PPTX
Optimizing Cancer Screening With MCED Technologies: From Science to Practical...
i3 Health
 
PPTX
How to Configure Storno Accounting in Odoo 18 Accounting
Celine George
 
PPTX
LEGAL ASPECTS OF PSYCHIATRUC NURSING.pptx
PoojaSen20
 
PDF
BÀI TẬP BỔ TRỢ THEO LESSON TIẾNG ANH - I-LEARN SMART WORLD 7 - CẢ NĂM - CÓ ĐÁ...
Nguyen Thanh Tu Collection
 
PDF
1, 2, 3… E MAIS UM CICLO CHEGA AO FIM!.pdf
Colégio Santa Teresinha
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PDF
Zoology (Animal Physiology) practical Manual
raviralanaresh2
 
PDF
IMP NAAC REFORMS 2024 - 10 Attributes.pdf
BHARTIWADEKAR
 
PPTX
HEAD INJURY IN CHILDREN: NURSING MANAGEMENGT.pptx
PRADEEP ABOTHU
 
PPT
digestive system for Pharm d I year HAP
rekhapositivity
 
PPTX
How to Configure Prepayments in Odoo 18 Sales
Celine George
 
Views on Education of Indian Thinkers Mahatma Gandhi.pptx
ShrutiMahanta1
 
PPT on the Development of Education in the Victorian England
Beena E S
 
Latest Features in Odoo 18 - Odoo slides
Celine George
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
How to Manage Access Rights & User Types in Odoo 18
Celine George
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
Optimizing Cancer Screening With MCED Technologies: From Science to Practical...
i3 Health
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
SCHOOL-BASED SEXUAL HARASSMENT PREVENTION AND RESPONSE WORKSHOP
komlalokoe
 
Optimizing Cancer Screening With MCED Technologies: From Science to Practical...
i3 Health
 
How to Configure Storno Accounting in Odoo 18 Accounting
Celine George
 
LEGAL ASPECTS OF PSYCHIATRUC NURSING.pptx
PoojaSen20
 
BÀI TẬP BỔ TRỢ THEO LESSON TIẾNG ANH - I-LEARN SMART WORLD 7 - CẢ NĂM - CÓ ĐÁ...
Nguyen Thanh Tu Collection
 
1, 2, 3… E MAIS UM CICLO CHEGA AO FIM!.pdf
Colégio Santa Teresinha
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
Zoology (Animal Physiology) practical Manual
raviralanaresh2
 
IMP NAAC REFORMS 2024 - 10 Attributes.pdf
BHARTIWADEKAR
 
HEAD INJURY IN CHILDREN: NURSING MANAGEMENGT.pptx
PRADEEP ABOTHU
 
digestive system for Pharm d I year HAP
rekhapositivity
 
How to Configure Prepayments in Odoo 18 Sales
Celine George
 
Ad

ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdf

  • 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; } } } }