1. 程式人生 > >使用Java_Swing來實現掃雷小遊戲

使用Java_Swing來實現掃雷小遊戲

swing設計掃雷心得

最近學習swing學習之餘做了一個小遊戲–掃雷

1,前期設計

這裡寫圖片描述

2,實現

其實完成這個遊戲的核心就在於對陣列的操縱,下面貼主要程式碼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 { /** * 義建 */ private static final long serialVersionUID = 1L; // 前期引數宣告 JMenuItem JmiNew, JmiSave, JmiOpen, JmiExit, Jmichuji, Jmizhongji, Jmigaoji, JmishowInFo, JmiZiding; Toolkit toolKit = Toolkit.getDefaultToolkit(); // 獲取預設工具包。 Clipboard clipboard = toolKit.getSystemClipboard();// 獲取系統 Calibrate // 的一個例項,作為本機平臺提供的剪貼簿工具的介面。 //兩個圖示 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;// 這個NUM是雷數,可以編寫一個程式來改變 // private static final int SNUM = 9;// 這個SNUM是掃雷的格數,可以編寫一個程式來改變 private JButton[][] jb; private int[][] map; boolean[][] flags; boolean[][] flag; int coutTime; // 宣告connection物件 Connection con; // 驅動程式名 String driver = "com.mysql.jdbc.Driver"; // url:指向要訪問的資料庫名 String url = "jdbc:mysql://localhost:3306/testsql3"; // mysql配置的使用者名稱 String user = "root"; // 密碼 String password = "huang"; public Main(int SNUM, int Mines) {// 主要介面建構函式 setTitle("掃雷"); // 初始雷數量 NUM = Mines; JMenuBar greenBar = new JMenuBar();// 選單容器 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)); // 選單 JMenu fileMenu1 = new JMenu("遊戲"); JMenu fileMenu2 = new JMenu("難度"); JMenu fileMenu3 = new JMenu("幫助:"); 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)); // 選單項 fileMenu1.add(JmiNew = new JMenuItem(" 新遊戲 ")); fileMenu1.add(JmiSave = new JMenuItem(" 排行版 ")); fileMenu1.add(JmiZiding = new JMenuItem(" 自定義 ")); fileMenu1.addSeparator(); fileMenu1.add(JmiExit = new JMenuItem(" 退出 ")); fileMenu2.add(Jmichuji = new JMenuItem(" 初級 ")); fileMenu2.add(Jmizhongji = new JMenuItem(" 中級 ")); fileMenu2.add(Jmigaoji = new JMenuItem(" 高階 ")); fileMenu3.add(JmishowInFo = new JMenuItem(" 開發者資訊 ")); JmiNew.addActionListener(this); JmiExit.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)); 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]; // 將按鈕對映到陣列中 flags = new boolean[map.length][map[0].length];// 儲存點開記錄表 flag = new boolean[map.length][map[0].length];// 儲存點開記錄表 int count = 0; // 佈雷 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);// 加入mouse監聽 add(jb[i][j]); } } // 計時器 JLabel ststus = new JLabel(); JLabel Times = new JLabel(); JLabel miao = new JLabel(); add(ststus); add(Times); Times.setText(" 0 "); miao.setText(" 秒"); setTimer(Times); coutTime = 0; ststus.setText(" 時間:"); 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); // 加入這一行 } private void setTimer(JLabel time) {// 時間監聽 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) {// 點選事件實現 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);//迴圈遍歷 } else { // 防止重複訪問 } } } } } } } private void showMines() {// 顯示所有雷 // TODO Auto-generated method stub for (int i = 0; i < map.length; i++) {// 顯雷 for (int j = 0; j < map.length; j++) { if (map[i][j] == '*') { jb[i][j].setIcon(icon); // } } } // 結束遊戲 int b = JOptionPane.showOptionDialog(null, "哎呀,炸了炸了,新遊戲?", "確認框", 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) {// 事件監聽處理 // 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();// 檢查是否遊戲結束 } } private void showRange() {// 顯示排行榜 new Shiyan13(map.length); } private void checkSuccess() {//判斷遊戲是否結束 // 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("-", "");//表唯一標示uuid // 連結資料庫,儲存時間資料 try { Class.forName(driver); con = (Connection) DriverManager.getConnection(url, user, password); String sql; if (!con.isClosed()) { // ta.setText(""); System.out.println("連線資料庫成功"); // 建立物件 Statement statement = (Statement) con.createStatement(); // if (map.length == 10) { // //要執行的sql語句 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) { // 資料庫驅動類異常處理 System.out.println("error"); e.printStackTrace(); } catch (SQLException e) { // System.out.println(e); System.err.println("找不到資料"); // int i=JOptionPane.showConfirmDialog(null, "你輸入的sql語句有誤", // "找不到",JOptionPane.YES_NO_OPTION); } catch (Exception e) { e.printStackTrace(); } finally { System.out.println("資料庫獲取資料成功!"); } int i = JOptionPane.showOptionDialog(null, "恭喜你過關了,是否繼續?", "確認框", 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) {//插旗子 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 mouseReleased(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.實現效果:

這裡寫圖片描述

4,主要功能實現:

(1) 基礎掃雷功能(隨機佈雷,插旗)
(2) 可以選擇難度
(3) 可以自定義掃雷的雷的數量以及格子數
(4) 設定時間
(5) 新增排行榜功能(根據時間存入資料庫排序)
(6) 外打包成exe檔案(帶jre)可以多平臺執行. (使用exe4j打包jar包)