扫雷游戏Java源代码详解
- 格式:doc
- 大小:71.00 KB
- 文档页数:12
自己写用Java写的扫雷游戏-----------做课程设计的可以参考一下。
运行界面截图:扫雷游戏主界面以下是游戏代码(共分三个文件即三个类:MySaoLei.java;Area.java 和ZiDingYi.java)://(1) MySaoLei.javapackage com.test;import java.awt.*;import javax.imageio.ImageIO;import javax.swing.*;import javax.swing.border.Border;import javax.swing.border.LineBorder;import java.awt.event.*;import java.io.File;import java.security.acl.Owner;import java.util.*;public class MySaoLei extends JFrame implements ActionListener,MouseListener{ //w表示横向可以放多少雷,h表示纵向可以放多少雷static int w=35,h=20;//设置雷的个数static int leisum=180;//用二维向量a[][]来存放雷Area a[][]=null;//win用于判断是否完成扫雷int win=0;Image image = null;JPanel jp=null;JPanel jp0=null;JMenuBar jmb;JMenu jm1,jm2;JMenuItem jm1_1,jm1_2,jm1_3,jm1_4,jm1_5,jm2_1; //主函数public static void main(String[] args) {// TODO Auto-generated method stubMySaoLei msl = new MySaoLei(w,h,leisum);}///////////////////////////////////////////////////构造函数public MySaoLei(int w,int h,int leisum){a=new Area[h][w];this.w=w;this.h=h;this.leisum=leisum;jmb=new JMenuBar();jm1=new JMenu("游戏(G)");jm1_1=new JMenuItem("初级");jm1_1.addActionListener(this);jm1_2=new JMenuItem("中级");jm1_2.addActionListener(this);jm1_3=new JMenuItem("高级");jm1_3.addActionListener(this);jm1_4=new JMenuItem("自定义");jm1_4.addActionListener(this);jm1_5=new JMenuItem("退出");jm1_5.addActionListener(this);jm1.add(jm1_1);jm1.add(jm1_2);jm1.add(jm1_3);jm1.add(jm1_4);jm1.add(jm1_5);jm2=new JMenu("帮助(H)");jm2_1=new JMenuItem("游戏规则"); jm2_1.addActionListener(this);jm2.add(jm2_1);jmb.add(jm1);jmb.add(jm2);//创建一个网格布局g1GridLayout gl=new GridLayout(h,w); gl.setHgap(1);gl.setVgap(1);jp=new JPanel();jp.setLayout(gl);//初始化雷区for(int i=0;i<h;i++){for(int j=0;j<w;j++){a[i][j]=new Area();a[i][j].addActionListener(this);a[i][j].addMouseListener(this);a[i][j].show(0);jp.add(a[i][j]);}}//添加每个按钮周围的按钮addAround();//设置雷int ii=0;int jj=0;for(int i=0;i<leisum;i++){ii=(int)(Math.random()*h);jj=(int)(Math.random()*w);a[ii][jj].isLei=1;a[ii][jj].Type=9;}//给每个按钮写上数据for(int i=0;i<h;i++){for(int j=0;j<w;j++){if(a[i][j].isLei==0){a[i][j].Type=getAroundsum(a[i][j]);}}}/////////////////////////////////////////////////////////////////////设置JFrametry{//image =ImageIO.read(new File("/me.jpg"));image=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/me.jpg")) ;this.setIconImage(image);}catch(Exception e){e.printStackTrace();}this.setJMenuBar(jmb);this.add(jp);this.setSize(w*35+10,h*35);this.setLocation(10, 10);this.setTitle("韦德爱扫雷");this.setIconImage(image);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setVisible(true);}//为每个按钮添加周围的按钮的函数public void addAround(){for(int i=0;i<h;i++){for(int j=0;j<w;j++){a[i][j].around=new Vector<Area>();if(i>0 && j>0){//左上角a[i][j].around.add(a[i-1][j-1]);//System.out.println(i+" "+j+"左上角");}if(j>0){//上方a[i][j].around.add(a[i][j-1]);//System.out.println(i+" "+j+"上方");}if(i<h-1 && j>0){//右上角a[i][j].around.add(a[i+1][j-1]);//System.out.println(i+" "+j+"右上角");}if(i<h-1){//右边a[i][j].around.add(a[i+1][j]);//System.out.println(i+" "+j+"右边");}if(i<h-1 && j<w-1){//右下角a[i][j].around.add(a[i+1][j+1]);//System.out.println(i+" "+j+"右下角");}if(j<w-1){//下方a[i][j].around.add(a[i][j+1]);//System.out.println(i+" "+j+"下方");}if(i>0 && j<w-1){//左下角a[i][j].around.add(a[i-1][j+1]);//System.out.println(i+" "+j+"左下角");}if(i>0){//左边a[i][j].around.add(a[i-1][j]);//System.out.println(i+" "+j+"左边");}}}}//得到按钮周边雷的个数的函数public int getAroundsum(Area area){int sum=0;Area a=null;for(int i=0;i<area.around.size();i++){a=area.around.get(i);if(a.isLei==1)sum++;}return sum;}//自动挖开空白区域public void wakai(Area a){Area a2=null;for(int i=0;i<a.around.size();i++){a2=a.around.get(i);if(a2.show==0 && a2.Type!=0){a2.show(1);}if(a2.show==0 && a2.Type==0){a2.show(1);wakai(a2);}}}//判断是否完成扫雷的函数public void win(){//判断是否挖完win=0;for(int i=0;i<h;i++){for(int j=0;j<w;j++){if(a[i][j].isLei==1 && a[i][j].show!=2){win++;}}}if(win==0){for(int i=0;i<h;i++){for(int j=0;j<w;j++){if(a[i][j].isLei==0 && a[i][j].show==0)a[i][j].show(1);}}JOptionPane.showMessageDialog(this, "恭喜你!扫雷完成!");}}//菜单响应函数public void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubif(e.getSource()==jm1_1){new MySaoLei(20,15,60);this.dispose();}if(e.getSource()==jm1_2){new MySaoLei(30,18,90);this.dispose();}if(e.getSource()==jm1_3){new MySaoLei(35,20,140);this.dispose();}if(e.getSource()==jm1_4){ZiDingYi zdy=new ZiDingYi(this,"自定义游戏等级",true);if(zdy.closeOwner)this.dispose();}if(e.getSource()==jm1_5){this.dispose();}if(e.getSource()==jm2_1){//System.out.println("点击了游戏规则");String message="游戏规则:\n每个小方块上都可能是雷、1~8的数字或者空白(空白表示0)。
教你怎么⽤Java开发扫雷游戏⽬录⼀、效果图⼆、实现思路三、代码实现3.1 设置头部3.2 设置游戏区域按钮3.3 设置雷3.4 计算周围雷的数量并显⽰3.5 添加点击事件3.6 打开指定按钮3.7 触雷爆炸3.8 递归打开周围3.9 ⿏标右键事件四、胜利判定⼀、效果图⼆、实现思路1.界⾯上可以点开的各种实际都是按钮,创建9⾏9列的⼆维数组,然后根据这个数组来创建JButton。
2.对应创建⼆维数组data,⽤来存取数据,0表⽰周围⽆雷,-1表⽰当前是雷,其他数字表⽰周围雷的数量。
3.对应创建⼆维数组state,⽤来存取按钮状态,0未打开,1 打开 2旗⼦ 3 未知(控制显⽰对应的图标)4.设置雷:随机⾏数 i 和列数 j,根据随机到 i、j 从⼆维数组data中取出对应的元素值,若值不为-1(不是雷),则将此元素data[i][j]设置为-1,若值是-1(已经是雷了),则跳过,不管是否跳过都进⾏递归,直到雷的数量达到设定的最⼤数量,跳出递归。
5.设置周围雷的数量:计算每个元素周围的雷数量(周围指的是左上、上、右上、右、右下、下、左下、左这8个位置),循环⼆维数组data,判断当前值不是-1,则需要计算周围雷的数量,等会细说。
6.有任⼀格⼦被揭开,则游戏开始并且计时,当格⼦被揭开的时候分3种情况(1)格⼦是雷,执⾏爆炸动画,游戏结束。
(2)当前格⼦周围有雷,则仅仅打开此格⼦,对应显⽰周围雷数量的数字图⽚。
(3)当前格⼦不是雷且周围没有雷(data取到的元素值为0),则依次打开周围,并且被打开的周围元素也没有雷的情况下,继续打开(递归)。
7.右键可以进⾏插⼩旗、打问号等操作(对数组state进⾏的操作)。
三、代码实现3.1 设置头部//设置头部private void setHeader() {Container container = new Container();container.setLayout(new GridLayout(1, 3));timeJLabel = new JLabel("时间:"+time,JLabel.CENTER);timeJLabel.setForeground(Color.DARK_GRAY);timeJLabel.setFont(new Font("微软雅⿊",Font.BOLD, 16));leiJLabel = new JLabel("雷:"+curLeiCount,JLabel.CENTER);leiJLabel.setForeground(Color.DARK_GRAY);leiJLabel.setFont(new Font("微软雅⿊",Font.BOLD, 16));reStart = new JButton((ImageIcon)imageMap.get(21));Dimension preferredSize = new Dimension(100,40);reStart.setPreferredSize(preferredSize);reStart.addActionListener(this);//注意添加顺序container.add(timeJLabel);container.add(reStart);container.add(leiJLabel);mainFrame.add(container,BorderLayout.NORTH);}3.2 设置游戏区域按钮1.创建容器,并采⽤GridLayout 布局。
扫雷不能不说一款非常经典的游戏,无聊时候可以打发时间,虽然玩了很久,但还不知道它是怎么写的,所以自己就尝试动手做了个。
众所周知,java的swing采用mvc模式,即模型-视图-控制器,所以如果真的了解了这个模式,较c++,用java做个游戏还是比较容易的。
下面是我写的扫雷的代码import java.awt.*;import java.io.*;import .URL;import java.awt.geom.*;import java.awt.event.*;import javax.swing.*;import java.util.ArrayDeque;import java.util.ArrayList;import java.util.concurrent.*;public class MineSweep{public static void main(String[] args){JFrame frame = new MineFrame();frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);}}class MineFrame extends JFrame{private JPanel buttonPanel;private MinePanel mp;private int rn,cn;public static final int DEFAULT_WIDTH = 650; public static final int DEFAULT_HEIGHT = 450; public static final int DEFAULT_CN = 9;public static final int DEFAULT_RN = 9;public JLabel remainMine;public JLabel mes;private JComboBox cb;public MineFrame(){setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);setTitle("扫雷");mp = new MinePanel(DEFAULT_CN,DEFAULT_RN,this); mp.setMinenum(10);mp.setRC(9,9);buttonPanel = new JPanel();add(mp,BorderLayout.CENTER);mes = new JLabel("");mes.setEnabled(false);add(mes,BorderLayout.EAST);cb = new JComboBox();cb.setEditable(true);cb.addItem("初级");cb.addItem("中级");cb.addItem("高级");cb.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {int index = cb.getSelectedIndex(); System.out.println(index);switch(index){case 0:mp.setMinenum(10);mp.setRC(9,9);break;case 1:mp.setMinenum(40);mp.setRC(16,16);break;case 2:mp.setMinenum(99);mp.setRC(30,16);break;}}});JButton showAll = new JButton("显示所有地雷");showAll.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e){mp.showMines();}});buttonPanel.add(showAll);JButton replay = new JButton("重新开始");replay.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e){mp.updateMines();}});buttonPanel.add(replay);buttonPanel.add(cb);remainMine = new JLabel("剩余雷数:" +mp.getMinenum()); add(remainMine,BorderLayout.SOUTH);add(buttonPanel,BorderLayout.NORTH);}}class Pair{public Pair(int r,int c){this.r = r;this.c =c;}public int r;public int c;}class MinePanel extends JPanel implements MouseListener {private int cn,rn;private int minenum;private Mine[][] mines;private int hideMine = minenum;private int ableMn ;private MineFrame f;private boolean over ;private int w,h;private boolean win;public static ArrayList<Image> IMAGES = new ArrayList<Image>(12); public MinePanel(int rn,int cn,MineFrame f){IMAGES.add(new ImageIcon(getURL(".\\img\\0.gif")).getImage()); IMAGES.add(new ImageIcon(getURL(".\\img\\1.gif")).getImage()); IMAGES.add(new ImageIcon(getURL(".\\img\\2.gif")).getImage()); IMAGES.add(new ImageIcon(getURL(".\\img\\3.gif")).getImage()); IMAGES.add(new ImageIcon(getURL(".\\img\\4.gif")).getImage()); IMAGES.add(new ImageIcon(getURL(".\\img\\5.gif")).getImage()); IMAGES.add(new ImageIcon(getURL(".\\img\\6.gif")).getImage()); IMAGES.add(new ImageIcon(getURL(".\\img\\7.gif")).getImage()); IMAGES.add(new ImageIcon(getURL(".\\img\\8.gif")).getImage()); IMAGES.add(new ImageIcon(getURL(".\\img\\mine.gif")).getImage()); IMAGES.add(new ImageIcon(getURL(".\\img\\11.gif")).getImage()); IMAGES.add(new ImageIcon(getURL(".\\img\\12.gif")).getImage()); this.f = f;this.rn = rn; = cn;this.ableMn = rn * cn;addMouseListener(this);updateMines();}public URL getURL(String file){URL url =null;try{url = this.getClass().getResource(file); }catch(Exception e){e.printStackTrace();}return url;}public void decAbleMn(){ableMn --;}public int getAbleMn(){return ableMn;}public void decHideMine(){hideMine --;}public void incHideMine(){hideMine ++;}public int getHideMine(){return hideMine;}public void setMinenum(int n){minenum = n;}public int getMinenum(){return minenum;}public void mousePressed(MouseEvent e) {if(!over){int x = (int)e.getX();int y = (int)e.getY();int keyCode = e.getButton();int c,r;r = x/Mine.WIDTH;c = y/Mine.HEIGHT;switch(keyCode){case MouseEvent.BUTTON1:if(mines[r][c].getFlag() == false) {try{mines[r][c].setOpen();decAbleMn();if(mines[r][c].getImage() == 9){over = true;decHideMine();showMines();}else if(mines[r][c].getImage() == 0) {if(getAbleMn() == rn * cn - minenum) {win = true;}openNear(r,c);}}catch(Exception ex){//e.printStackTrace();}repaint();}break;case MouseEvent.BUTTON3:if( mines[r][c].isOpen() == false || mines[r][c].getFlag() == true) {if(mines[r][c].getFlag() == true){incHideMine();mines[r][c].setFlag();repaint();}else if(hideMine > 0){mines[r][c].setFlag();decHideMine();repaint();}}break;}}}public void mouseReleased(MouseEvent e){}public void mouseClicked(MouseEvent e){}public void mouseEntered(MouseEvent e){}public void mouseExited(MouseEvent e){}private ArrayDeque<Pair> queue = new ArrayDeque<Pair>(20); public void openNear(int r,int c){int i,j;i = r;j = c;for(int n = -1; n <= 1; n ++){r = i + n;if(r >= 0 && r <mines.length)for(int k = -1; k <=1; k ++){c = j + k;if(c >= 0 && c < mines[r].length){if(mines[r][c].isOpen() == false && mines[r][c].getImage() == 0) {mines[r][c].setOpen();queue.add(new Pair(r,c));}else{if(mines[r][c].getFlag() ==true){mines[r][c].setFlag();incHideMine();}mines[r][c].setOpen();}}}}for(i = 0 ;i < queue.size(); i ++){Pair p = queue.poll();openNear(p.r,p.c);}}public void setRC(int rn,int cn){this.rn = rn; = cn;updateMines();repaint();}public void updateMines(){removeAll();win = false;over = false;f.setSize((10 +rn) * 20,(cn + 10) * 20);setSize(rn * Mine.HEIGHT,cn * Mine.WIDTH);mines = new Mine[rn][cn];for(int i = 0;i < mines.length;i ++)for(int j = 0 ;j < mines[i].length; j ++){mines[i][j] = new Mine(i,j);}int mn = getMinenum();hideMine = mn;for(int i = 0; i <mn;i ++){int r,c;do{r = (int)(Math.random() * rn);c = (int)(Math.random() * cn);}while(mines[r][c].getImage() == 9); mines[r][c].setImage(9);}generateNum();repaint();}public void generateNum(){int r,c;for(int i = 0 ;i < mines.length;i ++)for(int j = 0 ;j < mines[i].length; j ++) if(mines[i][j].getImage() != 9){int cnum = 0 ;for(int n = -1; n <= 1; n ++){r = i + n;if(r >= 0 && r < mines.length)for(int k = -1 ;k <=1; k ++){c = j + k;if(c >= 0 && c < mines[i].length){if(mines[r][c].getImage() == 9)cnum ++;}}}mines[i][j].setImage(cnum);}}public void paintComponent(Graphics g) {super.paintComponent(g);int c = 0;Graphics2D g2 = (Graphics2D) g;for(int i = 0 ;i < mines.length; i ++)for(int j = 0 ;j < mines[i].length; j ++){g2.setColor(mines[i][j].getColor());g2.draw(mines[i][j].getShape());if(mines[i][j].getFlag() == true && mines[i][j].isOpen() == false)g.drawImage(IMAGES.get(10),mines[i][j].getW(),mines[i][j].getH(),Mine .HEIGHT,Mine.WIDTH,this);if(mines[i][j].isOpen()&& mines[i][j].getFlag() == false ){g.drawImage(IMAGES.get(mines[i][j].getImage()),mines[i][j].getW(),min es[i][j].getH() ,Mine.HEIGHT,Mine.WIDTH,this);c ++;}}f.remainMine.setText("剩余雷数:" + getHideMine() );}public void showMines(){removeAll();for(int i = 0 ;i <mines.length; i ++)for(int j = 0 ; j < mines[i].length; j ++){if(mines[i][j].getImage() == 9){if(mines[i][j].getFlag() == false)mines[i][j].setOpen();}else{if(mines[i][j].getFlag() == true){mines[i][j].setOpen();mines[i][j].setFlag();mines[i][j].setImage(11);}}}hideMine = 0;repaint();}}class Mine{private Rectangle2D rect = null;public static final ImageIcon IMAGE = new ImageIcon("mine.gif");public static final int HEIGHT = 20;public static final int WIDTH = 20;private boolean flag = false;private boolean open = false;public static final Color DEFAULT_COLOR = Color.BLACK;private int image = 0;private Color color;private boolean isMine = false;private int w,h;public Mine(int r,int c){this.w = r * HEIGHT;this.h = c * HEIGHT;rect = new Rectangle2D.Double(1.0D *r * HEIGHT,1.0D *c * WIDTH ,1.0D *HEIGHT,1.0D *WIDTH);setColor(DEFAULT_COLOR);}public void setMine(){isMine = true;}public boolean isMine(){return isMine;}public void setColor(Color c)this.color = c;}public Color getColor() {return color;}public void setOpen(){open = true;}public boolean isOpen() {return open;}public void setImage(int n) {image =n;}public int getImage(){return image;}public int getW()return w;}public int getH(){return h;}public void setFlag(){flag = !flag;}public boolean getFlag(){return flag;}public Shape getShape(){return rect;}}代码主要包含三个类,MineSweep,MinePanel和Mine类。
java实现简单扫雷游戏本⽂实例为⼤家分享了java实现简单扫雷游戏的具体代码,供⼤家参考,具体内容如下package com.test.swing;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;/*** 这个是⼀个简单的扫雷例⼦,刚接触swing编写的,适合新⼿练习* 该程序使⽤setBounds(x,y,w,h)对控件布局* 做法参考win xp⾃带的扫雷,当然还写功能没做出来,* 另外做出来的功能有些还存在bug** @author Ping_QC*/public class Test extends JFrame implements ActionListener, Runnable,MouseListener {private static final long serialVersionUID = -2417758397965039613L;private final int EMPTY = 0;private final int MINE = 1;private final int CHECKED = 2;private final int MINE_COUNT = 10; // 雷的个数private final int BUTTON_BORDER = 50; // 每个点的尺⼨private final int MINE_SIZE = 10; // 界⾯规格, 20x20private final int START_X = 20; // 起始位置xprivate final int START_Y = 50; // 起始位置yprivate boolean flag;private JButton[][] jb;private JLabel jl;private JLabel showTime;private int[][] map;/*** 检测某点周围是否有雷,周围点的坐标可由该数组计算得到*/private int[][] mv = { { -1, 0 }, { -1, 1 }, { 0, 1 }, { 1, 1 }, { 1, 0 },{ 1, -1 }, { 0, -1 }, { -1, -1 } };/*** 随机产⽣设定个数的雷*/public void makeMine() {int i = 0, tx, ty;for (; i < MINE_COUNT;) {tx = (int) (Math.random() * MINE_SIZE);ty = (int) (Math.random() * MINE_SIZE);if (map[tx][ty] == EMPTY) {map[tx][ty] = MINE;i++; // 不记重复产⽣的雷}}}/*** 将button数组放到frame上,与map[][]数组对应*/public void makeButton() {for (int i = 0; i < MINE_SIZE; i++) {for (int j = 0; j < MINE_SIZE; j++) {jb[i][j] = new JButton();// if (map[i][j] == MINE)// jb[i][j].setText(i+","+j);// listener addjb[i][j].addActionListener(this);jb[i][j].addMouseListener(this);jb[i][j].setName(i + "_" + j); // ⽅便点击是判断是点击了哪个按钮// Font font = new Font(Font.SERIF, Font.BOLD, 10);// jb[i][j].setFont(font);// jb[i][j].setText(i+","+j);jb[i][j].setBounds(j * BUTTON_BORDER + START_X, i* BUTTON_BORDER + START_Y, BUTTON_BORDER, BUTTON_BORDER); this.add(jb[i][j]);}}}public void init() {flag = false;jl.setText("欢迎测试,⼀共有" + MINE_COUNT + "个雷");jl.setVisible(true);jl.setBounds(20, 20, 500, 30);this.add(jl);showTime.setText("已⽤时:0 秒");showTime.setBounds(400, 20, 100, 30);this.add(showTime);makeMine();makeButton();this.setSize(550, 600);this.setLocation(700, 100);this.setResizable(false);this.setDefaultCloseOperation(EXIT_ON_CLOSE);this.setVisible(true);}public Test(String title) {super(title);this.setLayout(null); //不使⽤布局管理器,每个控件的位置⽤setBounds设定jb = new JButton[MINE_SIZE][MINE_SIZE];jl = new JLabel();showTime = new JLabel();map = new int[MINE_SIZE][MINE_SIZE]; // 将按钮映射到数组中}public static void main(String[] args) {Test test = new Test("Hello Miner!");test.init();test.run();}@Overridepublic void actionPerformed(ActionEvent e) {Object obj = e.getSource();int x, y;if ((obj instanceof JButton) == false) {showMessage("错误", "内部错误");return;}String[] tmp_str = ((JButton) obj).getName().split("_");x = Integer.parseInt(tmp_str[0]);y = Integer.parseInt(tmp_str[1]);if (map[x][y] == MINE) {showMessage("死亡", "你踩到地雷啦~~~");flag = true;showMine();return;}dfs(x, y, 0);checkSuccess();}/*** 每次点击完后,判断有没有把全部雷都找到通过计算状态为enable的按钮的个数来判断 */private void checkSuccess() {int cnt = 0;for (int i = 0; i < MINE_SIZE; i++) {for (int j = 0; j < MINE_SIZE; j++) {if (jb[i][j].isEnabled()) {cnt++;}}}if (cnt == MINE_COUNT) {String tmp_str = showTime.getText();tmp_str = tmp_str.replaceAll("[^0-9]", "");showMessage("胜利", "本次扫雷共⽤时:" + tmp_str + "秒");flag = true;showMine();}}private int dfs(int x, int y, int d) {map[x][y] = CHECKED;int i, tx, ty, cnt = 0;for (i = 0; i < 8; i++) {tx = x + mv[i][0];ty = y + mv[i][1];if (tx >= 0 && tx < MINE_SIZE && ty >= 0 && ty < MINE_SIZE) {if (map[tx][ty] == MINE) {cnt++;// 该点附近雷数统计} else if (map[tx][ty] == EMPTY) {;} else if (map[tx][ty] == CHECKED) {;}}}if (cnt == 0) {for (i = 0; i < 8; i++) {tx = x + mv[i][0];ty = y + mv[i][1];if (tx >= 0 && tx < MINE_SIZE && ty >= 0 && ty < MINE_SIZE&& map[tx][ty] != CHECKED) {dfs(tx, ty, d + 1);}}} else {jb[x][y].setText(cnt + "");}jb[x][y].setEnabled(false);return cnt;}/*** 在jl标签上显⽰⼀些信息** @param title* @param info*/private void showMessage(String title, String info) {jl.setText(info);System.out.println("in functino showMessage() : " + info);}public void run() {int t = 0;while (true) {if (flag) {break;}try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}t++;showTime.setText("已⽤时:" + t + " 秒");}// showMine();}private void showMine() {// Icon iconMine = new ImageIcon("e:/mine.jpg");for (int i = 0; i < MINE_SIZE; i++) {for (int j = 0; j < MINE_SIZE; j++) {if (map[i][j] == MINE) {jb[i][j].setText("#");// jb[i][j].setIcon(iconMine);}}}}@Overridepublic void mouseClicked(MouseEvent e) {if (e.getButton() == 3) {Object obj = e.getSource();if ((obj instanceof JButton) == false) {showMessage("错误", "内部错误");return;}String[] tmp_str = ((JButton) obj).getName().split("_");int x = Integer.parseInt(tmp_str[0]);int y = Integer.parseInt(tmp_str[1]);if ("{1}quot;.equals(jb[x][y].getText())) {jb[x][y].setText("");} else {jb[x][y].setText("{1}quot;);}/* if(jb[x][y].getIcon() == null){jb[x][y].setIcon(new ImageIcon("e:/flag.jpg"));}else{jb[x][y].setIcon(null);}*/}}@Overridepublic void mousePressed(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}}更多精彩游戏,请参考专题以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
JAVA实现经典扫雷游戏的⽰例代码⽬录前⾔主要设计功能截图代码实现总结前⾔windows⾃带的游戏《扫雷》是陪伴了⽆数⼈的经典游戏,本程序参考《扫雷》的规则进⾏了简化,⽤java语⾔实现,采⽤了swing技术进⾏了界⾯化处理,设计思路⽤了⾯向对象思想。
主要需求1、要有难度等级,初级,中级,⾼级2、由玩家逐个翻开⽅块,以找出所有地雷为最终游戏⽬标。
如果玩家翻开的⽅块有地雷,则游戏结束3、游戏主区域由很多个⽅格组成。
使⽤⿏标左键随机点击⼀个⽅格,⽅格即被打开并显⽰出⽅格中的数字;⽅格中数字则表⽰其周围的8个⽅格隐藏了⼏颗雷。
4、⽤户右键可标记雷的位置5、雷都被标记出来则胜利主要设计1、格⼦格数固定为10*10格2、难度等级,初级:12,中级:24,⾼级:363、点击格⼦时,产⽣没有引爆的地图效果;4、点击格⼦时,此格⼦是雷,则显⽰所有雷的位置,并递归清空⾮雷格⼦,结束游戏5、实现检查所有的雷是否都被标记出来了,如果是,则胜利算法。
6、实现计时器算法,⽤来计时显⽰游戏开始多少秒7、实现难度等级,雷数的显⽰8、实现⿏标左键的实现逻辑9、实现⿏标右键的标记逻辑功能截图开始界⾯左键选中格⼦效果左键选中雷效果右键标记雷效果胜利效果代码实现程序启动类public class JMine extends JFrame implements MouseListener, ActionListener {private JMineArth mine;private JMineButton[][] mineButton;private GridBagConstraints constraints;private JPanel pane;private GridBagLayout gridbag;private boolean gameStarted;private static JCounter mineCounter;private static JCounter timeCounter;private Timer timer;private Timer winTimer = new Timer();public int numMine;public int numFlaged;private JMenuBar mb;private JMenu mGame;private JMenuItem miEasy;private JMenuItem miMiddle;private JMenuItem miHard;private JMenuItem miExit;private JMenu mHelp;private JMenuItem miAbout;private JPanel controlPane;private JButton bTest;private AboutFrame about;private WinFrame winFrame;private ImageIcon[] mineNumIcon = { new ImageIcon(JMine.class.getClassLoader().getResource("blank1.gif")),new ImageIcon(JMine.class.getClassLoader().getResource("1.gif")), new ImageIcon(JMine.class.getClassLoader().getResource("2.gif")),new ImageIcon(JMine.class.getClassLoader().getResource("3.gif")), new ImageIcon(JMine.class.getClassLoader().getResource("4.gif")),new ImageIcon(JMine.class.getClassLoader().getResource("5.gif")), new ImageIcon(JMine.class.getClassLoader().getResource("6.gif")),new ImageIcon(JMine.class.getClassLoader().getResource("7.gif")), new ImageIcon(JMine.class.getClassLoader().getResource("8.gif")),new ImageIcon(JMine.class.getClassLoader().getResource("0.gif"))};private ImageIcon[] mineStatus = { new ImageIcon(JMine.class.getClassLoader().getResource("blank1.gif")),new ImageIcon(JMine.class.getClassLoader().getResource("flag.gif")), new ImageIcon(JMine.class.getClassLoader().getResource("question.gif")) }; private ImageIcon[] mineBombStatus = { new ImageIcon(JMine.class.getClassLoader().getResource("0.gif")),new ImageIcon(JMine.class.getClassLoader().getResource("mine.gif")), new ImageIcon(JMine.class.getClassLoader().getResource("wrongmine.gif")), new ImageIcon(JMine.class.getClassLoader().getResource("bomb.gif")) };private ImageIcon[] faceIcon = { new ImageIcon(JMine.class.getClassLoader().getResource("smile.gif")),new ImageIcon(JMine.class.getClassLoader().getResource("Ooo.gif")) };// You loseprivate void bomb(int row, int col){try{//System.out.println("Bomb!");for (int i = 0; i < 10; i++) {for (int j = 0; j < 10; j++) {mineButton[i][j].setIcon(mineBombStatus[0]);int toShow;toShow = mine.mine[i][j] != 9 ? 0 : 1;mineButton[i][j].setClickFlag(true);if (toShow == 1 && (i != row || j != col)) {mineButton[i][j].setIcon(mineBombStatus[toShow]);mineButton[i][j].setClickFlag(true);} else if (toShow == 1 && (i == row && j == col)) {mineButton[i][j].setIcon(mineBombStatus[3]);mineButton[i][j].setClickFlag(true);} else if (toShow == 0 && mineButton[i][j].getFlag() != 1) { mineButton[i][j].setEnabled(false);} else if (toShow == 0 && mineButton[i][j].getFlag() == 1) { mineButton[i][j].setIcon(mineBombStatus[2]);mineButton[i][j].setClickFlag(true);}}}timer.cancel();}catch (Exception e){}}// check if you win() {private boolean isWin() {for (int i = 0; i < 10; i++) {for (int j = 0; j < 10; j++) {if (mine.mine[i][j] == 9 && mineButton[i][j].getFlag() != 1) { return (false);}if (mine.mine[i][j] != 9 && mineButton[i][j].getFlag() == 1) { return (false);}if (mine.mine[i][j] != 9&& mineButton[i][j].getClickFlag() == false) {return (false);}}}return (true);}// You Winprivate void win(){timer.cancel();winFrame.setVisible(true);winTimer.schedule(new TimerTask(){public void run() {while(!winFrame.getWinOk()){}numMine = winFrame.getMineNum();winFrame.setVisible(false);setNewGame(numMine);//System.out.println("Jerry Debug:"+numMine);this.cancel();winFrame.setWinOk(false);}},0L);}// Constructor of the gamepublic JMine() {super("JMine Game");setSize(250, 350);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);Insets space = new Insets(0, 0, 0, 0);// Game varsgameStarted = false;numMine = 12;numFlaged = 0;ImageIcon myIcon = new ImageIcon(JMine.class.getClassLoader().getResource("blank1.gif")); gridbag = new GridBagLayout();constraints = new GridBagConstraints();pane = new JPanel();pane.setLayout(gridbag);constraints.fill = GridBagConstraints.BOTH;constraints.anchor = GridBagConstraints.CENTER;// Begin Menu Setmb = new JMenuBar();mGame = new JMenu("Game");miEasy = new JMenuItem("Easy");miEasy.addActionListener(this);miMiddle = new JMenuItem("Middle");miMiddle.addActionListener(this);miHard = new JMenuItem("Hard");miHard.addActionListener(this);miExit = new JMenuItem("Exit");miExit.addActionListener(this);mGame.add(miEasy);mGame.add(miMiddle);mGame.add(miHard);mGame.addSeparator();mGame.add(miExit);mb.add(mGame);mHelp = new JMenu("Help");miAbout = new JMenuItem("About...");mHelp.add(miAbout);miAbout.addActionListener(this);mb.add(mHelp);this.setJMenuBar(mb);// end of Menu Set// Control PanelcontrolPane = new JPanel();bTest = new JButton(faceIcon[0]);bTest.setSize(26, 27);bTest.setMargin(space);bTest.addMouseListener(this);bTest.setPressedIcon(faceIcon[1]);mineCounter = new JCounter(numMine);timeCounter = new JCounter();controlPane.add(mineCounter);controlPane.add(bTest);controlPane.add(timeCounter);buildConstraints(constraints, 0, 0, 10, 2, 100, 100);gridbag.setConstraints(controlPane, constraints);pane.add(controlPane);// BottonsmineButton = new JMineButton[10][10];for (int i = 0; i < 10; i++) {for (int j = 0; j < 10; j++) {mineButton[i][j] = new JMineButton(i, j, myIcon);mineButton[i][j].addMouseListener(this);mineButton[i][j].setMargin(space);buildConstraints(constraints, j, i + 3, 1, 1, 100, 100);gridbag.setConstraints(mineButton[i][j], constraints);pane.add(mineButton[i][j]);}}// Content PanesetContentPane(pane);setLocation(200, 150);setVisible(true);// About Frameabout = new AboutFrame("JMine About");winFrame = new WinFrame("You win!");}// Set the GUI objects positionsvoid buildConstraints(GridBagConstraints gbc, int gx, int gy, int gw, int gh, int wx, int wy) {gbc.gridx = gx;gbc.gridy = gy;gbc.gridwidth = gw;gbc.gridheight = gh;gbc.weightx = wx;gbc.weighty = wy;}// the methods to check if there were mines, to be nestedvoid checkMine(int row, int col){int i, j;i = row < 0 ? 0 : row;i = i > 9 ? 9 : i;j = col < 0 ? 0 : col;j = j > 9 ? 9 : j;//System.out.println("Check Mine row:"+i + ",col:" +j);if (mine.mine[i][j] == 9) {bomb(i, j);} else if (mine.mine[i][j] == 0&& mineButton[i][j].getClickFlag() == false) {mineButton[i][j].setClickFlag(true);showLabel(i, j);for (int ii = i - 1; ii <= i + 1; ii++)for (int jj = j - 1; jj <= j + 1; jj++)checkMine(ii, jj);} else {showLabel(i, j);mineButton[i][j].setClickFlag(true);}if (isWin()) {win();}}private void clearAll(int row, int col){int top, bottom, left, right;top = row - 1 > 0 ? row - 1 : 0;bottom = row + 1 < 10 ? row + 1 : 9;left = col - 1 > 0 ? col - 1 : 0;right = col + 1 < 10 ? col + 1 : 9;for (int i = top; i <= bottom; i++) {for (int j = left; j <= right; j++) {if (mineButton[i][j].getFlag() != 1)checkMine(i, j);}}}private void resetAll() {for (int i = 0; i < 10; i++) {for (int j = 0; j < 10; j++) {mineButton[i][j].setFlag(0);mineButton[i][j].setClickFlag(false);mineButton[i][j].setIcon(mineStatus[0]);mineButton[i][j].setEnabled(true);mineButton[i][j].setVisible(true);}}}// to flag the mine you want to flag outvoid flagMine(int row, int col) {//System.out.println("Jerry Arrives here!");int i, j;i = row < 0 ? 0 : row;i = i > 9 ? 9 : i;j = col < 0 ? 0 : col;j = j > 9 ? 9 : j;if (mineButton[i][j].getFlag() == 0) {numFlaged++;} else if (mineButton[i][j].getFlag() == 1) {numFlaged--;}mineCounter.resetCounter(numMine - numFlaged >= 0 ? numMine - numFlaged: 0);mineButton[i][j].setFlag((mineButton[i][j].getFlag() + 1) % 3);showFlag(i, j);if (isWin()) {win();}}// show the numbers of the nearby minesvoid showLabel(int row, int col) {//System.out.println("ShowLabel row:" + row + ",col:" + col);int toShow;toShow = mine.mine[row][col];if (toShow != 0) {mineButton[row][col].setIcon(mineNumIcon[toShow]);mineButton[row][col].setClickFlag(true);//mineButton[row][col].setEnabled(false);} else {//mineButton[row][col].setIcon(mineNumIcon[0]);//mineButton[row][col].setClickFlag(true);mineButton[row][col].setEnabled(false);}}// circle the flag with blank, flaged, questionedvoid showFlag(int row, int col) {mineButton[row][col].setIcon(mineStatus[mineButton[row][col].getFlag()]);}// the mouse events listener methodspublic void mouseEntered(MouseEvent e) {//System.out.println("Jerry Test");}// method to start the new gameprivate void startNewGame(int num, int row, int col){mine = new JMineArth(num, row, col);//mine.printMine();gameStarted = true;timer = new Timer();timer.scheduleAtFixedRate(new TimerTask(){public void run() {timeCounter.counterAdd();//System.out.println(timeCounter.getCounterNum());}},1000,1000);}public void setNewGame(int num) {resetAll();numMine = num;numFlaged = 0;gameStarted = false;mineCounter.resetCounter(numMine);timeCounter.resetCounter(0);}// the event handle to deal with the mouse clickpublic void mouseClicked(MouseEvent e) {if (e.getSource() == bTest) {setNewGame(numMine);return;}int row, col;row = ((JMineButton) e.getSource()).getRow();col = ((JMineButton) e.getSource()).getCol();if (!gameStarted) {startNewGame(numMine, row, col);}if (e.getModifiers() == (InputEvent.BUTTON1_MASK + InputEvent.BUTTON3_MASK)) { //System.out.println("HA");clearAll(row, col);}if (!mineButton[row][col].getClickFlag()) {if (e.getModifiers() == InputEvent.BUTTON1_MASK) {//System.out.println("LeftButton");if (mineButton[row][col].getFlag() == 1) {return;} else {checkMine(row, col);}} else if (e.getModifiers() == InputEvent.BUTTON3_MASK) { //System.out.println("RightButton");flagMine(row, col);} else {//System.out.println("MiddleButton");}}}public void mousePressed(MouseEvent e) {//System.out.println("Jerry Press");}public void mouseReleased(MouseEvent e) {//System.out.println("Jerry Release");}public void mouseExited(MouseEvent e) {//System.out.println("Jerry Exited");}public void actionPerformed(ActionEvent e) {try {if (e.getSource() == miEasy) {setNewGame(12);return;}if (e.getSource() == miMiddle) {setNewGame(24);return;}if (e.getSource() == miHard) {setNewGame(36);return;}if (e.getSource() == miExit) {System.exit(0);}if (e.getSource() == miAbout) {about.setVisible(true);}} catch (Exception ie) {}}public static void main(String [] args) {JMine jmine = new JMine();jmine.setVisible(true);}}地雷分布图算法类public class JMineArth {public int [][] mine;private boolean fMineSet;JMineArth(int mineNum, int row, int col) {mine = new int[10][10];setMine(mineNum, row, col);setMineNum();}private void setMine(int mineNum, int Outrow, int Outcol) {int col=0, row = 0, i=0;//Math.srand(now);while (i < mineNum) {col = (int)(Math.random()*100)%10;row = (int)(Math.random()*100)%10;if (mine[col][row]==0 && (row!=Outrow || col!=Outcol || Outrow==10 )) {mine[row][col]=9;i++;}}}private void setMineNum() {for ( int i=0 ; i <10; i++) {for (int j=0; j < 10; j++) {mine[i][j]=mine[i][j]==9?9:checkMineNum(i,j);}}fMineSet = true;}private int checkMineNum(int ii,int jj) {int top,bottom, left, right, count=0;top=ii-1>0?ii-1:0;bottom=ii+1<10?ii+1:9;left=jj-1>0?jj-1:0;right=jj+1<10?jj+1:9;for (int i=top; i<=bottom; i++) {for(int j=left; j<= right; j++) {if (mine[i][j]==9) count++;}}return(count);}public void printMine() {for (int i = 0; i < 10; i++) {for (int j=0; j < 10; j++) {System.out.print(this.mine[i][j] + " ");}System.out.println();}}public static void main(String[] args) {JMineArth mine = new JMineArth(Integer.parseInt(args[0]),Integer.parseInt(args[1]),Integer.parseInt(args[2]));mine.printMine();}}总结通过此次的《扫雷》游戏实现,让我对swing的相关知识有了进⼀步的了解,对java这门语⾔也有了⽐以前更深刻的认识。
importjava.util.Scanner;public class SL {public static void main(String[] args) {Scanner s = new Scanner(System.in);int[][] square = null;String[][] draw = null;boolean flag = true;while(flag){System.out.println("请选择游戏难度");System.out.println("1:简单");System.out.println("2: 一般");System.out.println("3: 困难");intuserselect = s.nextInt();if(userselect!=1 &&userselect!=2 &&userselect!=3){System.out.println("您的输入有误,请重新输入");continue;}switch(userselect){case 1: square = new int[3][3];draw = new String[3][3];break;case 2: square = new int[6][6];draw= new String[6][6];break;case 3: square = new int[9][9];draw= new String[9][9];break;}for(int i =0;i<square.length;i++){for(int j=0;j<square[i].length;j++){square[i][j] = (int)(Math.random()*10/5);draw[i][j] = "*";System.out.print(square[i][j]+" ");}System.out.println("");}for(int i =0;i<square.length;i++){for(int j=0;j<square[i].length;j++){System.out.print("* ");}System.out.println("");}System.out.println("游戏开始");System.out.println("如果您觉得有雷,请输入:1"); System.out.println("如果您觉得没雷,请输入:0");R1:for(int i=0;i<square.length;i++){for(int j=0;j<square[i].length;j++){byte input = -1;while(flag){System.out.println("您觉得"+(i+1)+"-"+(j+1)+"位置上是否有雷"); input = s.nextByte();if(input!=0 && input!=1){System.out.println("您的输入有误,请重新输入");continue;}break;}if(input==square[i][j]){System.out.println("排除成功");draw[i][j] = String.valueOf(square[i][j]);for(int a =0;a<draw.length;a++){for(int b=0;b<draw[i].length;b++){System.out.print(draw[a][b]+" ");}System.out.println();}int x = i;int y = j;int counter =0;while(true){if(x-1>=0 && y-1>=0){counter += square[(x-1)][(y-1)];System.out.println("周围有"+counter+"颗雷");break;}else if(x-1<0){System.out.println("2");x++;}else if(y-1<0){System.out.println("3");y++;}}}else{System.out.println("游戏结束");break R1;}}}System.out.println("恭喜您过关成功");byteuserchoose = -1;while(flag){System.out.println("是否继续");System.out.println("继续请按:1");System.out.println("退出请按:0");userchoose = s.nextByte();if(userchoose!=0 &&userchoose!=1){System.out.println("您的输入有误请重新输入");continue;}break;}if(userchoose==0){break;}}}}。
扫雷使用Java语言和JavaFX开发的小游戏扫雷游戏是一款经典的单人益智游戏,目标是在一个方块网格中,找出所有不含雷的方块,同时避开所有含雷的方块。
本文将介绍如何使用Java语言和JavaFX开发一个简单的扫雷游戏。
一、游戏设计和规则扫雷游戏的设计和规则非常简单。
一个方块网格被分成若干个小方块,有些方块上隐藏着雷,而其他方块上则显示着数字,数字表示该方块周围的雷数。
玩家可以点击方块来揭示它的内容,如果揭示到含雷的方块,则游戏结束;如果揭示到数字方块,则继续进行游戏;若揭示到不含雷的方块,则继续揭示周围的方块,直到揭示到含雷的方块或者揭示到边界为止。
游戏目标是揭示出所有不含雷的方块。
二、项目结构与主要类在Java语言和JavaFX开发扫雷游戏时,一个推荐的项目结构如下:1. Main类:游戏的入口类,负责启动游戏。
2. Game类:游戏的主要逻辑类,包含方块网格的生成、雷的布置以及游戏状态的管理。
3. Block类:方块类,包含方块的状态(是否揭示、是否含雷等)和周围雷数的计算方法。
4. UI类:游戏的用户界面类,负责显示方块网格和处理点击事件等。
三、使用JavaFX创建用户界面JavaFX是现代化的Java图形界面开发框架,提供了丰富的界面组件和动画效果。
在扫雷游戏中,可以使用JavaFX来实现方块的显示以及用户交互。
1. 创建方块网格:使用JavaFX的GridPane布局来创建方块网格。
可以根据游戏难度在GridPane中添加若干个方块组件,并设置它们的样式和事件处理器。
2. 显示方块内容:根据方块的状态,在界面上显示相应的图标或者文字。
可以使用JavaFX的Label组件来显示方块的内容,并根据不同的状态设置不同的样式。
3. 处理点击事件:为每个方块组件添加事件处理器,当用户点击方块时,根据方块的内容和状态来更新界面显示。
四、实现游戏逻辑在Game类中实现游戏的主要逻辑。
首先,根据游戏难度生成方块网格,并在其中随机布置一定数量的雷。
主函数所在处package saolei.frame;import java.awt.BorderLayout;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import javax.swing.ImageIcon;import javax.swing.JFrame;import javax.swing.JPanel;import saolei.tools.Tools;import saolei.menubar.Mymenubar;import saolei.panel.MybompPanel;import saolei.panel.MyfacePanel;public class MymineFrame extends JFrame{private Mymenubar mymenubar;//菜单栏private MyfacePanel myfacePanel;//笑脸lableprivate MybompPanel mybompPanel;//雷面板private JPanel jPanel;//主面板用来装笑脸面板和雷面板public Mymenubar getMymenubar() {return mymenubar;}public void setMymenubar(Mymenubar mymenubar) { this.mymenubar = mymenubar;}public MyfacePanel getMyfacePanel() {return myfacePanel;}public void setMyfacePanel(MyfacePanel myfacePanel) { this.myfacePanel = myfacePanel;}public MybompPanel getMybompPanel() {return mybompPanel;}public void setMybompPanel(MybompPanel mybompPanel) { this.mybompPanel = mybompPanel;}public MymineFrame(String s){super(s);init();this.add(jPanel);//将主面板装到这个Framethis.pack();//自动设置大小this.setVisible(true);//设置Frame可见}private void init() {mymenubar=new Mymenubar(this);myfacePanel=new MyfacePanel();mybompPanel=new MybompPanel(this);jPanel=new JPanel();jPanel.setLayout(new BorderLayout());//将主面板设置为边框布局Tools.faceLabel.addMouseListener(new MouseAdapter() {//对笑脸添加监听public void mousePressed(MouseEvent e) {Tools.faceLabel.setIcon(Tools.faceIcon[1]);//未释放时笑脸凹下去}public void mouseReleased(MouseEvent e) {Tools.faceLabel.setIcon(Tools.faceIcon[0]);//释放时重新开局rePlay();}});this.setIconImage(newImageIcon("./images/icon.gif").getImage());//设置扫雷图标this.setLocationRelativeTo(null);//设置窗口相对于指定组件的位置,因为参数为nul,所以此窗口将置于屏幕的中央this.setDefaultCloseOperation(EXIT_ON_CLOSE);//设置在关闭时退出this.setResizable(false);//设置不可变大小this.setJMenuBar(mymenubar);//放入菜单jPanel.add(myfacePanel,BorderLayout.NORTH);//放笑脸jPanel.add(mybompPanel,BorderLayout.CENTER);//放雷区}public void rePlay()//重新开局函数{Tools.timer.stop();//时间开始,因为只能有一个计时器所以将它写在静态区Tools.myTimerTask.time = 0;//设置开始时间为0Tools.timeLabelB.setIcon(Tools.numberIcon[0]);Tools.timeLabelS.setIcon(Tools.numberIcon[0]);Tools.timeLabelG.setIcon(Tools.numberIcon[0]);this.remove(jPanel);//移除主面板然后重新new一个jPanel = new JPanel();mymenubar = new Mymenubar(this);//重新定义里面元素myfacePanel = new MyfacePanel();Tools.setMineCount(Tools.mineCount);Tools.faceLabel.setIcon(Tools.faceIcon[0]);mybompPanel = new MybompPanel(this);jPanel.setLayout(new BorderLayout());jPanel.add(myfacePanel, BorderLayout.NORTH);jPanel.add(mybompPanel, BorderLayout.CENTER);//重新装载组件this.add(jPanel);this.pack();this.validate();//确保组件具有有效的布局}public static void main(String[] args) {MymineFrame mymineFrame=new MymineFrame("扫雷");//主函数 ,函数入口}}雷面板package saolei.panel;import java.awt.Color;import java.awt.GridLayout;import javax.swing.BorderFactory;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.border.BevelBorder;import javax.swing.border.Border;import saolei.frame.MymineFrame;import ble.MymineLable;import saolei.listener.MyListener;import saolei.tools.Tools;public class MybompPanel extends JPanel{public MymineFrame mymineFrame;private int leftClick;public int getLeftClick() {return leftClick;}public void setLeftClick(int leftClick) {this.leftClick = leftClick;}private MymineLable[][]mymineLables;public MymineLable[][] getMymineLables() {return mymineLables;}public void setMymineLables(MymineLable[][] mymineLables) { this.mymineLables = mymineLables;}public MybompPanel(MymineFrame m){this.mymineFrame=m;init();}private void init() {this.setBackground(Color.LIGHT_GRAY);Border border1 = BorderFactory.createEmptyBorder(5, 5, 5, 5);Border border2 =BorderFactory.createBevelBorder(BevelBorder.LOWERED);this.setBorder(BorderFactory.createCompoundBorder(border1, border2));MyListener myListener=new MyListener(this);this.setLayout(new GridLayout(Tools.rowCount,Tools.colCount));mymineLables= new MymineLable[Tools.rowCount][Tools.colCount];for (int i = 0; i < Tools.rowCount; i++) {for (int j = 0; j < Tools.colCount; j++) {mymineLables[i][j] = new MymineLable(i, j);mymineLables[i][j].addMouseListener(myListener);this.add(mymineLables[i][j]);}}}public void setMine(int rowx,int coly){for(int i=0;i<Tools.mineCount;i++){int x=(int)(Math.random()*Tools.rowCount);int y=(int)(Math.random()*Tools.colCount);if(x==rowx&&y==coly){i--;}if(mymineLables[x][y].isIsmine()){i--;}else{mymineLables[x][y].setIsmine(true);mymineLables[x][y].setIcon(Tools.blank);}}for (int i = 0; i < Tools.rowCount; i++) {//算雷for (int j = 0; j < Tools.colCount; j++) {int count = 0;if (mymineLables[i][j].isIsmine() == false) {for (int x =i - 1; x <= i + 1; x++) {for (int y =j - 1; y <= j + 1; y++) {if (x>=0 && x<Tools.rowCount && y>=0 && y<Tools.colCount) {if (mymineLables[x][y].isIsmine()) {count++;}}}}}mymineLables[i][j].setCount(count);}}}笑脸面板package saolei.panel;import java.awt.BorderLayout;import java.awt.Color;import java.awt.Image;import javax.swing.BorderFactory;import javax.swing.Box;import javax.swing.ImageIcon;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.border.BevelBorder;import javax.swing.border.Border;import saolei.tools.Tools;public class MyfacePanel extends JPanel{ private Box box;public MyfacePanel(){init();}public void init() {this.setLayout(new BorderLayout());box = Box.createHorizontalBox();box.add(Box.createHorizontalStrut(5));box.add(Tools.mineLabelB);box.add(Tools.mineLabelS);box.add(Tools.mineLabelG);box.add(Box.createHorizontalGlue());box.add(Tools.faceLabel);box.add(Box.createHorizontalGlue());box.add(Tools.timeLabelB);box.add(Tools.timeLabelS);box.add(Tools.timeLabelG);box.add(Box.createHorizontalStrut(5));this.add(box);this.setBackground(Color.LIGHT_GRAY);Border border1 = BorderFactory.createEmptyBorder(5,5,5,5);Border border2 =BorderFactory.createBevelBorder(BevelBorder.LOWERED);this.setBorder(BorderFactory.createCompoundBorder(border1,border2 ));}}关于扫雷对话框package saolei.dialog;import java.awt.BorderLayout;import java.awt.Dimension;import java.awt.FlowLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.BorderFactory;import javax.swing.Box;import javax.swing.BoxLayout;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.border.Border;import saolei.frame.MymineFrame;public class AboutSweeping extends JDialog {/****/private static final long serialVersionUID = 1L;private JLabel labelIcon;private JLabel labelOne;private JLabel labelTwo;private JLabel labelThree;private JLabel labelFour;private JLabel labelFive;private Box boxOne;private Box boxTwo;private Box boxThree;private Box boxFour;private Box boxFive;private JPanel panelT;AboutSweeping sweep = null;public AboutSweeping() {}public AboutSweeping(MymineFrame mainFrame) {super(mainFrame);sweep = this;this.setTitle("关于扫雷");init();this.setSize(new Dimension(300, 200));this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);this.setLocationRelativeTo(mainFrame);//this.setResizable(false);this.setModal(true);this.setVisible(true);}private void init() {JPanel panel = new JPanel();labelIcon = new JLabel(new ImageIcon("./images/icon.gif"));labelOne = new JLabel("Java 扫雷智慧的挑战!");boxOne = Box.createHorizontalBox();boxOne.add(labelIcon);boxOne.add(Box.createHorizontalStrut(20));boxOne.add(labelOne);labelTwo = new JLabel("主要运用技术:swing和对象型数组");boxTwo = Box.createHorizontalBox();boxTwo.add(labelTwo);labelThree = new JLabel("主要知识:抽象类,继承,接口");boxThree = Box.createHorizontalBox();boxThree.add(labelThree);labelFour = new JLabel("版权所有:阿kiang");boxFour = Box.createHorizontalBox();boxFour.add(labelFour);labelFive = new JLabel("制作时间:2011.08.16");boxFive = Box.createHorizontalBox();boxFive.add(labelFive);panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));panel.add(boxOne);panel.add(boxTwo);panel.add(boxThree);panel.add(boxFour);panel.add(boxFive);JButton button = new JButton("确定");button.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {sweep.dispose();}});JPanel pl = new JPanel(new FlowLayout(FlowLayout.RIGHT));pl.add(button);panel.add(pl);Border border = BorderFactory.createEtchedBorder();panel.setBorder(border);panelT = new JPanel(new BorderLayout());Border b = BorderFactory.createEmptyBorder(10, 10, 10, 10);panelT.add(panel);panelT.setBorder(b);this.add(panel);}}扫雷英雄版package saolei.dialog;import java.awt.BorderLayout;import java.awt.Dimension;import java.util.SortedSet;import java.util.TreeSet;import javax.swing.JDialog;import javax.swing.JPanel;import javax.swing.JScrollPane;import javax.swing.JTextArea;import javax.swing.table.DefaultTableModel;import saolei.frame.MymineFrame;import ble.HeroBean;import saolei.tools.Tools;public class HeroDialog extends JDialog {/****/private static final long serialVersionUID = 1L;private JPanel panel = null;private JTextArea area;private SortedSet<HeroBean> heroSet;DefaultTableModel dataModel;private int level = 0;public HeroDialog(int level, MymineFrame mainFrame) { /*** 设置拥有者*/super(mainFrame);this.level = level;init();this.setSize(new Dimension(220, 150));this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);this.setLocationRelativeTo(mainFrame);this.setResizable(false);this.setModal(true);this.setVisible(true);}private void init() {heroSet = new TreeSet();area = new JTextArea();if (level == 1) {heroSet = Tools.setB;this.setTitle("初级英雄榜");} else if (level == 2) {heroSet = Tools.setI;this.setTitle("中级英雄榜");} else if (level == 3) {heroSet = Tools.setE;this.setTitle("高级英雄榜");}for (HeroBean bean : heroSet) {area.append(bean.toString() + "\n");}area.setEditable(false);JScrollPane jsp = new JScrollPane(area);panel = new JPanel(new BorderLayout());panel.add(jsp,BorderLayout.CENTER);this.add(panel);}}扫雷英雄版积分版package saolei.dialog;import java.awt.Dimension;import javax.swing.BorderFactory;import javax.swing.Box;import javax.swing.BoxLayout;import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextField;import javax.swing.border.Border;import saolei.frame.MymineFrame;import saolei.listener.HeroInputListener;import saolei.tools.Tools;public class HeroInputDialog extends JDialog{/****/private static final long serialVersionUID = 1L;private JTextField jtfN;private JLabel jlL;private JButton buttonY;private JButton buttonN;private JPanel panel;private Box box1;private Box box2;private Box box3;private HeroInputListener listen;public HeroInputDialog(MymineFrame mainFrame) {/**固定拥有者*/super(mainFrame);listen = new HeroInputListener(this);init();this.setTitle("请输入英雄大名");this.setSize(new Dimension(200, 150));this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);this.setLocationRelativeTo(mainFrame);this.setResizable(false);this.setModal(true);this.setVisible(true);}private void init() {jlL = new JLabel();if(Tools.mineCount==10){jlL.setText("完成初级扫雷,请留下大名!");}if(Tools.mineCount==40){jlL.setText("完成中级扫雷,请留下大名!");}if(Tools.mineCount==99){jlL.setText("完成高级扫雷,请留下大名!");}panel = new JPanel();panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));jtfN = new JTextField("匿名");jtfN.setPreferredSize(new Dimension(20,10));buttonY = new JButton("确定");buttonY.addActionListener(listen);buttonN = new JButton("取消");buttonN.addActionListener(listen);box1 = Box.createHorizontalBox();box1.add(jlL);box2 = Box.createHorizontalBox();box2.add(Box.createHorizontalStrut(30));box2.add(jtfN);box2.add(Box.createHorizontalStrut(30));box3 = Box.createHorizontalBox();box3.add(buttonY);box3.add(Box.createHorizontalStrut(10));box3.add(buttonN);panel.add(box1);panel.add(Box.createVerticalStrut(13));panel.add(box2);panel.add(Box.createVerticalStrut(13));panel.add(box3);Border border = BorderFactory.createEmptyBorder(15, 5, 10, 5);panel.setBorder(border);this.add(panel);}public JButton getButtonN() {return buttonN;}public JButton getButtonY() {return buttonY;}public JTextField getJtfN() {return jtfN;}}扫雷英雄版自定义对话框package saolei.dialog;import java.awt.BorderLayout;import java.awt.Dimension;import javax.swing.Box;import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextField;import saolei.frame.MymineFrame;import saolei.listener.SelfMineListener;import saolei.tools.Tools;public class Selfdefinedia extends JDialog{ private JPanel mianJPanel;private JPanel jPaneln;private JPanel jPanelc;private JPanel jPanels;private JLabel lx;private JLabel ly;private JLabel ll;private JTextField tx;private JTextField ty;private JTextField tl;private JButton sureButton;private JButton exitButton;public JPanel getMianJPanel() {return mianJPanel;}public void setMianJPanel(JPanel mianJPanel) {this.mianJPanel = mianJPanel;}public JPanel getjPaneln() {return jPaneln;}public void setjPaneln(JPanel jPaneln) { this.jPaneln = jPaneln;}public JPanel getjPanelc() {return jPanelc;}public void setjPanelc(JPanel jPanelc) { this.jPanelc = jPanelc;}public JPanel getjPanels() {return jPanels;}public void setjPanels(JPanel jPanels) { this.jPanels = jPanels;}public JLabel getLx() {return lx;}public void setLx(JLabel lx) {this.lx = lx;}public JLabel getLy() {return ly;}public void setLy(JLabel ly) {this.ly = ly;}public JLabel getLl() {return ll;}public void setLl(JLabel ll) {this.ll = ll;}public JTextField getTx() {return tx;}public void setTx(JTextField tx) { this.tx = tx;}public JTextField getTy() {return ty;}public void setTy(JTextField ty) {this.ty = ty;}public JTextField getTl() {return tl;}public void setTl(JTextField tl) {this.tl = tl;}public JButton getSureButton() {return sureButton;}public void setSureButton(JButton sureButton) { this.sureButton = sureButton;}public JButton getExitButton() {return exitButton;}public void setExitButton(JButton exitButton) { this.exitButton = exitButton;}public MymineFrame mymineFrame;public Selfdefinedia(MymineFrame mymineFrame){super(mymineFrame,"自定义扫雷",true);init();this.mymineFrame=mymineFrame;this.setLocationRelativeTo(mymineFrame);this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);this.setResizable(false);this.pack();this.setVisible(true);}private void init() {lx = new JLabel("行数:");ly = new JLabel("列数:");ll = new JLabel("雷数:");tx = new JTextField(Tools.rowCount+"");tx.setPreferredSize(new Dimension(40,20));ty = new JTextField(Tools.colCount+"");ty.setPreferredSize(new Dimension(40,20));tl = new JTextField(Tools.mineCount+"");tl.setPreferredSize(new Dimension(40,20));sureButton = new JButton("确定");sureButton.addActionListener(new SelfMineListener(this));exitButton = new JButton("取消");exitButton.addActionListener(new SelfMineListener(this));jPaneln = new JPanel();jPaneln.add(lx);jPaneln.add(tx);jPaneln.add(sureButton);jPanelc = new JPanel();jPanelc.add(ly);jPanelc.add(ty);jPanelc.add(Box.createHorizontalStrut(57));jPanels = new JPanel();jPanels.add(ll);jPanels.add(tl);jPanels.add(exitButton);mianJPanel = new JPanel();mianJPanel.setLayout(new BorderLayout());mianJPanel.add(jPaneln,BorderLayout.NORTH);mianJPanel.add(jPanelc,BorderLayout.CENTER);mianJPanel.add(jPanels,BorderLayout.SOUTH);this.add(mianJPanel);}}package ble;public class HeroBean implements Comparable{private String name = null;private String level = null;private int time = 0;public String getLevel() {return level;}public void setLevel(String level) {this.level = level;}public String getName() {return name;}public void setName(String name) { = name;}public int getTime() {return time;}public void setTime(int time) {this.time = time;}public int compareTo(Object o) {int i = -1;if(o instanceof HeroBean){HeroBean bean = (HeroBean)o;i = this.time-bean.time;if(i==0){i = .hashCode().hashCode();if(i==0){i=-1;}}}return i;}@Overridepublic String toString() {return + ":\t\t" + this.time+"秒";}}package ble;import javax.swing.ImageIcon;import javax.swing.JLabel;import saolei.panel.MybompPanel;import saolei.tools.Tools;public class MymineLable extends JLabel{ private int rowx;private int coly;private boolean ismine;private boolean isexpand;private int count;private int rightClick;private int leftClick;private boolean isFlag;private boolean isError;public boolean isError() {return isError;}public void setError(boolean isError) { this.isError = isError;}public boolean isFlag() {return isFlag;}public void setFlag(boolean isFlag) { this.isFlag = isFlag;}public int getLeftClick() {return leftClick;}public void setLeftClick(int leftClick) { this.leftClick = leftClick;}public int getRowx() {return rowx;}public void setRowx(int rowx) {this.rowx = rowx;}public int getColy() {return coly;}public void setColy(int coly) {this.coly = coly;}public boolean isIsmine() {return ismine;}public void setIsmine(boolean ismine) { this.ismine = ismine;}public boolean isIsexpand() {return isexpand;}public void setIsexpand(boolean isexpand) { this.isexpand = isexpand;}public int getCount() {return count;}public void setCount(int count) {this.count = count;}public int getRightClick() {return rightClick;}public void setRightClick(int rightClick) { this.rightClick = rightClick;}public MymineLable(int rowx,int coly) {this.rowx = rowx;this.coly = coly;this.setIcon(Tools.blank);}public void openMine(MybompPanel panel){if(this.getCount()==0){for(int i=this.getRowx()-1;i<=this.getRowx()+1;i++){for(int j=this.getColy()-1;j<=this.getColy()+1;j++){if(i>=0&&i<9&&j>=0&&j<9&&!(panel.getMymineLables()[i][j].equals(t his))){panel.getMymineLables()[i][j].setIcon(Tools.mineNumberIcon[panel. getMymineLables()[i][j].getCount()]);panel.getMymineLables()[i][j].setIsexpand(true);panel.getMymineLables()[i][j].openMine(panel);}}}}}}雷块package ble;import javax.swing.ImageIcon;import javax.swing.JLabel;import saolei.panel.MybompPanel;import saolei.tools.Tools;public class MymineLable extends JLabel{private int rowx;private int coly;private boolean ismine;private boolean isexpand;private int count;private int rightClick;private int leftClick;private boolean isFlag;private boolean isError;public boolean isError() {return isError;}public void setError(boolean isError) { this.isError = isError;}public boolean isFlag() {return isFlag;}public void setFlag(boolean isFlag) { this.isFlag = isFlag;}public int getLeftClick() {return leftClick;}public void setLeftClick(int leftClick) { this.leftClick = leftClick;}public int getRowx() {return rowx;}public void setRowx(int rowx) {this.rowx = rowx;}public int getColy() {return coly;}public void setColy(int coly) {this.coly = coly;}public boolean isIsmine() {return ismine;}public void setIsmine(boolean ismine) { this.ismine = ismine;}public boolean isIsexpand() {return isexpand;}public void setIsexpand(boolean isexpand) { this.isexpand = isexpand;}public int getCount() {return count;}public void setCount(int count) {this.count = count;}public int getRightClick() {return rightClick;}public void setRightClick(int rightClick) { this.rightClick = rightClick;}public MymineLable(int rowx,int coly) { this.rowx = rowx;this.coly = coly;this.setIcon(Tools.blank);}public void openMine(MybompPanel panel){if(this.getCount()==0){for(int i=this.getRowx()-1;i<=this.getRowx()+1;i++){for(int j=this.getColy()-1;j<=this.getColy()+1;j++){if(i>=0&&i<9&&j>=0&&j<9&&!(panel.getMymineLables()[i][j].equals(t his))){panel.getMymineLables()[i][j].setIcon(Tools.mineNumberIcon[panel. getMymineLables()[i][j].getCount()]);panel.getMymineLables()[i][j].setIsexpand(true);panel.getMymineLables()[i][j].openMine(panel);}}}}}}英雄监听package saolei.listener;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import saolei.dialog.HeroInputDialog;import ble.HeroBean;import saolei.tools.Tools;public class HeroInputListener implements ActionListener{ private HeroInputDialog heroInputDialog;public HeroInputListener(HeroInputDialog heroInputDialog) { this.heroInputDialog = heroInputDialog;}@Overridepublic void actionPerformed(ActionEvent e) {if (e.getSource().equals(heroInputDialog.getButtonY())) { String text = heroInputDialog.getJtfN().getText();if (text != null && text.length() != 0) {text = text.trim();//去除左右空格if (text.length() > 10) {text = text.substring(0, 10);}} else {text = "匿名";}HeroBean heroBean = new HeroBean();heroBean.setName(text);heroBean.setTime(Tools.myTimerTask.time);if (Tools.mineCount == 10) {heroBean.setLevel("初级");Tools.setB.add(heroBean);}if (Tools.mineCount == 40) {heroBean.setLevel("中级");Tools.setI.add(heroBean);}if (Tools.mineCount == 99) {heroBean.setLevel("高级");Tools.setE.add(heroBean);}heroInputDialog.dispose();} else if(e.getSource().equals(heroInputDialog.getButtonN())) { heroInputDialog.dispose();}}}重写鼠标监听package saolei.listener;import java.awt.event.InputEvent;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.util.Timer;import javax.swing.ImageIcon;import javax.swing.JLabel;import saolei.dialog.HeroInputDialog;import saolei.frame.MymineFrame;import ble.MymineLable;import saolei.panel.MybompPanel;import saolei.tools.Tools;public class MyListener implements MouseListener{//写鼠标监听,该类监听有依据鼠标不同动作private MybompPanel mybompPanel;//用于获取布雷面板private MymineLable mymineLable;//用于获取事件源private int leftClick;//左键一共击了多少次private boolean isLeftPress;//是否为左键击private boolean isDoublePress;//是否为左右键private boolean isRightpress;//是否为右键击private int bompCount=Tools.mineCount;//布了几个雷public boolean isRightpress() {return isRightpress;}public void setRightpress(boolean isRightpress) {this.isRightpress = isRightpress;}public boolean isLeftPress() {return isLeftPress;}public void setLeftPress(boolean isLeftPress) {this.isLeftPress = isLeftPress;}public boolean isDoublePress() {return isDoublePress;}public void setDoublePress(boolean isDoublePress) {this.isDoublePress = isDoublePress;}public MyListener(MybompPanel m){this.mybompPanel=m;}public void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub}public void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}public void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}/////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////public void mousePressed(MouseEvent e) {//鼠标点击未释放mymineLable=(MymineLable)(e.getSource());//左右击未释放if (e.getModifiersEx() == InputEvent.BUTTON1_DOWN_MASK+ InputEvent.BUTTON3_DOWN_MASK){setDoublePress(true);setLeftPress(false);setRightpress(false);Tools.faceLabel.setIcon(Tools.faceIcon[2]);//表情为惊讶if(!mymineLable.isIsexpand()){mymineLable.setIcon(new ImageIcon("./images/0.gif"));}for(inti=mymineLable.getRowx()-1;i<=mymineLable.getRowx()+1;i++){for(intj=mymineLable.getColy()-1;j<=mymineLable.getColy()+1;j++){if(i>=0&&i<Tools.rowCount&&j>=0&&j<Tools.colCount&&mybompPanel.ge tMymineLables()[i][j]!=mymineLable&&!(mybompPanel.getMymineLables()[i ][j].isIsexpand())&&(mybompPanel.getMymineLables()[i][j].getRightClick()!=1))//如果在区内且该雷不为被点的雷且被点的雷没有展开{if(mybompPanel.getMymineLables()[i][j].getRightClick()==2&&(mybom pPanel.getMymineLables()[i][j].getRightClick()!=1)){mybompPanel.getMymineLables()[i][j].setIcon(Tools.ask1);}if(mybompPanel.getMymineLables()[i][j].getRightClick()==0&&(mybom pPanel.getMymineLables()[i][j].getRightClick()!=1)){mybompPanel.getMymineLables()[i][j].setIcon(Tools.mineNumberIcon[ 0]);}}}}}///////////////////////////////////////////////////////////////// //////////////////////////////////////////if (e.getModifiers() == InputEvent.BUTTON1_MASK)//左键单击{setLeftPress(true);setRightpress(false);if(!mymineLable.isIsexpand()&&!isDoublePress()&&isLeftPress()) {for(int i=100000;i>0;i--){}if(!mymineLable.isIsexpand()&&!isDoublePress()&&isLeftPress()) {Tools.faceLabel.setIcon(Tools.faceIcon[2]);//表情为惊讶mymineLable.setIcon(newImageIcon("./images/0.gif"));//被击的凹下去}}}///////////////////////////////////////////////////////////////// ////////////////////////////if (e.getModifiers() == InputEvent.BUTTON3_MASK)//右击未释放{setLeftPress(false);setRightpress(true);if(!mymineLable.isIsexpand()&&!isDoublePress()&&isRightpress()){for(int i=100000;i>0;i--){}if(!mymineLable.isIsexpand()&&!isDoublePress()&&isRightpress()){mymineLable.setRightClick(mymineLable.getRightClick()+1);//该lable 右击次数加1。
教你使⽤Java实现扫雷⼩游戏(最新完整版)⽬录效果展⽰主类:GameWin类底层地图MapBottom类顶层地图MapTop类底层数字BottomNum类初始化地雷BottomRay类⼯具GameUtil类总结⼤家好,我是orangemilk_,哈哈,学习Java已经到⼀个阶段啦,今天我们使⽤GUI来写⼀个扫雷⼩游戏吧!效果展⽰主类:GameWin类package com.sxt;import javax.swing.*;import java.awt.*;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;public class GameWin extends JFrame {int width = 2 * GameUtil.OFFSET + GameUtil.MAP_W * GameUtil.SQUARE_LENGTH;int height = 4 * GameUtil.OFFSET + GameUtil.MAP_H * GameUtil.SQUARE_LENGTH;Image offScreenImage = null;MapBottom mapBottom = new MapBottom();MapTop mapTop = new MapTop();void launch(){GameUtil.START_TIME=System.currentTimeMillis();this.setVisible(true);this.setSize(width,height);this.setLocationRelativeTo(null);this.setTitle("Java扫雷⼩游戏");this.setDefaultCloseOperation(EXIT_ON_CLOSE);//⿏标事件this.addMouseListener(new MouseAdapter() {@Overridepublic void mouseClicked(MouseEvent e) {super.mouseClicked(e);switch (GameUtil.state){case 0 :if(e.getButton()==1){GameUtil.MOUSE_X = e.getX();GameUtil.MOUSE_Y = e.getY();GameUtil.LEFT = true;}if(e.getButton()==3) {GameUtil.MOUSE_X = e.getX();GameUtil.MOUSE_Y = e.getY();GameUtil.RIGHT = true;}//去掉break,任何时候都监听⿏标事件case 1 :case 2 :if(e.getButton()==1){if(e.getX()>GameUtil.OFFSET + GameUtil.SQUARE_LENGTH*(GameUtil.MAP_W/2)&& e.getX()<GameUtil.OFFSET + GameUtil.SQUARE_LENGTH*(GameUtil.MAP_W/2) + GameUtil.SQUARE_LENGTH&& e.getY()>GameUtil.OFFSET&& e.getY()<GameUtil.OFFSET+GameUtil.SQUARE_LENGTH){mapBottom.reGame();mapTop.reGame();GameUtil.FLAG_NUM=0;GameUtil.START_TIME=System.currentTimeMillis();GameUtil.state=0;break;default:}}});while (true){repaint();try {Thread.sleep(40);} catch (InterruptedException e) {e.printStackTrace();}}}@Overridepublic void paint(Graphics g) {offScreenImage = this.createImage(width,height);Graphics gImage = offScreenImage.getGraphics();//设置背景颜⾊gImage.setColor(Color.lightGray);gImage.fillRect(0,0,width,height);mapBottom.paintSelf(gImage);mapTop.paintSelf(gImage);g.drawImage(offScreenImage,0,0,null);}public static void main(String[] args) {GameWin gameWin = new GameWin();unch();}}底层地图MapBottom类//底层地图:绘制游戏相关组件package com.sxt;import java.awt.*;public class MapBottom {BottomRay bottomRay = new BottomRay();BottomNum bottomNum = new BottomNum();{bottomRay.newRay();bottomNum.newNum();}//重置游戏void reGame(){for (int i = 1; i <=GameUtil.MAP_W ; i++) {for (int j = 1; j <=GameUtil.MAP_H ; j++) {GameUtil.DATA_BOTTOM[i][j]=0;}}bottomRay.newRay();bottomNum.newNum();}//绘制⽅法void paintSelf(Graphics g){g.setColor(Color.BLACK);//画竖线for (int i = 0; i <= GameUtil.MAP_W; i++) {g.drawLine(GameUtil.OFFSET + i * GameUtil.SQUARE_LENGTH,3*GameUtil.OFFSET,GameUtil.OFFSET+i*GameUtil.SQUARE_LENGTH,3*GameUtil.OFFSET+GameUtil.MAP_H*GameUtil.SQUARE_LENGTH);}//画横线for (int i = 0; i <=GameUtil.MAP_H; i++){g.drawLine(GameUtil.OFFSET,3*GameUtil.OFFSET+i*GameUtil.SQUARE_LENGTH,GameUtil.OFFSET+GameUtil.MAP_W*GameUtil.SQUARE_LENGTH,3*GameUtil.OFFSET+i*GameUtil.SQUARE_LENGTH);}for (int i = 1; i <= GameUtil.MAP_W ; i++) {for (int j = 1; j <= GameUtil.MAP_H; j++) {//雷if (GameUtil.DATA_BOTTOM[i][j] == -1) {g.drawImage(GameUtil.lei,GameUtil.OFFSET + (i - 1) * GameUtil.SQUARE_LENGTH + 1,GameUtil.OFFSET * 3 + (j - 1) * GameUtil.SQUARE_LENGTH + 1,GameUtil.SQUARE_LENGTH - 2,GameUtil.SQUARE_LENGTH - 2,null);}//数字if (GameUtil.DATA_BOTTOM[i][j] >=0) {g.drawImage(GameUtil.images[GameUtil.DATA_BOTTOM[i][j]],GameUtil.OFFSET + (i - 1) * GameUtil.SQUARE_LENGTH + 15,GameUtil.OFFSET * 3 + (j - 1) * GameUtil.SQUARE_LENGTH + 5,null);}}}//绘制数字,剩余雷数,倒计时GameUtil.drawWord(g,""+(GameUtil.RAY_MAX-GameUtil.FLAG_NUM),GameUtil.OFFSET,2*GameUtil.OFFSET,30,Color.red);GameUtil.drawWord(g,""+(GameUtil.END_TIME-GameUtil.START_TIME)/1000,GameUtil.OFFSET + GameUtil.SQUARE_LENGTH*(GameUtil.MAP_W-1),2*GameUtil.OFFSET,30,Color.red);switch (GameUtil.state){case 0:GameUtil.END_TIME=System.currentTimeMillis();g.drawImage(GameUtil.face,GameUtil.OFFSET + GameUtil.SQUARE_LENGTH * (GameUtil.MAP_W/2), GameUtil.OFFSET,null);break;case 1:g.drawImage(GameUtil.win,GameUtil.OFFSET + GameUtil.SQUARE_LENGTH * (GameUtil.MAP_W/2), GameUtil.OFFSET,null);g.drawImage(GameUtil.over,GameUtil.OFFSET + GameUtil.SQUARE_LENGTH * (GameUtil.MAP_W/2),GameUtil.OFFSET,null);break;default:}}}顶层地图MapTop类顶层地图类:绘制顶层组件package com.sxt;import java.awt.*;public class MapTop {//格⼦位置int temp_x;int temp_y;//重置游戏void reGame(){for (int i = 1; i <=GameUtil.MAP_W ; i++) {for (int j = 1; j <=GameUtil.MAP_H ; j++) {GameUtil.DATA_TOP[i][j]=0;}}}//判断逻辑void logic(){temp_x=0;temp_y=0;if(GameUtil.MOUSE_X>GameUtil.OFFSET && GameUtil.MOUSE_Y>3*GameUtil.OFFSET){ temp_x = (GameUtil.MOUSE_X - GameUtil.OFFSET)/GameUtil.SQUARE_LENGTH+1;temp_y = (GameUtil.MOUSE_Y - GameUtil.OFFSET * 3)/GameUtil.SQUARE_LENGTH+1; }if(temp_x>=1 && temp_x<=GameUtil.MAP_W&& temp_y>=1 && temp_y<=GameUtil.MAP_H){if(GameUtil.LEFT){//覆盖,则翻开if(GameUtil.DATA_TOP[temp_x][temp_y]==0){GameUtil.DATA_TOP[temp_x][temp_y]=-1;}spaceOpen(temp_x,temp_y);GameUtil.LEFT=false;}if(GameUtil.RIGHT){//覆盖则插旗if(GameUtil.DATA_TOP[temp_x][temp_y]==0){GameUtil.DATA_TOP[temp_x][temp_y]=1;GameUtil.FLAG_NUM++;}//插旗则取消else if(GameUtil.DATA_TOP[temp_x][temp_y]==1){GameUtil.DATA_TOP[temp_x][temp_y]=0;GameUtil.FLAG_NUM--;}else if(GameUtil.DATA_TOP[temp_x][temp_y]==-1){numOpen(temp_x,temp_y);}GameUtil.RIGHT=false;}}boom();victory();}//数字翻开void numOpen(int x,int y){//记录旗数int count=0;if(GameUtil.DATA_BOTTOM[x][y]>0){for (int i = x-1; i <=x+1 ; i++) {for (int j = y-1; j <=y+1 ; j++) {if(GameUtil.DATA_TOP[i][j]==1){count++;}}}if(count==GameUtil.DATA_BOTTOM[x][y]){for (int i = x-1; i <=x+1 ; i++) {for (int j = y-1; j <=y+1 ; j++) {if(GameUtil.DATA_TOP[i][j]!=1){GameUtil.DATA_TOP[i][j]=-1;}//必须在雷区当中if(i>=1&&j>=1&&i<=GameUtil.MAP_W&&j<=GameUtil.MAP_H){spaceOpen(i,j);}}}}}}//失败判定 t 表⽰失败 f 未失败boolean boom(){if(GameUtil.FLAG_NUM==GameUtil.RAY_MAX){for (int i = 1; i <=GameUtil.MAP_W ; i++) {for (int j = 1; j <=GameUtil.MAP_H ; j++) {if(GameUtil.DATA_TOP[i][j]==0){GameUtil.DATA_TOP[i][j]=-1;}}}}for (int i = 1; i <=GameUtil.MAP_W ; i++) {for (int j = 1; j <=GameUtil.MAP_H ; j++) {if(GameUtil.DATA_BOTTOM[i][j]==-1&&GameUtil.DATA_TOP[i][j]==-1){GameUtil.state = 2;seeBoom();return true;}}//失败显⽰void seeBoom(){for (int i = 1; i <=GameUtil.MAP_W ; i++) {for (int j = 1; j <=GameUtil.MAP_H ; j++) {//底层是雷,顶层不是旗,显⽰if(GameUtil.DATA_BOTTOM[i][j]==-1&&GameUtil.DATA_TOP[i][j]!=1){GameUtil.DATA_TOP[i][j]=-1;}//底层不是雷,顶层是旗,显⽰差错旗if(GameUtil.DATA_BOTTOM[i][j]!=-1&&GameUtil.DATA_TOP[i][j]==1){GameUtil.DATA_TOP[i][j]=2;}}}}//胜利判断 t 表⽰胜利 f 未胜利boolean victory(){//统计未打开格⼦数int count=0;for (int i = 1; i <=GameUtil.MAP_W ; i++) {for (int j = 1; j <=GameUtil.MAP_H ; j++) {if(GameUtil.DATA_TOP[i][j]!=-1){count++;}}}if(count==GameUtil.RAY_MAX){GameUtil.state=1;for (int i = 1; i <=GameUtil.MAP_W ; i++) {for (int j = 1; j <=GameUtil.MAP_H ; j++) {//未翻开,变成旗if(GameUtil.DATA_TOP[i][j]==0){GameUtil.DATA_TOP[i][j]=1;}}}return true;}return false;}//打开空格void spaceOpen(int x,int y){if(GameUtil.DATA_BOTTOM[x][y]==0){for (int i = x-1; i <=x+1 ; i++) {for (int j = y-1; j <=y+1 ; j++) {//覆盖,才递归if(GameUtil.DATA_TOP[i][j]!=-1){if(GameUtil.DATA_TOP[i][j]==1){GameUtil.FLAG_NUM--;}GameUtil.DATA_TOP[i][j]=-1;//必须在雷区当中if(i>=1&&j>=1&&i<=GameUtil.MAP_W&&j<=GameUtil.MAP_H){spaceOpen(i,j);}}}}}}//绘制⽅法void paintSelf(Graphics g){logic();for (int i = 1; i <= GameUtil.MAP_W ; i++) {for (int j = 1; j <= GameUtil.MAP_H; j++) {//覆盖if (GameUtil.DATA_TOP[i][j] == 0) {g.drawImage(GameUtil.top,GameUtil.OFFSET + (i - 1) * GameUtil.SQUARE_LENGTH + 1,GameUtil.OFFSET * 3 + (j - 1) * GameUtil.SQUARE_LENGTH + 1, GameUtil.SQUARE_LENGTH - 2,GameUtil.SQUARE_LENGTH - 2,null);}//插旗if (GameUtil.DATA_TOP[i][j] == 1) {g.drawImage(GameUtil.flag,GameUtil.OFFSET + (i - 1) * GameUtil.SQUARE_LENGTH + 1,GameUtil.OFFSET * 3 + (j - 1) * GameUtil.SQUARE_LENGTH + 1, GameUtil.SQUARE_LENGTH - 2,GameUtil.SQUARE_LENGTH - 2,null);}//差错旗if (GameUtil.DATA_TOP[i][j] == 2) {g.drawImage(GameUtil.noflag,GameUtil.OFFSET + (i - 1) * GameUtil.SQUARE_LENGTH + 1,GameUtil.OFFSET * 3 + (j - 1) * GameUtil.SQUARE_LENGTH + 1, GameUtil.SQUARE_LENGTH - 2,GameUtil.SQUARE_LENGTH - 2,null);}}}}}底层数字BottomNum类//底层数字类package com.sxt;public class BottomNum {void newNum() {for (int i = 1; i <=GameUtil.MAP_W ; i++) {for (int j = 1; j <=GameUtil.MAP_H ; j++) {if(GameUtil.DATA_BOTTOM[i][j]==-1){for (int k = i-1; k <=i+1 ; k++) {for (int l = j-1; l <=j+1 ; l++) {if(GameUtil.DATA_BOTTOM[k][l]>=0){}}}}}}初始化地雷BottomRay类//初始化地雷类package com.sxt;public class BottomRay {//存放坐标int[] rays = new int[GameUtil.RAY_MAX*2];//地雷坐标int x,y;//是否放置 T 表⽰可以放置 F 不可放置boolean isPlace = true;//⽣成雷void newRay() {for (int i = 0; i < GameUtil.RAY_MAX*2 ; i=i+2) {x= (int) (Math.random()*GameUtil.MAP_W +1);//1-12y= (int) (Math.random()*GameUtil.MAP_H +1);//1-12//判断坐标是否存在for (int j = 0; j < i ; j=j+2) {if(x==rays[j] && y==rays[j+1]){i=i-2;isPlace = false;break;}}//将坐标放⼊数组if(isPlace){rays[i]=x;rays[i+1]=y;}isPlace = true;}for (int i = 0; i < GameUtil.RAY_MAX*2; i=i+2) {GameUtil.DATA_BOTTOM[rays[i]][rays[i+1]]=-1;}}}⼯具GameUtil类//⼯具类:存放静态参数,⼯具⽅法package com.sxt;import java.awt.*;public class GameUtil {//地雷个数static int RAY_MAX = 5;//地图的宽static int MAP_W = 11;//地图的⾼static int MAP_H = 11;//雷区偏移量static int OFFSET = 45;//格⼦边长static int SQUARE_LENGTH = 50;//插旗数量static int FLAG_NUM = 0;//⿏标相关//坐标static int MOUSE_X;static int MOUSE_Y;//状态static boolean LEFT = false;static boolean RIGHT = false;//游戏状态 0 表⽰游戏中 1 胜利 2 失败static int state = 0;//倒计时static long START_TIME;static long END_TIME;//底层元素 -1 雷 0 空 1-8 表⽰对应数字static int[][] DATA_BOTTOM = new int[MAP_W+2][MAP_H+2];//顶层元素 -1 ⽆覆盖 0 覆盖 1 插旗 2 差错旗static int[][] DATA_TOP = new int[MAP_W+2][MAP_H+2];//载⼊图⽚static Image lei = Toolkit.getDefaultToolkit().getImage("imgs/lei.png");static Image top = Toolkit.getDefaultToolkit().getImage("imgs/top.gif");static Image flag = Toolkit.getDefaultToolkit().getImage("imgs/flag.gif");static Image noflag = Toolkit.getDefaultToolkit().getImage("imgs/noflag.png");static Image face = Toolkit.getDefaultToolkit().getImage("imgs/face.png");static Image over = Toolkit.getDefaultToolkit().getImage("imgs/over.png");static Image win = Toolkit.getDefaultToolkit().getImage("imgs/win.png");static Image[] images = new Image[9];static {for (int i = 1; i <=8 ; i++) {images[i] = Toolkit.getDefaultToolkit().getImage("imgs/num/"+i+".png");}}static void drawWord(Graphics g,String str,int x,int y,int size,Color color){g.setColor(color);g.setFont(new Font("仿宋",Font.BOLD,size));g.drawString(str,x,y);}}总结在使⽤Java编写扫雷⼩游戏时遇到了很多问题,在解决问题时,确实对java的⾯向对象编程有了更加深⼊的理解。
import javax.swing.ImageIcon;public class Block {String name; //名字,比如"雷"或数字int aroundMineNumber; //周围雷的数目ImageIcon mineIcon; //雷的图标boolean isMine=false; //是否是雷boolean isMark=false; //是否被标记boolean isOpen=false; //是否被挖开public void setName(String name) {=name;}public void setAroundMineNumber(int n) {aroundMineNumber=n;}public int getAroundMineNumber() {return aroundMineNumber;}public String getName() {return name;}public boolean isMine() {return isMine;}public void setIsMine(boolean b) {isMine=b;}public void setMineIcon(ImageIcon icon){mineIcon=icon;}public ImageIcon getMineicon(){return mineIcon;}public boolean getIsOpen() {return isOpen;}public void setIsOpen(boolean p) {isOpen=p;}public boolean getIsMark() {return isMark;}public void setIsMark(boolean m) {isMark=m;}}import java.util.*;import javax.swing.*;public class LayMines{ImageIcon mineIcon;LayMines() {mineIcon=new ImageIcon("mine.gif");}public void layMinesForBlock(Block block[][],int mineCount){ int row=block.length;int column=block[0].length;LinkedList<Block> list=new LinkedList<Block>();for(int i=0;i<row;i++) {for(int j=0;j<column;j++)list.add(block[i][j]);}while(mineCount>0){int size=list.size(); // list返回节点的个数int randomIndex=(int)(Math.random()*size);Block b=list.get(randomIndex);b.setIsMine(true);b.setName("雷");b.setMineIcon(mineIcon);list.remove(randomIndex); //list删除索引值为randomIndex的节点mineCount--;}for(int i=0;i<row;i++){for(int j=0;j<column;j++){if(block[i][j].isMine()){block[i][j].setIsOpen(false);block[i][j].setIsMark(false);}else {int mineNumber=0;for(int k=Math.max(i-1,0);k<=Math.min(i+1,row-1);k++) {for(int t=Math.max(j-1,0);t<=Math.min(j+1,column-1);t++){if(block[k][t].isMine())mineNumber++;}}block[i][j].setIsOpen(false);block[i][j].setIsMark(false);block[i][j].setName(""+mineNumber);block[i][j].setAroundMineNumber(mineNumber);}}}}}import java.awt.*;import java.awt.event.*;import javax.swing.*;public class MineArea extends JPanel implements ActionListener,MouseListener{ JButton reStart;Block [][] block;BlockView [][] blockView;LayMines lay;int row,colum,mineCount,markMount; //雷区的行数、列数以及地雷个数和用户给出的标记数ImageIcon mark;int grade;JPanel pCenter,pNorth;JTextField showTime,showMarkedMineCount; //显示用时以及标记数Timer time; //计时器int spendTime=0;Record record;public MineArea(int row,int colum,int mineCount,int grade) {reStart=new JButton("重新开始");mark=new ImageIcon("mark.gif"); //探雷标记time=new Timer(1000,this);showTime=new JTextField(5);showMarkedMineCount=new JTextField(5);showTime.setHorizontalAlignment(JTextField.CENTER);showMarkedMineCount.setHorizontalAlignment(JTextField.CENTER);showMarkedMineCount.setFont(new Font("Arial",Font.BOLD,16));showTime.setFont(new Font("Arial",Font.BOLD,16));pCenter=new JPanel();pNorth=new JPanel();lay=new LayMines();initMineArea(row,colum,mineCount,grade); //初始化雷区,见下面的LayMines()reStart.addActionListener(this);pNorth.add(showMarkedMineCount);pNorth.add(reStart);pNorth.add(showTime);setLayout(new BorderLayout());add(pNorth,BorderLayout.NORTH);add(pCenter,BorderLayout.CENTER);}public void initMineArea(int row,int colum,int mineCount,int grade){ pCenter.removeAll();spendTime=0;markMount=mineCount;this.row=row;this.colum=colum;this.mineCount=mineCount;this.grade=grade;block=new Block[row][colum];for(int i=0;i<row;i++){for(int j=0;j<colum;j++)block[i][j]=new Block();}yMinesForBlock(block,mineCount);blockView=new BlockView[row][colum];pCenter.setLayout(new GridLayout(row,colum));for(int i=0;i<row;i++) {for(int j=0;j<colum;j++) {blockView[i][j]=new BlockView();blockView[i][j].giveView(block[i][j]); //给block[i][j]提供视图pCenter.add(blockView[i][j]);blockView[i][j].getBlockCover().addActionListener(this);blockView[i][j].getBlockCover().addMouseListener(this);blockView[i][j].seeBlockCover();blockView[i][j].getBlockCover().setEnabled(true);blockView[i][j].getBlockCover().setIcon(null);}}showMarkedMineCount.setText(""+markMount);validate();}public void setRow(int row){this.row=row;}public void setColum(int colum){this.colum=colum;}public void setMineCount(int mineCount){this.mineCount=mineCount;}public void setGrade(int grade) {this.grade=grade;}public void actionPerformed(ActionEvent e) {if(e.getSource()!=reStart&&e.getSource()!=time) {time.start();int m=-1,n=-1;for(int i=0;i<row;i++) {for(int j=0;j<colum;j++) {if(e.getSource()==blockView[i][j].getBlockCover()){m=i;n=j;break;}}}if(block[m][n].isMine()) {for(int i=0;i<row;i++) {for(int j=0;j<colum;j++) {blockView[i][j].getBlockCover().setEnabled(false);if(block[i][j].isMine())blockView[i][j].seeBlockNameOrIcon();}}time.stop();spendTime=0;markMount=mineCount;}else {show(m,n); //见本类后面的show方法}}if(e.getSource()==reStart) {initMineArea(row,colum,mineCount,grade);}if(e.getSource()==time){spendTime++;showTime.setText(""+spendTime);}inquireWin();}public void show(int m,int n) {if(block[m][n].getAroundMineNumber()>0&&block[m][n].getIsOpen()==false){ blockView[m][n].seeBlockNameOrIcon();block[m][n].setIsOpen(true);return;}elseif(block[m][n].getAroundMineNumber()==0&&block[m][n].getIsOpen()==false){ blockView[m][n].seeBlockNameOrIcon();block[m][n].setIsOpen(true);for(int k=Math.max(m-1,0);k<=Math.min(m+1,row-1);k++) {for(int t=Math.max(n-1,0);t<=Math.min(n+1,colum-1);t++)show(k,t);}}}public void mousePressed(MouseEvent e){JButton source=(JButton)e.getSource();for(int i=0;i<row;i++) {for(int j=0;j<colum;j++) {if(e.getModifiers()==InputEvent.BUTTON3_MASK&&source==blockView[i][j].getBlockCover()){if(block[i][j].getIsMark()) {source.setIcon(null);block[i][j].setIsMark(false);markMount=markMount+1;showMarkedMineCount.setText(""+markMount);}else{source.setIcon(mark);block[i][j].setIsMark(true);markMount=markMount-1;showMarkedMineCount.setText(""+markMount);}}}}}public void inquireWin(){int number=0;for(int i=0;i<row;i++) {for(int j=0;j<colum;j++) {if(block[i][j].getIsOpen()==false)number++;}}if(number==mineCount){time.stop();record=new Record();switch(grade){case 1: record.setGrade("初级");break;case 2: record.setGrade("中级");break;case 3: record.setGrade("高级");break;}record.setTime(spendTime);record.setVisible(true);}}public void mouseReleased(MouseEvent e){} public void mouseEntered(MouseEvent e){} public void mouseExited(MouseEvent e){}public void mouseClicked(MouseEvent e){}}import java.awt.event.*;import java.awt.*;import javax.swing.*;import javax.swing.border.*;import java.util.*;import java.io.*;public class MineGame extends JFrame implements ActionListener{ JMenuBar bar;JMenu fileMenu;JMenuItem 初级,中级,高级,扫雷英雄榜;MineArea mineArea=null;File 英雄榜=new File("英雄榜.txt");Hashtable hashtable=null;ShowRecord showHeroRecord=null;MineGame(){mineArea=new MineArea(16,16,40,1);add(mineArea,BorderLayout.CENTER);bar=new JMenuBar();fileMenu=new JMenu("游戏");初级=new JMenuItem("初级");中级=new JMenuItem("中级");高级=new JMenuItem("高级");扫雷英雄榜=new JMenuItem("扫雷英雄榜");fileMenu.add(初级);fileMenu.add(中级);fileMenu.add(高级);fileMenu.add(扫雷英雄榜);bar.add(fileMenu);setJMenuBar(bar);初级.addActionListener(this);中级.addActionListener(this);高级.addActionListener(this);扫雷英雄榜.addActionListener(this);hashtable=new Hashtable();hashtable.put("初级","初级#"+999+"#匿名");hashtable.put("中级","中级#"+999+"#匿名");hashtable.put("高级","高级#"+999+"#匿名");if(!英雄榜.exists()) {try{ FileOutputStream out=new FileOutputStream(英雄榜);ObjectOutputStream objectOut=new ObjectOutputStream(out);objectOut.writeObject(hashtable);objectOut.close();out.close();}catch(IOException e){}}showHeroRecord=new ShowRecord(this,hashtable);setBounds(100,100,280,380);setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);validate();}public void actionPerformed(ActionEvent e){if(e.getSource()==初级){mineArea.initMineArea(8,8,10,1);setBounds(100,100,200,280);}if(e.getSource()==中级){mineArea.initMineArea(16,16,40,2);setBounds(100,100,280,380);}if(e.getSource()==高级){mineArea.initMineArea(22,22,99,3);setBounds(100,100,350,390);}if(e.getSource()==扫雷英雄榜){if(showHeroRecord!=null)showHeroRecord.setVisible(true);}validate();}public static void main(String args[]){new MineGame();}}import java.io.*;import java.util.*;import javax.swing.*;import java.awt.event.*;import java.awt.*;public class Record extends JDialog implements ActionListener{ int time=0;String grade=null;String key=null;String message=null;JTextField textName;JLabel label=null;JButton 确定,取消;public Record(){setTitle("记录你的成绩");this.time=time;this.grade=grade;setBounds(100,100,240,160);setResizable(false);setModal(true);确定=new JButton("确定");取消=new JButton("取消");textName=new JTextField(8);textName.setText("匿名");确定.addActionListener(this);取消.addActionListener(this);setLayout(new GridLayout(2,1));label=new JLabel("您现在是...高手,输入您的大名上榜");add(label);JPanel p=new JPanel();p.add(textName);p.add(确定);p.add(取消);add(p);setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);}public void setGrade(String grade){this.grade=grade;label.setText("您现在是"+grade+"高手,输入您的大名上榜"); }public void setTime(int time){this.time=time;}public void actionPerformed(ActionEvent e){if(e.getSource()==确定){message=grade+"#"+time+"#"+" "+textName.getText();key=grade;writeRecord(key,message);setVisible(false);}if(e.getSource()==取消){setVisible(false);}}public void writeRecord(String key,String message){File f=new File("英雄榜.txt");try{ FileInputStream in=new FileInputStream(f);ObjectInputStream object_in=new ObjectInputStream(in);Hashtable hashtable=(Hashtable)object_in.readObject();object_in.close();in.close();String temp=(String)hashtable.get(key);StringTokenizer fenxi=new StringTokenizer(temp,"#");fenxi.nextToken();int n=Integer.parseInt(fenxi.nextToken());if(time<n){hashtable.put(key,message);FileOutputStream out=new FileOutputStream(f);ObjectOutputStream object_out=new ObjectOutputStream(out);object_out.writeObject(hashtable);object_out.close();out.close();}}catch(Exception e) {System.out.println(e);}}}import java.io.*;import java.util.*;import javax.swing.*;import java.awt.event.*;import java.awt.*;public class ShowRecord extends JDialog implements ActionListener{ File file=new File("英雄榜.txt");String name=null;Hashtable hashtable=null;JButton 显示,重新记分;JLabel label初级[],label中级[],label高级[];public ShowRecord(JFrame frame,Hashtable h) {setTitle("扫雷英雄榜");hashtable=h;setBounds(100,100,320,185);setResizable(false);setVisible(false);setModal(true);label初级=new JLabel[3];label中级=new JLabel[3];label高级=new JLabel[3];for(int i=0;i<3;i++) {label初级[i]=new JLabel();label初级[i].setBorder(null);label中级[i]=new JLabel();label中级[i].setBorder(null);label高级[i]=new JLabel();label高级[i].setBorder(null);}label初级[0].setText("初级");label初级[1].setText(""+999);label初级[1].setText("匿名");label中级[0].setText("中级");label中级[1].setText(""+999);label中级[1].setText("匿名");label高级[0].setText("高级");label高级[1].setText(""+999);label高级[1].setText("匿名");JPanel pCenter=new JPanel();pCenter.setLayout(new GridLayout(3,3));for(int i=0;i<3;i++)pCenter.add(label初级[i]);for(int i=0;i<3;i++)pCenter.add(label中级[i]);for(int i=0;i<3;i++)pCenter.add(label高级[i]);pCenter.setBorder(BorderFactory.createTitledBorder("扫雷英雄榜"));显示=new JButton("显示成绩");重新记分=new JButton("重新记分");显示.addActionListener(this);重新记分.addActionListener(this);JPanel pSouth=new JPanel();pSouth.setLayout(new FlowLayout(FlowLayout.RIGHT));pSouth.add(重新记分);pSouth.add(显示);add(pCenter,BorderLayout.CENTER);add(pSouth,BorderLayout.SOUTH) ;}public void readAndShow(){try{ FileInputStream in=new FileInputStream(file);ObjectInputStream object_in=new ObjectInputStream(in);hashtable=(Hashtable)object_in.readObject();object_in.close();in.close();String temp=(String)hashtable.get("初级");StringTokenizer fenxi=new StringTokenizer(temp,"#");label初级[0].setText(fenxi.nextToken());label初级[1].setText(fenxi.nextToken());label初级[2].setText(fenxi.nextToken());temp=(String)hashtable.get("中级");fenxi=new StringTokenizer(temp,"#");label中级[0].setText(fenxi.nextToken());label中级[1].setText(fenxi.nextToken());label中级[2].setText(fenxi.nextToken());temp=(String)hashtable.get("高级");fenxi=new StringTokenizer(temp,"#");label高级[0].setText(fenxi.nextToken());label高级[1].setText(fenxi.nextToken());label高级[2].setText(fenxi.nextToken());}catch(Exception e){}}public void actionPerformed(ActionEvent e) {if(e.getSource()==重新记分) {hashtable.put("初级","初级#"+999+"#匿名");label初级[0].setText("初级");label初级[1].setText(""+999);label初级[2].setText("匿名");hashtable.put("中级","中级#"+999+"#匿名");label中级[0].setText("初级");label中级[1].setText(""+999);label中级[2].setText("匿名");hashtable.put("高级","高级#"+999+"#匿名");label高级[0].setText("初级");label高级[1].setText(""+999);label高级[2].setText("匿名");try{ FileOutputStream out=new FileOutputStream(file);ObjectOutputStream object_out=new ObjectOutputStream(out);object_out.writeObject(hashtable);object_out.close();out.close();}catch(IOException event){}setVisible(false);}if(e.getSource()==显示){readAndShow();}}}。
1设计题目及具体要求设计题目:扫雷游戏的开发题目需求:玩者进入游戏后,开始游戏,目的是为了找出所有隐藏的小方格后一定数目地雷,进行标记,把所有地雷找出并用时最少的胜利者进出扫雷英雄榜。
单击游戏菜单可以选择<初级>,<高级>,<中级>和<扫雷英雄榜>。
扫雷的各个级别是根据游戏的总格子数和地雷总数来区别的,初级的总格子数最少,地雷数也最少,高级的总格子数和地雷数最多。
扫雷英雄榜中记录着各个级别的第一名玩家,而且玩家可以刷新纪录。
游戏上方可以显示这盘中还有多少颗地雷,还可以显示在这盘游戏中游戏进行了多长时间。
选择级别后游戏去会出现相应的扫雷区域,这是玩家用鼠标单击任意一个方格,开始计时及游戏开始。
玩家要揭开某个方块可单击它,若该方块不是雷,会显示出一个数字或者是一个空格子这表示一概方格为中心周围的把各方格子中总共有多少颗地雷,玩家需要进行判断继续游戏,若是地雷则玩家输了这盘游戏,这时玩家可以退出游戏或选择重新开始。
若玩家确定某个方格子底下是地雷,这是可以单击鼠标右键,不管是不是正确,这时会出现一个小旗子标志,同时剩余地雷数减一个。
游戏胜利后,系统会弹出对话框保存成绩可以记录胜利者的名字。
实现环境及工具简介系统开发平台:Eclipse1.7数据库管理系统软件:Oracle运行平台:windows XPJava开发包:jdk7.02总体设计总体设计:再设计扫雷游戏时,需要编写7个源文件:MineGame.java,MineArea.java,Block.java,BlockView.java,LayMines.java,ShowRecord.java,Record.java 除了这七个源文件外,还需要Java系统提供一些重要的类,如File,JButton和JLabel等类。
2.1 MineGame.java(主类):主要负责创建扫雷游戏主窗口,该文件有main方法,扫雷游戏从该类开始执行。
java扫雷小游戏import java.awt.*;import java.awt.event.*;import javax.swing.*;/*按扭类*/class Bomb extends JButton{public int num_x,num_y; //第几号方块public int BombRoundCount; //周围雷数public boolean isBomb; //是否为雷public boolean isClicked; //是否被点击public int BombFlag; //探雷标记public boolean isRight; //是否点击右键public Bomb(int x,int y){BombFlag = 0;num_x = x;num_y = y;BombRoundCount = 0;isBomb = false;isClicked = false;isRight = false;}}/*窗口及算法实现类*/class MainBomb extends JFrame implements ActionListener,MouseListener{int x=64,e=10;String n="Color.blue";public JTextField text;public Label nowBomb,setBomb;public int BlockNum,BombNum; //当前方块数当前雷数 public Icon icon_bomb = new ImageIcon("Bomb.gif"); //踩雷public Icon icon_bomb_big = new ImageIcon("bomb_big.gif"); //踩雷标记 public Icon icon_flag = new ImageIcon("flag.gif"); //雷标记public Icon icon_question = new ImageIcon("question.gif");//疑惑是否有雷Icon y= new ImageIcon("2.gif");Icon z= new ImageIcon("1.gif");Icon k= new ImageIcon("3.jpg");public JButton start = new JButton(y);public Panel MenuPamel = new Panel();public Panel mainPanel = new Panel();public Bomb[][] bombButton;MenuBar jmb=new MenuBar();Menu me=new Menu("游戏");MenuItem mi1=new MenuItem("高级");Container c =getContentPane();;public Menu me2=new Menu("帮助");public Menu me4=new Menu("等级");public MenuItem mi2=new MenuItem("开始");public MenuItem mi3=new MenuItem("玩法");public MenuItem mi4=new MenuItem("初级");public MenuItem mi5=new MenuItem("中级");public Menu me3=new Menu("颜色");public MenuItem mi6=new MenuItem("蓝色");public MenuItem mi7=new MenuItem("红色");public MenuItem mi8=new MenuItem("绿色");public MenuItem mi9=new MenuItem("黄色");public MenuItem mi10=new MenuItem("黑色"); public MenuItem mi11=new MenuItem("灰色"); /*界面设计*/public MainBomb(){super("扫雷伤心的骆驼制作2008.6 "); setMenuBar(jmb);jmb.add(me);jmb.add(me2);me.add(mi2);me4.add(mi4);me4.add(mi5);me4.add(mi1);me3.add(mi7);me3.add(mi6);me3.add(mi8);me3.add(mi9);me3.add(mi10);me3.add(mi11);me.add(me3);me.add(me4);me2.add(mi3);mi1.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e1){x = 100;e=20;MenuPamel.removeAll();//移除面板中的所有组件mainPanel.removeAll();c.remove(MenuPamel);//移除C容器中的组件c.remove(mainPanel);display();replay();}});mi4.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e1){x =49;MenuPamel.removeAll();//移除面板中的所有组件mainPanel.removeAll();c.remove(MenuPamel);//移除C容器中的组件c.remove(mainPanel);display();replay();}});mi5.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e1){x = 81;e=15;MenuPamel.removeAll();//移除面板中的所有组件mainPanel.removeAll();c.remove(MenuPamel);//移除C容器中的组件c.remove(mainPanel);display();replay();}});mi3.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){ JOptionPane msg = new JOptionPane();JOptionPane.showMessageDialog(null,"请输入雷数点击图片,你再点击可能有雷的地方假如不是雷则打开,显示的数字为周围的雷数","玩法",2);}} );mi6.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){ c.setBackground(Color.blue);MenuPamel.removeAll();//移除面板中的所有组件mainPanel.removeAll();c.remove(MenuPamel);//移除C容器中的组件c.remove(mainPanel);display();replay();}} );mi7.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){ c.setBackground(Color.red);MenuPamel.removeAll();//移除面板中的所有组件mainPanel.removeAll();c.remove(MenuPamel);//移除C容器中的组件c.remove(mainPanel);display();replay();}} );mi8.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){ c.setBackground(Color.green);MenuPamel.removeAll();//移除面板中的所有组件mainPanel.removeAll();c.remove(MenuPamel);//移除C容器中的组件c.remove(mainPanel);display();replay();}} );mi9.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ c.setBackground(Color.yellow);MenuPamel.removeAll();//移除面板中的所有组件mainPanel.removeAll();c.remove(MenuPamel);//移除C容器中的组件c.remove(mainPanel);display();replay();}} );mi10.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ c.setBackground(Color.black);MenuPamel.removeAll();//移除面板中的所有组件mainPanel.removeAll();c.remove(MenuPamel);//移除C容器中的组件c.remove(mainPanel);display();replay();}} );mi11.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ c.setBackground(Color.gray);MenuPamel.removeAll();//移除面板中的所有组件mainPanel.removeAll();c.remove(MenuPamel);//移除C容器中的组件c.remove(mainPanel);display();replay();}} );}void display(){BlockNum = x;BombNum = e;c.setLayout(new BorderLayout());text=new JTextField("10 ",3);nowBomb = new Label("当前雷数"+" "+BombNum+"");setBomb= new Label("设置地雷数");start.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){ start.setIcon(y);BombNum = Integer.parseInt(text.getText().trim());if(BombNum >= 10 && BombNum < 50 )replay();else if(BombNum < 10){JOptionPane msg = new JOptionPane();JOptionPane.showMessageDialog(null,"您设置的地雷数太少了,请重设!","错误",2);}else if(BombNum >=50 ){JOptionPane msg = new JOptionPane();JOptionPane.showMessageDialog(null,"您设置的地雷数太多了,请重设!","错误",2);}}} );mi2.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){ start.setIcon(y);BombNum = Integer.parseInt(text.getText().trim());if(BombNum >= 10 && BombNum < 50 )replay();else if(BombNum >=50 ){JOptionPane msg = new JOptionPane();JOptionPane.showMessageDialog(null,"您设置的地雷数太多了,请重设!","错误",2);}else if(BombNum < 10){JOptionPane msg = new JOptionPane();JOptionPane.showMessageDialog(null,"您设置的地雷数太少了,请重设!","错误",2);}}} );MenuPamel.add(setBomb);MenuPamel.add(text);MenuPamel.add(start);MenuPamel.add(nowBomb);c.add(MenuPamel,"North");mainPanel.setLayout(new GridLayout( (int)Math.sqrt(BlockNum) , (int)Math.sqrt(BlockNum)) ); bombButton=new Bomb[ (int)Math.sqrt(BlockNum) ][];for(int i = 0 ; i < (int)Math.sqrt(BlockNum) ; i++){bombButton[ i ]=new Bomb[ (int)Math.sqrt(BlockNum) ];}for(int i = 0 ; i < (int)Math.sqrt(BlockNum) ; i++ )for(int j = 0 ; j < (int)Math.sqrt(BlockNum) ; j++ ){bombButton[ i ][ j ]=new Bomb(i,j);bombButton[ i ][ j ].setForeground( Color.gray);bombButton[ i ][ j ].addActionListener(this);bombButton[ i ][ j ].addMouseListener(this);}for(int i = 0 ; i < (int)Math.sqrt(BlockNum) ; i++ )for(int j = 0 ; j < (int)Math.sqrt(BlockNum) ; j++ )mainPanel.add(bombButton[ i ][ j ]);c.add(mainPanel,"Center");startBomb();setSize(500,500);setLocation(350,200);setResizable(true);setVisible(true);}/*布雷*/public void startBomb(){for(int i=0;i<BombNum;i++){int x =(int)(Math.random()*(int)(Math.sqrt(BlockNum)));int y =(int)(Math.random()*(int)(Math.sqrt(BlockNum)));if(bombButton[ x ][ y ].isBomb==true)i--;elsebombButton[ x ][ y ].isBomb=true ;}}/*重新开始*/public void replay(){nowBomb.setText("当前雷数"+" "+BombNum+"");for(int i = 0 ; i < (int)Math.sqrt(BlockNum) ; i++)for(int j = 0 ; j < (int)Math.sqrt(BlockNum) ; j++){bombButton[ i ][ j ].isBomb=false;bombButton[ i ][ j ].isClicked=false;bombButton[ i ][ j ].setEnabled(true);bombButton[ i ][ j ].setText("");bombButton[ i ][ j ].setIcon(null);}startBomb();/*是否挖完了所有的雷*/public void isWin(){int findBomb=0; //找到的地雷数for(int i = 0;i < (int)Math.sqrt(BlockNum) ; i++)for(int j = 0;j < (int)Math.sqrt(BlockNum ); j++){if(bombButton[ i ][ j ].isBomb == true && bombButton[ i ][ j ].isRight == true)findBomb++;}if( findBomb == Integer.parseInt(text.getText().trim()) ){start.setIcon(z);JOptionPane msg = new JOptionPane();JOptionPane.showMessageDialog(this,"您挖完了所有的雷,您胜利了!","您胜利了",2);for(int i=0;i<(int)Math.sqrt(BlockNum);i++)for(int j=0;j<(int)Math.sqrt(BlockNum);j++){ if(bombButton[ i ][ j ].isClicked == false)bombButton[ i ][ j ].setEnabled(false);}}}/*计算方块周围雷数*/public void CountRoundBomb(){for (int i = 0; i < (int)Math.sqrt(BlockNum); i++) {for (int j = 0; j < (int)Math.sqrt(BlockNum); j++) {int count = 0;//当需要检测的单元格本身无地雷的情况下,统计周围的地雷个数if (bombButton[ i ][ j ].isBomb != true) {if ( (i - 1 >= 0) && (j - 1 >= 0)) {if (bombButton[i - 1][j - 1].isBomb == true) {count += 1; //检测左上方空格是否是地雷}}if ( (i - 1 >= 0)) {if (bombButton[i - 1][ j ].isBomb == true) {count += 1; //检测上方空格是否为地雷}if ( (i - 1 >= 0) && (j + 1 <= (int)Math.sqrt(BlockNum)-1)) {if (bombButton[i - 1][j + 1] .isBomb == true) {count += 1; //检测右上方是否为地雷}}if ( (j - 1 >= 0)) {if (bombButton[ i ][j - 1] .isBomb == true) {count += 1; //检测左边是否为地雷}}if ( (i >= 0) && (j + 1 <= (int)Math.sqrt(BlockNum)-1)) {if (bombButton[ i ][j + 1].isBomb == true) {count += 1; //右边}}if ( (j - 1 >= 0) && (i + 1 <= (int)Math.sqrt(BlockNum)-1)) {if (bombButton[i + 1][j - 1].isBomb == true) {count += 1; //左下}}if ( (i + 1 <= (int)Math.sqrt(BlockNum)-1)) {if (bombButton[i + 1][ j ].isBomb == true) {count += 1; //下}}if ( (j + 1 <= (int)Math.sqrt(BlockNum)-1) && (i + 1 <= Math.sqrt(BlockNum)-1)) { if (bombButton[i + 1][j + 1].isBomb == true) {count += 1; //右下}}bombButton[ i ][ j ].BombRoundCount = count;}}}}/**当选中的位置为空,则翻开周围的地图**/public void isNull(Bomb[][] bombButton,Bomb ClickecButton){int i,j;i=ClickecButton.num_x;j=ClickecButton.num_y;if (ClickecButton.isBomb==true) {}else {if ( (i - 1 >= 0) && (j - 1 >= 0)) { //检测左上方空格是否是空if (bombButton[i - 1][j - 1].isBomb == false && bombButton[i - 1][j - 1].isClicked == false && bombButton[i - 1][j - 1].isRight == false) {bombButton[i - 1][j - 1].setText((bombButton[i - 1][j - 1].BombRoundCount)+"");bombButton[i - 1][j - 1].setEnabled(false);bombButton[i - 1][j - 1].isClicked=true;if(bombButton[i-1][j-1].BombRoundCount==0) isNull(bombButton,bombButton[i - 1][j - 1]);}}if ( (i - 1 >= 0)) { //检测上方空格是否为空if (bombButton[i - 1][ j ] .isBomb == false && bombButton[i - 1][ j ].isClicked == false && bombButton[i - 1][ j ].isRight == false) {bombButton[i - 1][ j ].setText((bombButton[i - 1][ j ].BombRoundCount)+"");bombButton[i - 1][ j ].setEnabled(false);bombButton[i - 1][ j ].isClicked=true;if(bombButton[i-1][j].BombRoundCount==0) isNull(bombButton,bombButton[i - 1][j ]);}}if ( (i - 1 >= 0) && (j + 1 <= ((int)Math.sqrt(BlockNum)-1)) ) { //检测右上方是否为空if (bombButton[i - 1][j + 1] .isBomb == false && bombButton[i - 1][j + 1].isClicked == false && bombButton[i - 1][j + 1].isRight == false) {bombButton[i - 1][j + 1].setText((bombButton[i - 1][j + 1].BombRoundCount)+"");bombButton[i - 1][j + 1].setEnabled(false);bombButton[i - 1][j + 1].isClicked=true;if(bombButton[i-1][j+1].BombRoundCount==0)isNull(bombButton,bombButton[i - 1][j + 1]);}}if ( (j - 1 >= 0)) { //检测左边是否为空if (bombButton[ i ][j - 1].isBomb == false && bombButton[ i ][j - 1].isClicked == false &&bombButton[ i ][j - 1].isRight == false) {bombButton[ i ][j - 1].setText((bombButton[ i ][j - 1].BombRoundCount)+"");bombButton[ i ][j - 1].setEnabled(false);bombButton[ i ][j - 1].isClicked=true;if(bombButton[i][j-1].BombRoundCount==0)isNull(bombButton,bombButton[i ][j - 1]);}if ( (i >= 0) && (j + 1 <= ((int)Math.sqrt(BlockNum)-1)) ) { //检测右边空格是否是空if (bombButton[ i ][j + 1].isBomb == false && bombButton[ i ][j + 1].isClicked == false && bombButton[ i ][j + 1].isRight == false) {bombButton[ i ][j + 1].setText((bombButton[ i ][j + 1].BombRoundCount)+"");bombButton[ i ][j + 1].setEnabled(false);bombButton[ i ][j + 1].isClicked=true;if(bombButton[i][j+1].BombRoundCount==0)isNull(bombButton,bombButton[i ][j +1]);}}if ( (j - 1 >= 0) && (i + 1 <= ((int)Math.sqrt(BlockNum)-1)) ) { //检测左下空格是否是空if (bombButton[i + 1][j - 1].isBomb == false && bombButton[i + 1][j - 1].isClicked == false && bombButton[i + 1][j - 1].isRight == false) {bombButton[i + 1][j - 1].setText((bombButton[i + 1][j - 1].BombRoundCount)+"");bombButton[i + 1][j - 1].setEnabled(false);bombButton[i + 1][j - 1].isClicked=true;if(bombButton[i+1][j-1].BombRoundCount==0)isNull(bombButton,bombButton[i + 1][j - 1]);}}if ( (i + 1 <= ((int)Math.sqrt(BlockNum)-1)) ) { //检测下边空格是否是空if (bombButton[i + 1][ j ].isBomb == false && bombButton[i + 1][ j ].isClicked == false && bombButton[i + 1][ j ].isRight == false) {bombButton[i + 1][ j ].setText((bombButton[i + 1][ j ].BombRoundCount)+"");bombButton[i + 1][ j ].setEnabled(false);bombButton[i + 1][ j ].isClicked=true;if(bombButton[i+1][j].BombRoundCount==0)isNull(bombButton,bombButton[i +1][j ]);}}if ( (j + 1 <= ((int)Math.sqrt(BlockNum)-1) ) && (i + 1 <= ((int)Math.sqrt(BlockNum)-1)) ) { //检测右下边空格是否是空if (bombButton[i + 1][j + 1].isBomb == false && bombButton[i + 1][j + 1].isClicked == false && bombButton[i + 1][j + 1].isRight == false) {bombButton[i + 1][j + 1].setText((bombButton[i + 1][j + 1].BombRoundCount)+"");bombButton[i + 1][j + 1].setEnabled(false);bombButton[i + 1][j + 1].isClicked=true;if(bombButton[i+1][j+1].BombRoundCount==0)isNull(bombButton,bombButton[i + 1][j +1]);}/*if ( (i - 1 >= 0) && (j - 1 >= 0))//检测左上isNull(bombButton,bombButton[i - 1][j - 1]);if ( (i - 1 >= 0))isNull( bombButton,bombButton[i - 1][ j ]);//检测上方if ( (i - 1 >= 0) && (j + 1 <= (int)Math.sqrt(BlockNum)-1))isNull( bombButton,bombButton[i - 1][j + 1]);//检测右上if ( (j - 1 >= 0))isNull(bombButton,bombButton[i][j - 1]);//检测左边if ( (i >= 0) && (j + 1 <= ((int)Math.sqrt(BlockNum)-1)) )isNull(bombButton,bombButton[i][j + 1]);//检测右边if ( (j - 1 >= 0) && (i + 1 <= ((int)Math.sqrt(BlockNum)-1)) )isNull(bombButton,bombButton[i + 1][j - 1]); //检测左下if ( (i + 1 <= ((int)Math.sqrt(BlockNum)-1)) ) //检测下isNull(bombButton,bombButton[i + 1][ j ]);if ( (j + 1 <= ((int)Math.sqrt(BlockNum)-1)) && (i + 1 <= ((int)Math.sqrt(BlockNum)-1)) ) //检测右下isNull(bombButton,bombButton[i + 1][j + 1]);*/}}public void actionPerformed(ActionEvent e){CountRoundBomb();if(((Bomb)e.getSource()).isBomb==false && ((Bomb)e.getSource()).isClicked == false){((Bomb)e.getSource()).setText(( ((Bomb)e.getSource()).BombRoundCount )+"");((Bomb)e.getSource()).isClicked=true;((Bomb)e.getSource()).setIcon(null);((Bomb)e.getSource()).setEnabled(false);if((((Bomb)e.getSource()).BombRoundCount) == 0)isNull(bombButton,(Bomb)e.getSource());isWin();}else if(((Bomb)e.getSource()).isBomb == true){start.setIcon(k);for(int i=0;i<(int)Math.sqrt(BlockNum);i++)for(int j=0;j<(int)Math.sqrt(BlockNum);j++){if(bombButton[ i ][ j ].isBomb == true)bombButton[ i ][ j ].setIcon(icon_bomb);}((Bomb)e.getSource()).setIcon(icon_bomb_big);JOptionPane msg = new JOptionPane();JOptionPane.showMessageDialog(this,"你踩到地雷了,下次注意啊。
扫雷游戏Java源代码import java.awt.BorderLayout;import java.awt.Container;import java.awt.Font;import java.awt.GridLayout;import java.awt.Insets;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;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.JPanel;import javax.swing.Timer;public class ScanLei1 extends JFrame implements ActionListener{private static final long serialVersionUID = 1L;private Container contentPane;private JButton btn;private JButton[] btns;private JLabel b1;private JLabel b2;private JLabel b3;private Timer timer;private int row=9;private int col=9;private int bon=10;private int[][] a;private int b;private int[] a1;private JPanel p,p1,p2,p3;public ScanLei1(String title){super(title);contentPane=getContentPane();setSize(297,377);this.setBounds(400, 100, 400, 500);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);timer =new Timer(1000,(ActionListener) this);a = new int[row+2][col+2];initGUI();}public void initGUI(){p3=new JPanel();b=bon;JMenuBar menuBar=new JMenuBar();JMenu menu1=new JMenu("游戏");JMenu menu2=new JMenu("帮助");JMenuItem mi1=new JMenuItem("初级");JMenuItem mi2 = new JMenuItem("中级");JMenuItem mi3 =new JMenuItem("高级");mi1.addActionListener(this);menu1.add(mi1);mi2.addActionListener(this);menu1.add(mi2);mi3.addActionListener(this);menu1.add(mi3);menuBar.add(menu1);menuBar.add(menu2);p3.add(menuBar);b1=new JLabel(bon+"");a1=new int[bon];btn =new JButton("开始");btn.addActionListener(this);b2=new JLabel("0");b3=new JLabel("");btns=new JButton[row*col];p=new JPanel();p.setLayout(new BorderLayout());contentPane.add(p);p.add(p3,BorderLayout.NORTH);//combo=new JComboBox(new Object[]{"初级","中级","高级"} );//加监听/*combo.addItemListener(new ItemListener(){}});*/p1=new JPanel();//在那个位置//(( FlowLayout)p1.getLayout()).setAlignment( FlowLayout.RIGHT);p1.add(b1);p1.add(btn);p1.add(b2);p1.add(b3);p.add(p3,BorderLayout.NORTH);p.add(p1,BorderLayout.CENTER);p2=new JPanel();p2.setLayout(new GridLayout(row,col,0,0));for(int i=0;i<row*col;i++){btns[i]=new JButton("");btns[i].setMargin(new Insets(0,0,0,0));btns[i].setFont(new Font(null,Font.BOLD,25));btns[i].addActionListener(this);btns[i].addMouseListener(new NormoreMouseEvent());p2.add(btns[i]);}contentPane.add(p,BorderLayout.NORTH);contentPane.add(p2,BorderLayout.CENTER);}public void go(){setVisible(true);}public static void main(String[] args){new ScanLei1("扫雷").go();}public void out(int[][] a,JButton[] btns,ActionEvent e,int i,int x,int y){int p=1;if(a[x][y]==0){a[x][y]=10;btns[i].setEnabled(false); //33for(int l=y-1;l<=y+1;l++){int m=x-1-1;int n=l-1;p=1;System.out.println(a[1][2]);if(n>-1&&n<col&&m>-1&&m<row){for(int q=0;q<row&&p==1;q++){//col-->row;if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){if(a[x-1][l]!=0&&a[x-1][l]!=10){btns[n+col*q].setText(a[x-1][l]+"");a[x-1][l]=10;btns[n+col*q].setEnabled(false);}else if(a[x-1][l]==0){//a[x-1][l]=10;btns[n+col*q].setEnabled(false);out(a,btns,e,n+col*q,x-1,l);////55////a[x-1][l]=10;btns[n+col*q].setEnabled(false);}p=0;}}}p=1;m=x;if(n>-1&&n<col&&m>-1&&m<col){for(int q=0;q<row&&p==1;q++){if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){if(a[x+1][l]!=0&&a[x+1][l]!=10){btns[n+col*q].setText(a[x+1][l]+"");a[x+1][l]=10;btns[n+col*q].setEnabled(false);}else if(a[x+1][l]==0){out(a,btns,e,n+col*q,x+1,l);///55////a[x+1][l]=10;btns[n+col*q].setEnabled(false);}p=0;}}}}int m=x-1;int n=y-1-1;if(n>-1&&n<col&&m>-1&&m<col){for(int q=0;q<row&&p==1;q++){if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){if(a[x][y-1]!=0&&a[x][y-1]!=10){btns[n+col*q].setText(a[x][y-1]+"");a[x][y-1]=10;btns[n+col*q].setEnabled(false);}else if(a[x][y-1]==0){out(a,btns,e,n+col*q,x,y-1);a[x][y-1]=10;btns[n+col*q].setEnabled(false);}p=0;}}}p=1;m=x-1;n=y+1-1;if(n>-1&&n<col&&m>-1&&m<col){for(int q=0;q<row&&p==1;q++){if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){if(a[x][y+1]!=0&&a[x][y+1]!=10){btns[n+col*q].setText(a[x][y+1]+"");a[x][y+1]=10;btns[n+col*q].setEnabled(false);}else if(a[x][y+1]==0){out(a,btns,e,n+col*q,x,y+1);a[x][y+1]=10;btns[n+col*q].setEnabled(false);}p=0;}}}}public void actionPerformed(ActionEvent e) {if(e.getActionCommand()=="初级"){row=9;col=9;bon=10;a1=new int[bon];b=bon;//setSize(297,377);a = new int[row+2][col+2];this.remove(p2);timer.stop();b1.setText("10");b2.setText("0");b3.setText("");btns=new JButton[row*col];p2=new JPanel();p2.setLayout(new GridLayout(row,col,0,0));for(int i=0;i<row*col;i++){btns[i]=new JButton(" ");btns[i].setMargin(new Insets(0,0,0,0));btns[i].setFont(new Font(null,Font.BOLD,25));btns[i].addActionListener(this);btns[i].addMouseListener(new NormoreMouseEvent());p2.add(btns[i]);}contentPane.add(p2,BorderLayout.CENTER);//setSize(297,377);this.pack();for(int i=0;i<row*col;i++){btns[i].setText(" ");btns[i].setEnabled(true);}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){a[i][j]=0;}}}else if(e.getActionCommand()=="中级"){row=16;col=16;bon=40;//setSize(33*col,33*row+80);a1=new int[bon];a = new int[row+2][col+2];b=bon;this.remove(p2);timer.stop();b1.setText("40");b2.setText("0");b3.setText("");btns=new JButton[row*col];p2=new JPanel();p2.setLayout(new GridLayout(row,col,0,0));for(int i=0;i<row*col;i++){btns[i]=new JButton(" ");btns[i].setMargin(new Insets(0,0,0,0));btns[i].setFont(new Font(null,Font.BOLD,25));btns[i].addActionListener(this);btns[i].addMouseListener(new NormoreMouseEvent());p2.add(btns[i]);}contentPane.add(p2,BorderLayout.CENTER);this.pack();//setSize(33*col,33*row+80);for(int i=0;i<row*col;i++){btns[i].setText("");btns[i].setEnabled(true);}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){a[i][j]=0;}}}else if(e.getActionCommand()=="高级"){row=16;col=32;bon=99;setSize(33*col,33*row+80);a1=new int[bon];a = new int[row+2][col+2];b=bon;this.remove(p2);timer.stop();b1.setText("99");b2.setText("0");b3.setText("");btns=new JButton[row*col];p2=new JPanel();p2.setLayout(new GridLayout(row,col,0,0));for(int i=0;i<row*col;i++){btns[i]=new JButton(" ");btns[i].setMargin(new Insets(0,0,0,0));btns[i].setFont(new Font(null,Font.BOLD,25));btns[i].addActionListener(this);btns[i].addMouseListener(new NormoreMouseEvent());p2.add(btns[i]);}contentPane.add(p2,BorderLayout.CENTER);//setSize(33*col,33*row+80);this.pack();for(int i=0;i<row*col;i++){btns[i].setText("");btns[i].setEnabled(true);}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){a[i][j]=0;}}}if(e.getSource()==btn){timer.start();b=bon;b3.setText("");//System.out.println(bon);//清空for(int i=0;i<row*col;i++){btns[i].setText("");btns[i].setEnabled(true);}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){a[i][j]=0;}}//产生随机数for(int i=0;i<bon;i++){ int p=1;int m=(int)(Math.random()*row*col);while(p==1){int l=1;int j;for( j=0;j<i&&l==1;j++){if(a1[j]==m){m=(int)(Math.random()*row*col);l=0;}}if(j==i){a1[i]=m;p=0;}}}b1.setText(bon+"");b2.setText("0");//布雷for(int i=0;i<bon;i++){int x=(a1[i]/col+1);int y=(a1[i]%col+1);a[x][y]=100;}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){if(i==0||j==0||i==row+1||j==col+1){a[i][j]=0;}}}for(int i=1;i<=row;i++){for(int j=1;j<=col;j++){if(a[i][j]!=100){for(int l=j-1;l<=j+1;l++){if(a[i-1][l]==100){a[i][j]++;}if(a[i+1][l]==100){a[i][j]++;}}if(a[i][j-1]==100){a[i][j]++;}if(a[i][j+1]==100){a[i][j]++;}}}}}if(e.getSource()==timer){String time=b2.getText().trim();int t=Integer.parseInt(time);//System.out.println(t);if(t>=600){timer.stop();}else{t++;b2.setText(t+"");}}for(int i=0;i<col*row;i++){if(btns[i].getText()!="★"){int x=i/col+1;int y=i%col+1;if(e.getSource()==btns[i]&&a[x][y]==100){btns[i].setText("★");btns[i].setEnabled(false);a[x][y]=10;for(int k=0;k<col*row;k++){int m1=k/col+1;int n1=k%col+1;if(a[m1][n1]!=10&&btns[k].getText()=="★"){btns[k].setText("*o*");}}for(int j=0;j<col*row;j++){int m=j/col+1;int n=j%col+1;if(a[m][n]==100){btns[j].setText("★");btns[j].setEnabled(false);b3.setText("你输了!!");}btns[j].setEnabled(false);a[m][n]=10;}timer.stop();}else if(e.getSource()==btns[i]){if(a[x][y]==0){out(a,btns,e,i,x,y);a[x][y]=10;btns[i].setEnabled(false);}if(a[x][y]!=0&&a[x][y]!=10){btns[i].setText(a[x][y]+"");btns[i].setEnabled(false);a[x][y]=10;}}}else if(btns[i].getText()=="★"){}}}class NormoreMouseEvent extends MouseAdapter{public void mouseClicked(MouseEvent e) {System.out.println(b);for(int i=0;i<col*row;i++){int x1=i/col+1;int y1=i%col+1;if(e.getSource()==btns[i]&&btns[i].getText()!="★"&&a[x1][y1]!=10) {if(e.getButton()==MouseEvent.BUTTON3){btns[i].setText("★");b--;if(b==0){int flag=0;for(int j=0;j<col*row;j++){int x=j/col+1;int y=j%col+1;if(a[x][y]==100&&btns[j].getText()=="★"){flag++;}}if(flag==bon){timer.stop();b3.setText("你赢了!");}}b1.setText(b+"");}}elseif(e.getSource()==btns[i]&&btns[i].getText()=="★"&&a[x1][y1]!=-1){if(e.getButton()==MouseEvent.BUTTON3){btns[i].setText("");b++;if(b>bon){b1.setText(bon+"");}else{b1.setText(b+"");}btns[i].setEnabled(true);}}}}}}。