A minesweeper game written with knowledge of the Java AWT interface
Detailed annotations in the code
Package Com.langsin.saolei;
Import Java.awt.Color;
Import Java.awt.Font;
Import Java.awt.Frame;
Import Java.awt.Graphics;
Import java.awt.GridLayout;
Import Java.awt.Image;
Import java.awt.Insets;
Import Java.awt.Label;
Import Java.awt.Menu;
Import Java.awt.MenuBar;
Import Java.awt.MenuItem;
Import Java.awt.MenuShortcut;
Import Java.awt.TextArea;
Import java.awt.event.ActionEvent;
Import Java.awt.event.ActionListener;
Import java.awt.event.KeyEvent;
Import Java.awt.event.MouseAdapter;
Import java.awt.event.MouseEvent;
Import Java.awt.event.WindowAdapter;
Import java.awt.event.WindowEvent;
Import Java.awt.image.BufferedImage;
Import Java.io.BufferedReader;
Import Java.io.File;
Import Java.io.FileReader;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import java.util.ArrayList;
Import java.util.List;
Import Java.util.Random;
Import Javax.imageio.ImageIO;
Import Javax.swing.ImageIcon;
Import Javax.swing.JOptionPane;
Import Javax.swing.JPanel;
public class Saolei extends Frame implements ActionListener {
First define the number of horizontal buttons and the vertical button
private static int with = 10;
private static int LENG = 10;
Define the number of mines
private static int mines_count = 10;
Define the number of flags
private static int red_count = 10;
Define a random class
private static random random = new random ();
Define a two-dimensional array
private static bomb[][] jb = new Bomb[with][leng];
Decide whether to end
Private Boolean flag = false;
Determine if success is not successful by default
Private Boolean sucess = false;
Staging the contents of a sucess.txt with a collection
Private list<string> List = new arraylist<string> ();
Staging game time with a collection
Private list<string> listtime = new arraylist<string> ();
StringBuffer buffer = new StringBuffer ();
Define a panel member variable
Private JPanel JP;
Threads that record time
Private Runnable Runnable;
Used Time
private int usedtime = 0;
Define two tag times and flags
Private Label time, Redflag;
/*
* Detect if there is thunder around a point, the coordinates of the surrounding points can be calculated by the array
*/
Private int[][] mv = {{1, 0}, {-1, 0}, {0, 1}, {0,-1}, {1, 1},
{-1,-1}, {1,-1}, {-1, 1}};
Class through the constructor.
Public Saolei () throws Exception {
Super ("Minesweeper");
Absolute Layout Manager
This.setlayout (NULL);
Set icon
This.seticonimage (Imageio.read (New File ("./image/icon. jpg"));
Set size
This.setbounds (100, 100, 500, 500);
This.addwindowlistener (New Windowadapter () {
@Override
public void windowclosing (WindowEvent e) {
System.exit (0);
}
});
SetMenu ();
Intmine ();
Intbottom ();
This.setresizable (FALSE);
This.setvisible (TRUE);
}
Setting the Initialization menu
public void SetMenu () {
Menu bar
MenuBar Menbar = new MenuBar ();
menu item Game
Menu game = new Menu ("Game (G)");
menu item Game Components new games
MenuItem-newgame = new MenuItem ("New Game");
Game New Start
Newgame.addactionlistener (new ActionListener () {
@Override
public void actionperformed (ActionEvent e) {
Call the method of restarting the game
Resetgame ();
}
});
Game.add (Newgame);
menu item Game Component Change appearance
MenuItem change = new MenuItem ("alter appearance");
Change.addactionlistener (new ActionListener () {
@Override
public void actionperformed (ActionEvent e) {
for (int i = 0; i < with; i++) {
for (int j = 0; J < LENG; J + +) {
if (!jb[i][j].isisclicked () && jb[i][j].isenabled ()) {
Jb[i][j].setbackground (Color.Blue);
} else {
Jb[i][j].setbackground (Color.White);
}
}
}
}
});
Game.add (change);
Add a horizontal line
Game.addseparator ();
Game.add (New MenuItem ("-"));
Component Exit for menu item game
MenuItem exit = new MenuItem ("Exit",
New Menushortcut (KEYEVENT.VK_A, true));
Exit.addactionlistener (new ActionListener () {
@Override
public void actionperformed (ActionEvent e) {
TODO auto-generated Method Stub
System.exit (0);
}
});
Game.add (exit);
Menbar.add (game);
menu item Help
Menu Tj = new Menu ("Statistic (T)");
Component statistics for menu item games
MenuItem record = new MenuItem ("View Statistics");
Record the game's success and failure in two txt text
Record.addactionlistener (new ActionListener () {
@Override
public void actionperformed (ActionEvent e) {
try {
Tongji ();
} catch (Exception E1) {
TODO auto-generated Catch block
E1.printstacktrace ();
}
}
});
Tj.add (record);
Menbar.add (TJ);
Add a menu bar
This.setmenubar (Menbar);
}
Initialize bottom of
private void Intbottom () {
Create two labels one is the time one is timing
Label LAB1 = new label ("Time");
Lab1.setfont (New Font ("Arial", Font.Bold, 15));
Lab1.setforeground (Color.Blue);
Lab1.setbounds (80, 430, 35, 35);
This.add (LAB1);
Time = new Label ("0");
Time.setfont (New Font ("Arial", Font.plain, 15));
Time.setbounds (140, 435, 50, 25);
This.add (time);
One is to mark the number of small red flags
Label LAB2 = new label ("banner");
Lab2.setfont (New Font ("Arial", Font.Bold, 15));
Lab2.setforeground (Color.Blue);
Lab2.setbounds (300, 430, 35, 35);
This.add (LAB2);
Redflag = new Label ("10");
Redflag.setfont (New Font ("Arial", Font.plain, 15));
Redflag.setbounds (350, 435, 50, 25);
This.add (Redflag);
Through the interface to achieve
runnable = new Runnable () {
public void Run () {
while (true) {
Whether to end
if (flag) {
Break
}
try {
Sleep 1s
Thread.Sleep (1000);
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
Used Time +1
usedtime++;
Time.settext (string.valueof (usedtime));
}
}
};
Start thread
New Thread (runnable). Start ();
}
Initialize the minefield (Use a button to act as a mine panel to add a button to the panel)
private void Intmine () {
Place the button on the panel
JP = new JPanel ();
The layout manager for the panel is the Grid layout manager
Jp.setlayout (New GridLayout (with, LENG, 0, 0));
Setting the location of the panel
Jp.setbounds (75, 70, 350, 350);
Makemines (TRUE);
This.add (JP);
}
Randomly arranged mined area to reset mined area
private void Makemines (Boolean newflag) {
Put the button on the panel and set the initial button properties
for (int i = 0; i < LENG; i++) {
for (int j = 0, J < with; J + +) {
if (Newflag) {
Record the location
JB[I][J] = new Bomb (i, j);
Jp.add (Jb[i][j]);
Sets the position of the button where the blank number between the button and the label is located
Jb[i][j].setmargin (New Insets (0, 0, 0, 0));
Jb[i][j].addactionlistener (this);
Mouse Click event mouse Right click
Jb[i][j].addmouselistener (New Mouseadapter () {
@Override
public void mouseclicked (MouseEvent e) {
Object obj = E.getsource ();
E.ismetadown () Detect right mouse button click
if (E.ismetadown () && obj instanceof Bomb) {
Forcing type conversions
Bomb Bomb = (Bomb) obj;
The number of flags is greater than or equal to 0
if (bomb.isenabled () && red_count >= 0) {
Define a number to determine the state
Right click to change to 1 red flag State two to 2? Number status
int num = (Bomb.getbombflag () + 1)% 3;
Switch (num) {
Case 0:
Initial state
Bomb.seticon (NULL);
Break
Case 1:
red_count--;
Buffer Picture Object
BufferedImage bf1 = new BufferedImage (
35, 35,
BUFFEREDIMAGE.TYPE_INT_RGB);
By caching the picture object, get the Paintbrush tool object graphics and modify the cached picture.
Graphics grap = Bf1.getgraphics ();
Read this picture first.
Image Image;
try {
Image = Imageio.read (New File (
"./image/red flag. jpg");
Then change it with the Brush object to zoom the image
Grap.drawimage (image, 0, 0, 35, 35,
NULL);
Bomb.seticon (New ImageIcon (BF1));
} catch (IOException E2) {
TODO auto-generated Catch block
E2.printstacktrace ();
}
Break
Case 2:
red_count++;
Buffer Picture Object
BufferedImage BF2 = new BufferedImage (
35, 35,
BUFFEREDIMAGE.TYPE_INT_RGB);
By caching the picture object, get the Paintbrush tool object graphics and modify the cached picture.
Graphics grap2 = Bf2.getgraphics ();
Read this picture first.
Image Image2;
try {
Then change it with the Brush object to zoom the image
Image2 = Imageio.read (New File (
"./image/question mark. jpg"));
Grap2.drawimage (image2, 0, 0, 35,
, null);
Bomb.seticon (New ImageIcon (BF2));
} catch (IOException E1) {
TODO auto-generated Catch block
E1.printstacktrace ();
}
Break
Default
Break
}
Redflag.settext (string.valueof (Red_count));
Change state
Bomb.setbombflag (num);
try {
Checksuccess ();
} catch (Exception E1) {
TODO auto-generated Catch block
E1.printstacktrace ();
}
}
}
}
});
} else {
Jb[i][j].seticon (NULL);
Jb[i][j].setenabled (TRUE);
The default is no click
Jb[i][j].setisclicked (FALSE);
Jb[i][j].settext ("");
The default is no Thunder
Jb[i][j].setbomb (FALSE);
Default initial state value is 0
Jb[i][j].setbombflag (0);
}
}
}
Number of mines
int i = 0;
Defining coordinates
int x, y;
while (I < 10) {
x = Random.nextint (with);
y = Random.nextint (LENG);
To determine if there's thunder in this place, not by default.
if (!jb[x][y].isbomb ()) {
Set to have Thunder
Jb[x][y].setbomb (TRUE);
To see if there are duplicate
View coordinates where y corresponds to column x corresponds to row from 0-9
SYSTEM.OUT.PRINTLN (x + "" + y);
i++;
}
}
}
To determine the progress of the game by clicking on the event
Click events
@Override
public void actionperformed (ActionEvent e) {
Object obj = E.getsource ();
if (obj instanceof Bomb) {
Bomb bs = (Bomb) obj;
If the resulting status is 1 that is the Red flag end Click event
if (bs.getbombflag () = = 1) {
Return
}
If the resulting state is 2 that is "? ”
else if (bs.getbombflag () = = 2) {
Click to remove the question mark
Bs.setisclicked (TRUE);
Bs.seticon (NULL);
}
If the point is ray,
if (Bs.isbomb ()) {
Buffer Picture Object
BufferedImage bf1 = new BufferedImage (35, 35,
BUFFEREDIMAGE.TYPE_INT_RGB);
By caching the picture object, get the Paintbrush tool object graphics and modify the cached picture.
Graphics grap = Bf1.getgraphics ();
Read this picture first.
Image Image;
try {
Image = Imageio.read (new File ("./image/mine. png"));
Then change it with the Brush object to zoom the image
Grap.drawimage (image, 0, 0, +, +, NULL);
Set the picture to Thunder
Bs.seticon (New ImageIcon (BF1));
} catch (IOException E2) {
TODO auto-generated Catch block
E2.printstacktrace ();
}
Game Over
Flag = true;
Show All the Thunder
try {
Showmine ();
} catch (Exception E1) {
TODO auto-generated Catch block
E1.printstacktrace ();
}
Pop Up a window dialog box to show end of game Click event
Joptionpane.showmessagedialog (This, "Minesweeper failed!");
Return
}
No point to Reith.
Determine if lightning is used to determine the condition of the surrounding thunder by an algorithm
Judge (Bs.getnum_x (), bs.getnum_y ());
}
}
Start the game again
private void Resetgame () {
Flag = true;
Red_count = 10;
Time.settext ("0");
Usedtime = 0;
Redflag.settext ("10");
Makemines (FALSE);
Set the game's appearance to initial
for (int i = 0; i < with; i++) {
for (int j = 0; J < LENG; J + +) {
Jb[i][j].setbackground (NULL);
}
}
try {
Thread.Sleep (1000);
} catch (Interruptedexception E1) {
TODO auto-generated Catch block
E1.printstacktrace ();
}
New Thread (runnable). Start ();
Flag = false;
}
If point to Thunder, the game is over show all Ray
Show All the Thunder methods
private void Showmine () throws Exception {
for (int i = 0; i < with; i++) {
for (int j = 0; J < LENG; J + +) {
if (Jb[i][j].isbomb ()) {
Buffer Picture Object
BufferedImage bf1 = new BufferedImage (35, 35,
BUFFEREDIMAGE.TYPE_INT_RGB);
By caching the picture object, get the Paintbrush tool object graphics and modify the cached picture.
Graphics grap = Bf1.getgraphics ();
Read this picture first.
Image image = Imageio.read (new File ("./image/mine. png"));
Then change it with the Brush object to zoom the image
Grap.drawimage (image, 0, 0, +, +, NULL);
Jb[i][j].seticon (New ImageIcon (BF1));
}
}
}
}
//Determine success
private void Checksuccess () throws Exception {
int count = 0;
for (int i = 0, i < LENG; i++) {
for (int j = 0, J < with; J + +) {
//If it is ray and this place has a red flag
if (Jb[i][j].isbomb () & amp;& Jb[i][j].getbombflag () = = 1) {
//to accumulate
count++;
}
}
}
if (count = = Mines_count) {
flag = true;
Joptionpane.showmessagedialog (This, "Congratulations, Victory!") ");
sucess = true;
String TM = Time.gettext ();
Listtime.add (tm);
Writesucess (sucess);
}
}
//Determine if there is a ray
private void judge (int x, int y) {
//settings (x, y) This position has been clicked to get this position
jb[x][y].setisclicked (true);
When clicked, set the background to white
Jb[x][y].setbackground (color.white);
The point over setting is not clickable click over is set to unavailable
Jb[x][y].setenabled (false);
Setting the relative initial position of this point of click Is (0,0) setting the number of the initial surrounding thunder is 0
int sx = 0;
int sy = 0;
int minenumber = 0;
for (int i = 0; i < mv.length; i++) {
SX = x + mv[i][0];
Sy = y + mv[i][1];
//Ensure that all coordinate points are on the panel to determine which buttons have not been clicked
if (SX >= 0 && SX < with && sy >= 0 && Sy < LENG {
if (Jb[sx][sy].isbomb ()) {
////If it is ray, the number of the
//display is incremented (x, y) the number of mines around this position
minenumber++;
}
}
}
//via Recursive implementation
if (Minenumber = = 0) {
for (int i = 0; i < mv.length; i++) {
SX = x + mv[i][0];
Sy = y + mv[i][1];
//Ensure that all coordinates correspond to one button
if (SX >= 0 && SX < LENG && sy >= 0 && Sy < LENG
&& ;!jb[sx][sy].isisclicked ()) {
Judge (SX, SY);
}
}
} else {
Jb[x][y].setfont (New Font ("Arial", Font.Bold, 12));
Jb[x][y].settext (string.valueof (Minenumber));
}
}
Only if it succeeds.
Write a method to write the success record to the Sucess.txt file
private void Writesucess (Boolean sucess) throws Exception {
int snum = 0;
If there are no elements in the list
Readsucess ();
if (List.isEmpty ()) {
PrintWriter pw = new PrintWriter (New File ("./sucess.txt"));
Pw.println ("Game results \ T game time");
Buffer.append ("Game success" + "\ T" + listtime.get (snum));
Pw.println (Buffer.tostring ());
Pw.close ();
snum++;
} else {
PrintWriter pw = new PrintWriter (New File ("./sucess.txt"));
for (int i = 0; i < list.size (); i++) {
Pw.println (List.get (i));
}
Buffer.append ("Game success" + "\ T" + listtime.get (snum));
Pw.println (Buffer.tostring ());
Pw.close ();
snum++;
}
}
private void Readsucess () throws Exception {
BufferedReader br = new BufferedReader (New FileReader ("./sucess.txt"));
String line = null;
while (line = Br.readline ()) = null) {
List.add (line);
}
Br.close ();
}
Create a new window
private void Tongji () throws Exception {
Final frame frame = new Frame ("statistical information");
Frame.setbounds (100, 100, 300, 300);
TextArea ta = new TextArea ();
Ta.setfont (New Font ("Arial", Font.Bold, 15));
Ta.setforeground (Color.Blue);
BufferedReader bf = new BufferedReader (New FileReader (
"./sucess.txt")));
String line = null;
StringBuffer buf = new StringBuffer ();
while (line = Bf.readline ()) = null) {
Buf.append (line + "\ n");
}
Ta.settext (Buf.tostring ());
Bf.close ();
Frame.add (TA);
Frame.addwindowlistener (New Windowadapter () {
@Override
public void windowclosing (WindowEvent e) {
Frame.dispose ();
}
});
Frame.setresizable (FALSE);
Frame.setvisible (TRUE);
}
Program execution
public static void Main (string[] args) throws Exception {
New Saolei ();
}
}
Java AWT Project Development