Swing's mine-sweeping experience is for your reference. The specific content is as follows
Recently, I made a small game after studying swing: Minesweeping
1. Preliminary design
2. Implementation
In fact, the core of completing this game lies in manipulating the array. The main code below is Main.java:
package first;import java.awt.Color;import java.awt.Dimension;import java.awt.Font;import java.awt.GridLayout;import java.awt.Image;import java.awt.Toolkit;import java.awt.datatransfer.Clipboard;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.net.ServerSocket;import java.net.Socket;import java.sql.DriverManager;import java.sql.SQLException;import java.util.HashSet;import java.util.Set;import java.util.UUID;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JOptionPane;import javax.swing.Timer;import com.mysql.jdbc.Connection;import com.mysql.jdbc.Statement;public class Main extends JFrame implements ActionListener, MouseListener { /** * Yijian*/ private static final long serialVersionUID = 1L; // Early parameter declaration JMenuItem JmiNew, JmiSave, JmiOpen, JmiExit, Jmichuji, Jmizhongji, Jmigaoji, JmishowInFo, JmiZiding; Toolkit toolKit = Toolkit.getDefaultToolkit(); // Get the default toolkit. Clipboard clipboard = toolKit.getSystemClipboard();// Get an instance of the system Calibrate // as an interface to the clipboard tool provided by the native platform. //Two icons ImageIcon icon = new ImageIcon("G://eclipse-workspace//classTest_ThunderGame//mine.png"); ImageIcon icon1 = new ImageIcon("G://eclipse-workspace//classTest_ThunderGame//flag.png"); private static int NUM = 1;// This NUM is a thunder number, you can write a program to change // private static final int SNUM = 9;// This SNUM is the tile number of minesweeping, you can write a program to change private JButton[][] jb; private int[][] map; boolean[][] flags; boolean[][] flag; int coutTime; // Declare the connection object Connection con; // Driver name String driver = "com.mysql.jdbc.Driver"; // url: Point to the database name to be accessed String url = "jdbc:mysql://localhost:3306/testsql3"; // MySQL configured user String user = "root"; // Password String password = "huang"; public Main(int SNUM, int Mines) {// Main interface constructor setTitle("mine-sweeping"); // Initial number of thunder NUM = Mines; JMenuBar greenBar = new JMenuBar();// Menu container greenBar.setOpaque(true); greenBar.setBackground(new Color(250, 250, 250)); greenBar.setPreferredSize(new Dimension(800, 28)); greenBar.setFont(new Font(Font.DIALOG_INPUT, Font.ITALIC, 16)); // Menu JMenu fileMenu1 = new JMenu("Game"); JMenu fileMenu2 = new JMenu("Difficulty"); JMenu fileMenu3 = new JMenu("Help:"); greenBar.add(fileMenu1); greenBar.add(fileMenu2); greenBar.add(JmishowInFo = fileMenu3); fileMenu1.setFont(new Font(Font.DIALOG_INPUT, Font.ITALIC, 16)); fileMenu2.setFont(new Font(Font.DIALOG_INPUT, Font.ITALIC, 16)); fileMenu3.setFont(new Font(Font.DIALOG_INPUT, Font.ITALIC, 16)); // Menu item fileMenu1.add(JmiNew = new JMenuItem(" New Game")); fileMenu1.add(JmiSave = new JMenuItem(" Ranking Version")); fileMenu1.add(JmiZiding = new JMenuItem(" Custom")); fileMenu1.addSeparator(); fileMenu1.add(JmiExit = new JMenuItem(" Exit")); fileMenu2.add(Jmichuji = new JMenuItem(" Junior")); fileMenu2.add(Jmizhongji = new JMenuItem(" Intermediate")); fileMenu2.add(Jmigaoji = new JMenuItem(" Advanced")); fileMenu3.add(JmishowInFo = new JMenuItem(" Developer Information")); JmiNew.addActionListener(this); JmiExit.addActionListener(this); JmiSave.addActionListener(this); JmiSave.addActionListener(this); JmishowInFo.addActionListener(this); Jmichuji.addActionListener(this); Jmizhongji.addActionListener(this); Jmigaoji.addActionListener(this); JmiZiding.addActionListener(this); JmiZiding.setFont(new Font(Font.DIALOG_INPUT, Font.ITALIC, 16)); JmishowInFo.setFont(new Font(Font.DIALOG_INPUT, Font.ITALIC, 16)); JmiNew.setFont(new Font(Font.DIALOG_INPUT, Font.ITALIC, 16)); JmiSave.setFont(new Font(Font.DIALOG_INPUT, Font.ITALIC, 16)); JmiExit.setFont(new Font(Font.DIALOG_INPUT, Font.ITALIC, 16)); Jmichuji.setFont(new Font(Font.DIALOG_INPUT, Font.ITALIC, 16)); Jmizhongji.setFont(new Font(Font.DIALOG_INPUT, Font.ITALIC, 16)); Jmizhongji.setFont(new Font(Font.DIALOG_INPUT, Font.ITALIC, 16)); Jmigaoji.setFont(new Font(Font.DIALOG_INPUT, Font.ITALIC, 16)); setJMenuBar(greenBar); Image icon = Toolkit.getDefaultToolkit().getImage("G://eclipse-workspace//classTest_ThunderGame//mine.png"); setIconImage(icon); setLayout(new GridLayout(SNUM, SNUM)); jb = new JButton[SNUM][SNUM]; map = new int[SNUM][SNUM]; // Map the buttons into an array flags = new boolean[map.length][map[0].length];// Save the record table flag = new boolean[map.length][map[0].length];// Save the record table int count = 0; // Bleigh while (count < NUM) { int i = (int) (Math.random() * map.length);// hang int j = (int) (Math.random() * map[0].length);// lie if (map[i][j] != '*') { map[i][j] = '*'; count++; } } for (int i = 0; i < SNUM; i++) { for (int j = 0; j < SNUM; j++) { jb[i][j] = new JButton(); jb[i][j].setName(i + "_" + j); jb[i][j].setBackground(new Color(220, 220, 220)); jb[i][j].setFont(new Font(Font.DIALOG_INPUT, Font.ITALIC, 10)); jb[i][j].addActionListener(this); jb[i][j].addMouseListener(this);// Add mouse listener add(jb[i][j]); } } // Timer JLabel ststus = new JLabel(); JLabel Times = new JLabel(); JLabel miao = new JLabel(); add(ststus); add(Times); Times.setText(" 0 "); miao.setText(" seconds"); setTimer(Times); coutTime = 0; ststus.setText(" time: "); greenBar.add(ststus); greenBar.add(Times, RIGHT_ALIGNMENT); greenBar.add(miao, RIGHT_ALIGNMENT); Times.setFont(new Font(Font.DIALOG_INPUT, Font.ITALIC, 16)); ststus.setFont(new Font(Font.DIALOG_INPUT, Font.ITALIC, 16)); miao.setFont(new Font(Font.DIALOG_INPUT, Font.ITALIC, 16)); setSize(700, 700); setLocationRelativeTo(null); setVisible(true); // setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setDefaultCloseOperation(DISPOSE_ON_CLOSE); // Add this line} private void setTimer(JLabel time) {// Time listening final JLabel varTime = time; Timer timeAction = new Timer(1000, new ActionListener() { public void actionPerformed(ActionEvent e) { coutTime++; varTime.setText("" + coutTime); } }); timeAction.start(); } private void showTheClick(int x, int y) {// Click event implementation if (map[x][y] == '*') { jb[x][y].setIcon(icon); showMines(); } else { int count1 = 0; for (int a = x - 1; a <= x + 1; a++) { for (int b = y - 1; b <= y + 1; b++) { if (!(a < 0 || b < 0 || b >= map[0].length || a >= map.length) && map[a][b] == '*') count1++; } } flags[x][y] = true; if (count1 == 0) { jb[x][y].setBackground(Color.white); } else { jb[x][y].setText(count1 + ""); jb[x][y].setFont(new Font(Font.DIALOG_INPUT, Font.ITALIC, 20)); jb[x][y].setBackground(Color.white); } if (count1 == 0) { for (int i = x - 1; i <= x + 1; i++) { for (int j = y - 1; j <= y + 1; j++) { if (!(i < 0 || j < 0 || i >= map.length || j >= map[0].length)) { if (!(i == x && j == y) && flags[i][j] == false) { showTheClick(i, j);// Loop traversal} else { // Prevent repeated access} } } } } } } } } } private void showMines() {// Show all thunders// TODO Auto-generated method stub for (int i = 0; i < map.length; i++) {// Show lightning for (int j = 0; j < map.length; j++) { if (map[i][j] == '*') { jb[i][j].setIcon(icon); // } } } // End the game int b = JOptionPane.showOptionDialog(null, "Oh, it exploded, new game?", "Confirm box", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); if (b == 1) { System.exit(0); } else { setVisible(false); new Main(map.length,NUM); } } @Override public void actionPerformed(ActionEvent e) {// Event listening processing// TODO Auto-generated method stub if (e.getSource() == JmiNew) { setVisible(false); new Main(map.length,NUM); } else if (e.getSource() == JmiSave) { showRange(); } else if (e.getSource() == JmiExit) { System.exit(0); } else if (e.getSource() == JmiZiding) { new SelfMines(); } else if (e.getSource() == Jmichuji) { setVisible(false); new Main(5,3); } else if (e.getSource() == JmishowInFo) { new MyInfo(); } else if (e.getSource() == Jmizhongji) { setVisible(false); new Main(10,10); } else if (e.getSource() == Jmigaoji) { setVisible(false); new Main(20,60); } else { Object obj = e.getSource(); int x, y; String[] strM = ((JButton) obj).getName().split("_"); x = Integer.parseInt(strM[0]); y = Integer.parseInt(strM[1]); showTheClick(x, y); checkSuccess();// Check whether the game is over} } private void showRange() {// Show ranking new Shiyan13(map.length); } private void checkSuccess() {//Determine whether the game is over// TODO Auto-generated method stub int count = map.length * map[0].length; for (int i = 0; i < map.length; i++) { for (int j = 0; j < map[0].length; j++) { if (flags[i][j] == true) count--; } } if (count == NUM) { String uuid = UUID.randomUUID().toString().replaceAll("-", "");//The table uniquely indicates uuid // Link to the database and store time data try { Class.forName(driver); con = (Connection) DriverManager.getConnection(url, user, password); String sql; if (!con.isClosed()) { // ta.setText(""); System.out.println("Connecting database successfully"); // Create object Statement statement = (Statement) con.createStatement(); // if (map.length == 10) { // // SQL statement to be executed sql = "insert into middlerange(userId,userTime) values(/"" + uuid + "/"," + coutTime + ");"; statement.executeUpdate(sql); con.close(); } else if (map.length == 5) { sql = "insert into rang(userid,userTime) values(/"" + uuid + "/"," + coutTime + ");"; statement.executeUpdate(sql); con.close(); } else if (map.length == 20) { sql = "insert into toprange(userId,userTime) values(/"" + uuid + "/"," + coutTime + ");"; statement.executeUpdate(sql); con.close(); }else{ } } catch (ClassNotFoundException e) { // Database driver class exception handling System.out.println("error"); e.printStackTrace(); } catch (SQLException e) { // System.out.println(e); System.err.println("Data not found"); // int i=JOptionPane.showConfirmDialog(null, "The SQL statement you entered is incorrect", // "Not found",JOptionPane.YES_NO_OPTION); } catch (Exception e) { e.printStackTrace(); } finally { System.out.println("Database gets data successfully!"); } int i = JOptionPane.showOptionDialog(null, "Congratulations on passing the test, do you continue?", "Confirm box", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); // ststus.setText("hello"+i); if (i == 1) { System.exit(0); } else { setVisible(false); new Main(map.length,NUM); } } } @Override public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub int c = e.getButton(); if (c == MouseEvent.BUTTON3) { Object obj1 = e.getSource(); int x, y; String[] strM = ((JButton) obj1).getName().split("_"); x = Integer.parseInt(strM[0]); y = Integer.parseInt(strM[1]); if (flag[x][y] == false && flags[x][y] == false) {//Insert the flag jb[x][y].setIcon(icon1); flag[x][y] = true; } else { jb[x][y].setIcon(null); flag[x][y] = false; } } } @Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub }}3. Realize the effect
4. Main functions implementation
(1) Basic mine-sweeping function (random mine-burning, flag insertion)
(2) You can choose difficulty (3) You can customize the number of mines sweeping and the number of grids (4) Set time (5) Add ranking function (storage it in the database according to time)
(6) Packaging it into an exe file (with jre) can be run on multiple platforms. (Use exe4j to package the jar package)
If you need source code, you can leave an email! This is the source code: mine-sweeping game
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.