Java语言 扫雷游戏完整源代码

合集下载

Java简单雷电游戏代码

Java简单雷电游戏代码

完整代码!!!import java.awt.*;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import javax.swing.ImageIcon;import javax.swing.JPanel;public class Mhh {public static void main(String args[]){Frame w=new Frame();w.setSize(430,500);MyPanel9 mp=new MyPanel9();w.add(mp);w.addKeyListener(mp);mp.addKeyListener(mp);Thread t=new Thread(mp);t.start();w.show();}}class MyPanel9 extends JPanel implements Runnable,KeyListener { int count=1000;//发射子弹的数目int flag1=0;//标志flag为1时发射子弹int m=0; //记录已发射子弹的数目int max=2000;//记录得分int x=280;//下面飞机的坐标int y=420;int x1[]=new int[15];//上面飞机的坐标int[] y1=new int[15];int x2[]=new int[count];//发射子弹的坐标int[] y2=new int[count];public MyPanel9(){//上面飞机随即分布for(int i=0;i<15;i++){x1[i]=(int)(Math.random()*400);y1[i]=(int)(Math.random()*500);}}public void paint(Graphics g){super.paint(g);Image img2=new ImageIcon("1.jpg").getImage();g.drawImage(img2,0,0,430,500,null);Image img1=new ImageIcon("2.jpg").getImage();//画下面的飞机g.drawImage(img1,x,y,30,40,null);if(max>0){Font f=new Font("",Font.BOLD,16);g.setFont(f);g.setColor(Color.RED);g.drawString("成绩是:"+max,20,20);for(int i=0;i<10;i++){Image img3=new ImageIcon("4.jpg").getImage();//画上面的飞机g.drawImage(img3,x1[i],y1[i],30,40,null);}if(m==count) m=0;if(flag1==1){//画新子弹的位置x2[m]=x;y2[m]=y;m++;flag1=0;}for(int i=0;i<m;i++){g.setColor(Color.RED);g.fillOval(x2[i]+5,y2[i],15,15);}}else{Font ff=new Font("",Font.BOLD,36);g.setFont(ff);g.setColor(Color.RED);g.drawString("GAME OVER",100,200);}}public void run(){while(true){for(int i=0;i<10;i++){//飞机随机下落y1[i]++;if(y1[i]>500){y1[i]=0;x1[i]=(int)(Math.random()*400);max-=50;}}for(int j=0;j<m;j++){//子弹移动的过程y2[j]-=10;}for(int i=0;i<m;i++){ //子弹击中飞机的过程if(y2[i]>0){for(int j=0;j<10;j++){if(0<=(y2[i]-y1[j])&&(y2[i]-y1[j])<=10){if(-15<=(x2[i]-x1[j])&&(x2[i]-x1[j])<=10){max+=10;y2[i]=-1;x1[j]=(int)(Math.random()*400);y1[j]=0;}}}}}if(max<0){return;}try{Thread.sleep(35);}catch(Exception e){}repaint();}}public void keyTyped(KeyEvent e) {// TODO Auto-generated method stub}public void keyPressed(KeyEvent e) {//控制下面飞机移动if(e.getKeyCode()==KeyEvent.VK_LEFT){x-=10;if(x<0){x=0;}}if(e.getKeyCode()==KeyEvent.VK_UP){y-=10;if(y<0){y=0;}}if(e.getKeyCode()==KeyEvent.VK_RIGHT){x+=10;if(x>400){x=400;}}if(e.getKeyCode()==KeyEvent.VK_DOWN){y+=10;if(y>420){y=420;}}repaint();if(e.getKeyCode()==KeyEvent.VK_SPACE){flag1=1;}}public void keyReleased(KeyEvent e) {// TODO Auto-generated method stub}}。

JAVA课程设计扫雷含代码

JAVA课程设计扫雷含代码

0
随机生成:使用随 机数生成器生成地 图
地图大小:根据游 戏难度设置地图大 小
地雷分布:在地图 上随机分布地雷
标记地雷:在地图 上标记地雷位置, 方便玩家识别
雷区标记逻辑
初始化:创建雷区数组,设置初始状态 标记雷区:当玩家点击雷区时,标记为雷区 更新雷区:当玩家点击非雷区时,更新雷区状态 判断胜负:当所有非雷区都被标记时,游戏结束,判断胜负
游戏结束:当所有非雷方格都被点击,或者玩家踩到雷时,游戏结束
游戏界面设计
游戏界面分为两个部分:游戏区和菜单区 游戏区显示游戏地图和地雷位置 菜单区包括开始游戏、暂停游戏、重新开始、退出游戏等按钮 游戏界面采用简洁明了的设计风格,易于玩家操作和理解
游戏流程控制
初始化游戏:创建游戏界面,设置游戏参数 玩家输入:接收玩家输入的坐标,判断是否合法 游戏逻辑:根据玩家输入,更新游戏状态,判断是否触发雷 游戏结束:判断游戏是否结束,显示游戏结果 重新开始:提供重新开始游戏的选项,重新开始游戏流程
05
JAVA扫雷游戏代码实 现
游戏主程序代码实现
初始化游戏界面 生成随机雷区 玩家点击操作 判断输赢条件 游戏结束处理
游戏地图类代码实现
初始化地图,设置地雷位置 和状态
创建游戏地图类,定义地图 大小和地雷数量
实现地图显示,绘制地雷和 空白区域
实现地图更新,根据玩家操 作更新地雷状态和显示
游戏雷区类代码实现
感谢您的观看
汇报人:
兼容性:测试游戏在不同操作系统 和硬件配置下的兼容性
添加标题
添加标题
添加标题
添加标题
稳定性:测试游戏在长时间运行下 的稳定性
用户体验:测试游戏的易用性和用 户体验

扫雷java代码

扫雷java代码

/*** This program is written by Jerry Shen(Shen Ji Feng)* use the technology of SWING GUI and the OO design** @author Jerry Shen(jerry.shen@)* Distributed under the licience of GPLv3* all rights reserved.*/import java.awt.*;import javax.swing.*;//图形计数器JCounter三位class JCounter extends JPanel {private ImageIcon [] numSet = { new ImageIcon("c0.gif"), new ImageIcon("c1.gif"),new ImageIcon("c2.gif"), new ImageIcon("c3.gif"),new ImageIcon("c4.gif"), new ImageIcon("c5.gif"),new ImageIcon("c6.gif"), new ImageIcon("c7.gif"),new ImageIcon("c8.gif"), new ImageIcon("c9.gif"),};private JButton [] counter = { new JButton(numSet[0]), new JButton(numSet[0]), new JButton(numSet[0])};private int counterNum;private Insets space;public JCounter() {this(0);}public JCounter(int num) {super();setSize(23, 39);space = new Insets(0,0,0,0);this.counterNum = num;for (int i=0; i< 3; i++){counter[i].setSize(13,23);counter[i].setMargin(space);add(counter[i]);}this.setVisible(true);resetImage();}public int getCounterNum() {return(counterNum);}private void setCounterNum(int num){this.counterNum = num;}private void resetImage() {int ones, tens, hundreds;ones = counterNum % 10 ;tens = counterNum % 100/10;hundreds = (counterNum) % 1000/100;this.counter[0].setIcon(numSet[hundreds]);this.counter[1].setIcon(numSet[tens]);this.counter[2].setIcon(numSet[ones]);}public void resetCounter(int num) {setCounterNum(num);resetImage();this.repaint();}public static void main(String[] args) {JFrame jf = new JFrame("Test");jf.setSize(23,39);JCounter jc = new JCounter();jf.setContentPane(jc);jf.show();jc.resetCounter(394);}}。

Java 课程设计 扫雷

Java 课程设计 扫雷

自己写用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)。

扫雷游戏代码

扫雷游戏代码
}
}
/*计算方块周围雷数 */
public void CountRoundBomb()
{
for (int i = 0; i < (int)Math.sqrt(BlockNum); i++) {
for (int j = 0; j < (int)Math.sqrt(BlockNum); j++) {
}
/*重新开始*/
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=new Bomb[ (int)Math.sqrt(BlockNum) ][];
for(int i = 0 ; i < (int)Math.sqrt(BlockNum) ; i++)
{
bombButton[ i ]=new Bomb[ (int)Math.sqrt(BlockNum) ];
int y =(int)(Math.random()*(int)(Math.sqrt(BlockNum)-1));
if(bombButton[ x ][ y ].isBomb==true)
i--;
else
bombButton[ x ][ y ].isBomb=true ;

扫雷的java程序

扫雷的java程序

扫雷不能不说一款非常经典的游戏,无聊时候可以打发时间,虽然玩了很久,但还不知道它是怎么写的,所以自己就尝试动手做了个。

众所周知,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类。

扫雷游戏代码

扫雷游戏代码

扫雷游戏代码standalone; self-contained; independent; self-governed;autocephalous; indie; absolute; unattached; substantive/**/#ifndef BLOCK_H_#define BLOCK_H_#include<QLabel>class QWidget;class Block:public QLabel{Q_OBJECTpublic:explicit Block(bool mine_flag,QWidget*parent=0);void set_number(int number);void turn_over();bool is_mine()const;bool is_turn_over()const;signals:void turn_over(bool is_mine);protected:void mousePressEvent(QMouseEvent*event); private:bool mine_flag_;bool mark_flag_;bool turn_over_flag_;int number_;};#endif#include""#include<QLabel>#include<QMouseEvent>#include<QPixmap>#include<QWidget>Block::Block(bool mine_flag,QWidget*parent) :QLabel(parent){mine_flag_=mine_flag;mark_flag_=false;turn_over_flag_=false;number_=-1;setPixmap(QPixmap(":/images/"));}void Block::set_number(int number){number_=number;}void Block::turn_over(){if(!turn_over_flag_){turn_over_flag_=true;if(mine_flag_)setPixmap(QPixmap(":/images/"));elsesetPixmap(QPixmap(":/images/mine_"+QString("%1").arg(num ber_)+".png"));update();}}bool Block::is_mine()const{return mine_flag_;}bool Block::is_turn_over()const{return turn_over_flag_;}/*鼠标事件的实现*/void Block::mousePressEvent(QMouseEvent*event){if(event->button()==Qt::LeftButton){if(!turn_over_flag_&&!mark_flag_){turn_over_flag_=true;if(mine_flag_==true){setPixmap(QPixmap(":/images/"));update();emit turn_over(true);}else{setPixmap(QPixmap(":/images/mine_"+QString("%1").arg(num ber_)+".png"));update();emit turn_over(false);}}}else if(event->button()==Qt::RightButton){if(!turn_over_flag_){if(!mark_flag_){mark_flag_=true;setPixmap(QPixmap(":/images/"));}else{mark_flag_=false;setPixmap(QPixmap(":/images/"));}update();}}QLabel::mousePressEvent(event);}#ifndef BLOCK_AREA_H_#define BLOCK_AREA_H_#include""#include<QWidget>class QEvent;class QGridLayout;class QObject;class BlockArea:public QWidget{Q_OBJECTpublic:BlockArea(int row,int column,int mine_number,QWidget* parent=0);void set_block_area(int row,int column,intmine_number,int init_flag=false);signals:void game_over(bool is_win);protected:bool eventFilter(QObject*watched,QEvent*event); private slots:void slot_turn_over(bool is_mine);private:int calculate_mines(int x,int y)const;rg(easy_record_time_)),1,1);up_layout->addWidget(new QLabel(easy_record_name_),1,2);up_layout->addWidget(new QLabel(tr("Middle")),2,0);up_layout->addWidget(newQLabel(QString("%1").arg(middle_record_time_)),2,1);up_layout->addWidget(newQLabel(middle_record_name_),2,2);up_layout->addWidget(new QLabel(tr("Hard")),3,0);up_layout->addWidget(newQLabel(QString("%1").arg(hard_record_time_)),3,1);up_layout->addWidget(new QLabel(hard_record_name_),3,2);QPushButton*recount_button=newQPushButton(tr("recount"));QPushButton*close_button=new QPushButton(tr("close"));close_button->setDefault(true);connect(recount_button,SIGNAL(clicked()),&dialog,SLOT(ac cept()));connect(close_button,SIGNAL(clicked()),&dialog,SLOT(reje ct()));QHBoxLayout*bottom_layout=new QHBoxLayout;bottom_layout->addStretch();bottom_layout->addWidget(recount_button);bottom_layout->addWidget(close_button);QVBoxLayout*main_layout=new QVBoxLayout(&dialog);main_layout->addLayout(up_layout);main_layout->addLayout(bottom_layout);if()==QDialog::Accepted){easy_record_time_=middle_record_time_=hard_record_time_= g_no_record_time;easy_record_name_=middle_record_name_=hard_record_name_= g_no_record_name;}}void MainWindow::slot_show_game_toolBar(bool show){if(show)game_toolBar->show();elsegame_toolBar->hide();}void MainWindow::slot_show_statusBar(bool show){if(show)statusBar()->show();elsestatusBar()->hide();}/*游戏的设置容易、中等、困难及自定义*/void MainWindow::slot_standard(QAction*standard_action) {if(standard_action==easy_standard_action){current_standard_=0;row_=9;column_=9;mine_number_=10;}else if(standard_action==middle_standard_action){ current_standard_=1;row_=16;column_=16;mine_number_=40;}else if(standard_action==hard_standard_action){current_standard_=2;row_=16;column_=30;mine_number_=99;}else if(standard_action==custom_standard_action){ QDialog dialog;(tr("set standard"));QSpinBox*row_spinBox=new QSpinBox;row_spinBox->setRange(5,50);row_spinBox->setValue(row_);QSpinBox*column_spinBox=new QSpinBox;column_spinBox->setRange(5,50);column_spinBox->setValue(column_);QSpinBox*mine_spinBox=new QSpinBox;mine_spinBox->setValue(mine_number_);QHBoxLayout*up_layout=new QHBoxLayout;up_layout->addWidget(row_spinBox);up_layout->addWidget(column_spinBox);up_layout->addWidget(mine_spinBox);QDialogButtonBox*dialog_buttonBox=new QDialogButtonBox;dialog_buttonBox->addButton(QDialogButtonBox::Ok);dialog_buttonBox->addButton(QDialogButtonBox::Cancel);connect(dialog_buttonBox,SIGNAL(accepted()),&dialog,SLOT (accept()));connect(dialog_buttonBox,SIGNAL(rejected()),&dialog,SLOT (reject()));QHBoxLayout*bottom_layout=new QHBoxLayout;bottom_layout->addStretch();bottom_layout->addWidget(dialog_buttonBox);QVBoxLayout*main_layout=new QVBoxLayout(&dialog);main_layout->addLayout(up_layout);main_layout->addLayout(bottom_layout);if()==QDialog::Accepted)if(row_spinBox->value()*column_spinBox->value()>mine_spinBox->value()){current_standard_=3;row_=row_spinBox->value();column_=column_spinBox->value();mine_number_=mine_spinBox->value();}}slot_new_game();}/*实现帮助菜单中的关于游戏,及功能*/void MainWindow::slot_about_game(){QString introduction("<h2>"+tr("About Mine Sweepr")+"</h2>"+"<p>"+tr("This game is played by revealing squares of the grid,typically by clicking them with a mouse.If a square containing a mine is revealed,the player loses the game.Otherwise,a digit is revealed in the square,indicating the number of adjacent squares(out of the possible eight)that contain this number is zero then the square appears blank,and the surrounding squares are automatically also revealed.By using logic,the player can in many instances use this information to deduce that certain other squares are mine-free, in which case they may be safely revealed,or mine-filled,in which they can be marked as such(which is effected by right-clicking the square and indicated by a flag graphic).")+"</p>"+"<p>"+tr("This program is free software;you can redistribute it and/or under the terms of the GNU General Public License as published by the Software Foundation;either version3of the License,or(at your option)any later version.")+"</p>"+"<p>"+tr("Please see")+"<a href="+tr("for an overview of GPLv3licensing")+"</p>"+"<br>"+tr("Version:")+g_software_version+"</br>"+"<br>"+tr("Author:")+g_software_author+"</br>");QMessageBoxmessageBox(QMessageBox::Information,tr("About Mine Sweeper"),introduction,QMessageBox::Ok);();}/*游戏的判断,及所给出的提示做出判断*/void MainWindow::slot_game_over(bool is_win){();QString name;if(is_win){switch(current_standard_){case0:if(time_label->text().toInt()<easy_record_time_){name=QInputDialog::getText(this,tr("Please enter your name"),tr("You create a record.Please enter your name"));if(!()){easy_record_time_=time_label->text().toInt();easy_record_name_=name;}}elseQMessageBox::information(this,tr("Result"),tr("You win"));break;case1:if(time_label->text().toInt()<middle_record_time_){name=QInputDialog::getText(this,tr("Please enter your name"),tr("You create a record.Please enter your name"));if(!()){middle_record_time_=time_label->text().toInt();middle_record_name_=name;}}elseQMessageBox::information(this,tr("Result"),tr("You win"));break;case2:if(time_label->text().toInt()<hard_record_time_){name=QInputDialog::getText(this,tr("Please enter your name"),tr("You create a record.Please enter your name"));if(!()){hard_record_time_=time_label->text().toInt();hard_record_name_=name;}}elseQMessageBox::information(this,tr("Result"),tr("You win"));break;default:QMessageBox::information(this,tr("Result"),tr("Y ou win"));}}else{QMessageBox::information(this,tr("Result"),tr("You lose"));}}/*定时器的设置*/void MainWindow::slot_timer(){time_label->setText(QString("%1").arg()/1000));}/*关于菜单栏的设置是否显示游戏工具栏和状态栏*/void MainWindow::read_settings(){QSettings settings;("MainWindow");resize("size").toSize());move("pos").toPoint());bool show_game_toolBar=("showGameToolBar").toBool();show_game_toolBar_action->setChecked(show_game_toolBar);slot_show_game_toolBar(show_game_toolBar);bool show_statusBar=("showStatusBar").toBool();show_statusBar_action->setChecked(show_statusBar);slot_show_statusBar(show_statusBar);();("GameSetting");current_standard_=("current_standard").toInt();switch(current_standard_){case0:easy_standard_action->setChecked(true);break;case1:middle_standard_action->setChecked(true);break;case2:hard_standard_action->setChecked(true);break;case3:custom_standard_action->setChecked(true);break;default:;}row_=("row").toInt()==09:("row").toInt();column_=("column").toInt()==09:("column").toInt();mine_number_=("mine_number").toInt()==010:("mine_number" ).toInt();();("Rank");easy_record_time_=("easy_record_time").toInt()==0g_no_re cord_time:("easy_record_time").toInt();middle_record_time_=("middle_record_time").toInt()==0g_n o_record_time:("middle_record_time").toInt();hard_record_time_=("hard_record_time").toInt()==0g_no_re cord_time:("hard_record_time").toInt();easy_record_name_=("easy_record_name").toString()==""g_n o_record_name:("easy_record_name").toString();middle_record_name_=("middle_record_name").toString()==" "g_no_record_name:("middle_record_name").toString();hard_record_name_=("hard_record_name").toString()==""g_n o_record_name:("hard_record_name").toString();();}void MainWindow::write_settings(){QSettings settings;("MainWindow");("size",size());("pos",pos());("showGameToolBar",show_game_toolBar_action->isChecked());("showStatusBar",show_statusBar_action->isChecked());();("GameSetting");("current_standard",current_standard_);("row",row_);("column",column_);("mine_number",mine_number_);();("Rank");("easy_record_time",easy_record_time_);("middle_record_time",middle_record_time_);("hard_record_time",hard_record_time_);("easy_record_name",easy_record_name_);("middle_record_name",middle_record_name_);("hard_record_name",hard_record_name_);();}/*菜单栏里图片的显示*/void MainWindow::create_actions(){new_game_action=new QAction(QIcon(":/images/"),tr("New Game"),this);new_game_action->setShortcut(QKeySequence::New);connect(new_game_action,SIGNAL(triggered()),this,SLOT(sl ot_new_game()));rank_action=newQAction(QIcon(":/images/"),tr("Rank"),this);connect(rank_action,SIGNAL(triggered()),this,SLOT(slot_r ank()));exit_action=newQAction(QIcon(":/images/"),tr("Exit"),this);exit_action->setShortcut(QKeySequence::Quit);connect(exit_action,SIGNAL(triggered()),this,SLOT(close( )));show_game_toolBar_action=new QAction(tr("Show Game Tool Bar"),this);show_game_toolBar_action->setCheckable(true);connect(show_game_toolBar_action,SIGNAL(toggled(bool)),t his,SLOT(slot_show_game_toolBar(bool)));show_statusBar_action=new QAction(tr("Show Status Bar"),this);show_statusBar_action->setCheckable(true);connect(show_statusBar_action,SIGNAL(toggled(bool)),this ,SLOT(slot_show_statusBar(bool)));easy_standard_action=newQAction(QIcon(":/images/"),tr("Easy"),this);easy_standard_action->setCheckable(true);middle_standard_action=newQAction(QIcon(":/images/"),tr("Middle"),this);middle_standard_action->setCheckable(true);hard_standard_action=newQAction(QIcon(":/images/"),tr("Hard"),this);hard_standard_action->setCheckable(true);custom_standard_action=newQAction(QIcon(":/images/"),tr("Custom"),this);custom_standard_action->setCheckable(true);standard_actionGroup=new QActionGroup(this);standard_actionGroup->addAction(easy_standard_action);standard_actionGroup->addAction(middle_standard_action);standard_actionGroup->addAction(hard_standard_action);standard_actionGroup->addAction(custom_standard_action);connect(standard_actionGroup,SIGNAL(triggered(QAction*)) ,this,SLOT(slot_standard(QAction*)));about_game_action=newQAction(QIcon(":/images/"),tr("About Game"),this);connect(about_game_action,SIGNAL(triggered()),this,SLOT( slot_about_game()));about_qt_action=new QAction(QIcon(":/images/"),tr("About Qt"),this);connect(about_qt_action,SIGNAL(triggered()),qApp,SLOT(ab outQt()));}/*菜单栏的创建*/void MainWindow::create_menus(){game_menu=menuBar()->addMenu(tr("Game"));game_menu->addAction(new_game_action);game_menu->addSeparator();game_menu->addAction(rank_action);game_menu->addSeparator();game_menu->addAction(exit_action);setting_menu=menuBar()->addMenu(tr("Setting"));setting_menu->addAction(show_game_toolBar_action);setting_menu->addAction(show_statusBar_action);setting_menu->addSeparator();setting_menu->addAction(easy_standard_action);setting_menu->addAction(middle_standard_action);setting_menu->addAction(hard_standard_action);setting_menu->addAction(custom_standard_action);help_menu=menuBar()->addMenu(tr("Help"));help_menu->addAction(about_game_action);help_menu->addAction(about_qt_action);}void MainWindow::create_game_toolBar(){game_toolBar=addToolBar(tr("Game Tool Bar"));game_toolBar->setFloatable(false);game_toolBar->setMovable(false);game_toolBar->addAction(new_game_action);game_toolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); }void MainWindow::create_statusBar(){time_label=new QLabel;statusBar()->addPermanentWidget(time_label);statusBar()->addPermanentWidget(newQLabel(tr("second")));}#include""#include<QApplication>#include<QTranslator>int main(int argc,char*argv[]){QApplication app(argc,argv);QTranslator translator;(":/");(&translator);MainWindow window;();return();}。

JAVA实现经典扫雷游戏的示例代码

JAVA实现经典扫雷游戏的示例代码

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这门语⾔也有了⽐以前更深刻的认识。

Java小游戏—扫雷

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

扫雷游戏开发代码

扫雷游戏开发代码
return isMark;
}
public void setIsMark(boolean m) {
isMark=m;
}
}
/*(2)雷区显示*/
import javax.swing.*;
import java.awt.*;
}
else {
int n=block.getAroundMineNumber();
setBackground(new Color(0,0,122));
if(n>=1)
{
isMine=b;
}
public void setMineIcon(ImageIcon icon){
mineIcon=icon;
}
public ImageIcon getMineicon(){
return mineIcon;
if(n==2)////
blockNameOrIcon.setForeground(new Color(0,0,255));////////
if(n==3)
blockNameOrIcon.setForeground(new Color(0,255,0));///
}
}
block[i][j].setIsOpen(false);
block[i][j].setIsMark(false);
block[i][j].setName(""+mineNumber);
blockNameOrIcon.setVerticalTextPosition(AbstractButton.CENTER);
blockCover=new JButton();

扫雷源代码(精)

扫雷源代码(精)

#include <Windows.h>#include <stdio.h>#include <stdlib.h>#include <conio.h>#include <time.h>#define RECT 10#define MY_BUFSIZE 1024 // 宽字符缓冲// 棋盘的最大x,y#define MAXX 21#define MAXY 21// 按键大小写皆可以输入#define LEFT 75#define RIGHT 77#define UP 72#define DOWN 80#define ENTER 13#define ESC 27#define UPA 'A'#define LOWA 'a'#define UPW 'W'#define LOWW 'w'#define UPQ 'Q'#define LOWQ 'q'#define UPD 'D'#define LOWD 'd'void init();//初始化雷曲函数void draw_board(void); //画布函数void draw_face(int type);//游戏状态函数void draw_rect(int type);//按键后响应函数void operate_mine(void);//随机生成雷函数void move(void);//移动函数void hide(void);//隐藏函数void show(void);//高亮当前坐标void open_mine(void);//挖雷函数int is_win(void);//判断输赢函数void change_rectColor(int x, int y, int col);//改变周围颜色函数void test(char a[]);LPCWSTR StrToLPWSTR(char *szStr); // c风格字符串转宽字符串void goto_xy(int x, int y); // 定位光标void set_fontColor(int color); // 设置字符显示的背景前景色int get_keys(void); // 获取按键// 全局变量int x = 0, y = 0; // 初始化坐标值int num = 0; // 统计当前总共雷数量CONSOLE_CURSOR_INFO cur_info = { 1, 0 }; // 光标信息结构HANDLE hOut = NULL; // 控制台句柄结构指针COORD pos = { 0, 0 }; // 定位控制台坐标结构struct Seave //定义结构体储存每个方格的状态{int flag; //是否翻开bool mark; //雷是否标记int num; //周围雷的个数如果为9表示为雷};struct Seave mine[10][10];void init() //初始化雷区,全部设置为未翻开,未标记{int i, j;for (i = 0; i<10; i++)for (j = 0; j<10; j++){mine[i][j].flag = 0;mine[i][j].mark = true;//表示没有雷mine[i][j].num= 0;}}void DONG(int *b, int i) //计算雷周围的函数{int x = 0;if (*(b + i) == 0){if (i == 0){if (*(b + i + 1) == 9)x += 1;if (*(b + i + 10) == 9)x += 1;if (*(b + i + 10 + 1) == 9)x += 1;}else if (i == 9){if (*(b + i - 1) == 9)x += 1;if (*(b + i + 10) == 9)x += 1;if (*(b + i + 10 - 1) == 9)x += 1;}else if (i != 0 && i % 10 == 0){if (*(b + i + 1) == 9)x += 1;if (*(b + i + 10) == 9)x += 1;if (*(b + i + 10 + 1) == 9)x += 1;if (*(b + i - 10) == 9)x += 1;if (*(b + i - 10 + 1) == 9)x += 1;}else if ((i - 9) != 0 && (i - 9) % 10 == 0) {if (*(b + i - 1) == 9)x += 1;if (*(b + i + 10) == 9)x += 1;if (*(b + i + 10 - 1) == 9)x += 1;if (*(b + i - 10) == 9)x += 1;if (*(b + i - 10 - 1) == 9)x += 1;}else if (i == 90){if (*(b + i + 1) == 9)x += 1;if (*(b + i + 10) == 9)x += 1;if (*(b + i + 10 + 1) == 9)x += 1;}else if (i == 99){if (*(b + i - 1) == 9)x += 1;if (*(b + i - 10) == 9)x += 1;if (*(b + i - 10 - 1) == 9)x += 1;}else{if (*(b + i - 1) == 9)x += 1;if (*(b + i + 1) == 9)x += 1;if (*(b + i + 10) == 9)x += 1;if (*(b + i + 10 + 1) == 9)x += 1;if (*(b + i + 10 - 1) == 9)x += 1;if (*(b + i - 10) == 9)x += 1;if (*(b + i - 10 + 1) == 9)x += 1;if (*(b + i - 10 - 1) == 9)x += 1;}*(b + i) = x;}}void operate_mine(void) //随机产生雷{int z, i, j;int a[10][10] = { 0 };srand((unsigned)time(NULL));for (z = 0; z <= 12; z++){i = rand() % 11;j = rand() % 11;if (a[i][j] == 0){a[i][j] = 9;mine[i][j].mark = false; //雷区标记}else z--;}for (i = 0; i <= 99; i++)DONG(&a[0][0], i);for (i = 0; i<10; i++)for (j = 0; j<10; j++){mine[i][j].num = a[i][j];}}void set_fontColor(int color)//设置前景颜色{hOut == NULL ? (hOut = GetStdHandle(STD_OUTPUT_HANDLE)) : hOut;SetConsoleTextAttribute(hOut, color);}void draw_rect(int type){switch (type){case 0: // 未挖开方格set_fontColor(0x87); goto_xy(2 * x + 1, 2 * y + 1); printf("█"); break;case 1: // 表示挖开,并显示数字,如果有set_fontColor(0x88); goto_xy(2 * x + 1, 2 * y + 1); printf("█");if (mine[x][y].num == 0) break;set_fontColor(0x8a); goto_xy(2 * x + 1, 2 * y + 1); printf("%2d", mine[x][y].num); break;case 2: // 排除地雷set_fontColor(0x74); goto_xy(2 * x + 1, 2 * y + 1); printf(" X"); break;case 3: // 标记问号,表示不确定set_fontColor(0x74); goto_xy(2 * x + 1, 2 * y + 1); printf(" ?"); break;case 4: // 挖出地雷了set_fontColor(0xc0); goto_xy(2 * x + 1, 2 * y + 1); printf("●"); break;default: break;}}/*****************************测试之后才知道方向键两个字节第一个字节ASCII 0x00e0 224第二个字节分别是:上:0x0048 72下:0x0050 80左:0x012b 75右:0x012d 77*****************************/int get_keys(void){char ch;if (_kbhit()){ // 有按键按下if ((ch = _getch()) == 224 || ch == -32) // 方向键产生2个char,后一个用于判断ch = _getch();while (_kbhit())_getch(); // 清空剩余按键return ch;}elsereturn -1; // 没有按键按下}void show(void){//高亮显示当前方块所在的方格线change_rectColor(x, y, 0x8c);}void change_rectColor(int x, int y, int col){// 棋子周围棋盘线变色set_fontColor(col);goto_xy(2 * x, 2 * y + 1);printf("|");goto_xy(2 * x + 2, 2 * y + 1);printf("|");goto_xy(2 * x, 2 * y);printf(" --- ");goto_xy(2 * x, 2 * y + 2);printf(" --- ");}LPCWSTR StrToLPWSTR(char *szStr){WCHAR wszClassName[MY_BUFSIZE]; // 宽字符缓冲区WCHAR *retWchar = wszClassName;memset(wszClassName, 0, sizeof(wszClassName)); // 缓冲区清零MultiByteToWideChar(CP_ACP, 0, szStr, strlen(szStr) + 1, wszClassName,sizeof(wszClassName) / sizeof(wszClassName[0]));return retWchar;}void goto_xy(int x, int y){pos.X = x * 2; pos.Y = y;hOut == NULL ? (hOut = GetStdHandle(STD_OUTPUT_HANDLE)) : hOut;SetConsoleCursorPosition(hOut, pos);}void hide(void){change_rectColor(x, y, 0x87);// 恢复方块所在方格线颜色switch (mine[x][y].flag){case 0:; // 表示此方格未挖开draw_rect(0);break;case 1: // 挖开并且显示数字draw_rect(1);break;case 2: // 方格上有标记,表明此方格有雷draw_rect(2);break;case 3:draw_rect(3);break;default:break;}}void test(char a[], int x, int y){set_fontColor(0x8a);goto_xy(0, MAXY + 2);printf("%10s%d%d", a, x, y);}void draw_board(void){int i, j;SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&cur_info);// 隐藏光标system("mode con cols=46 lines=28");// 改变控制台窗体宽高SetConsoleTitle(StrToLPWSTR("扫雷 by 达夫东文&钓钓的猫")); // 改变窗口标题system("COLOR 87");// 控制台背景前景色// 打印棋盘到屏幕printf("-----------------------------------------\n");printf("| | | | | | | | | | | 1\n");printf("-----------------------------------------\n");printf("| | | | | | | | | | | 2\n");printf("-----------------------------------------\n");printf("| | | | | | | | | | | 3\n");printf("-----------------------------------------\n");printf("| | | | | | | | | | | 4\n");printf("-----------------------------------------\n");printf("| | | | | | | | | | | 5\n");printf("-----------------------------------------\n");printf("| | | | | | | | | | | 6\n");printf("-----------------------------------------\n");printf("| | | | | | | | | | | 7\n");printf("-----------------------------------------\n");printf("| | | | | | | | | | | 8\n");printf("-----------------------------------------\n");printf("| | | | | | | | | | | 9\n");printf("-----------------------------------------\n");printf("| | | | | | | | | | | 10\n");printf("-----------------------------------------\n");printf(" 1 2 3 4 5 6 7 8 9 10\n");// 画灰白色的方格set_fontColor(0x87);for (i = 0; i < RECT; i++)for (j = 0; j < RECT; j++){goto_xy(2 * i + 1, 2 * j + 1);printf("█");}set_fontColor(0x8a);goto_xy(0, MAXY + 2);printf("%16s", "剩余:00");draw_face(0);//操作说明set_fontColor(0x87);goto_xy(0, MAXY + 4);printf(" \"方向键移动\",\"ESC退出游戏\",\"a扫雷\"\n"" \"q标记问号\",\"w标记地雷\",\"d结束当前游戏\""); }void main(){for (;1;){int key;draw_board();init();operate_mine();while (1){key = get_keys();switch (key){case LEFT:hide();x--;x = x >= 0 ? x : 0;show();break;case RIGHT:hide();x++;x = x > 9 ? 9 : x;show();break;case UP:hide();y--;y = y >= 0 ? y : 0;show();break;case DOWN:hide();y++;y = y > 9 ? 9 : y;show();break;case UPA:case LOWA:if (mine[x][y].flag != 0) // 已经挖过,退出break;if (mine[x][y].mark == false){ // 挖到地雷了for (x = 0; x < 10; x++) // 显示出所有地雷for (y = 0; y < 10; y++)if (mine[x][y].mark == false)draw_rect(4);set_fontColor(0x8c);goto_xy(16, MAXY + 2);printf("%12s", "sorry你输了");draw_face(2); // 显示出悲伤的表情_getch();return ;}open_mine(); // 没挖过且没有地雷,则挖开周围方格show();if (is_win()){set_fontColor(0x8c);goto_xy(16, MAXY + 2);printf("%8s", "赢了");draw_face(1);_getch();return ;}break;case UPW: // 标记“X”,说明方格有雷case LOWW:if (mine[x][y].flag == 2) // 如果在已经标记为X的方格上再按一次w键,则取消标记X{num++;mine[x][y].flag = 0;draw_rect(0);break;}if (mine[x][y].flag != 0)break;mine[x][y].flag = 2;draw_rect(2); // 显示标记Xshow(); // 显示当前选择的方块if (is_win()){set_fontColor(0x8c);goto_xy(16, MAXY + 2);printf("%8s", "赢了");draw_face(1);_getch();return ;}break;case UPQ: // 标记?,不确定是否有地雷case LOWQ:if (mine[x][y].flag == 3) // 如果在已经标记为?的方格上再按一次?键,则取消标记?{mine[x][y].flag = 0;draw_rect(0);break;}if (mine[x][y].flag != 0)break;mine[x][y].flag = 3;draw_rect(3); // 显示标记?show(); // 显示当前选择的方块break;case UPD:case LOWD:for (x = 0; x < 10; x++) // 显示出所有地雷for (y = 0; y < 10; y++)if (mine[x][y].mark == false)draw_rect(4);set_fontColor(0x8c);goto_xy(16, MAXY + 2);printf("%12s", "sorry你输了");draw_face(2); // 显示出悲伤的表情_getch();break;case ESC:exit(1);break;default:break;}}}getchar();return ;}void draw_face(int type){set_fontColor(0x8a);goto_xy(8, MAXY + 2);switch (type){case 0: printf("%16s", "状态:@_@"); break; // 游戏进行中case 1: printf("%16s", "状态:^_^"); break; // 胜利case 2: printf("%16s", "状态:>_<"); break; // 失败default: break;}}void open_mine(void)// 扫雷,此函数调用者已经判断了是否踩雷,不需重复判断{int temp_x, temp_y;int m, n;temp_x = x;temp_y = y;if (mine[x][y].num == 0 && mine[x][y].flag == 0) // 没有被挖开且方格上没有数字{mine[x][y].flag = 1;draw_rect(1); // 挖开此处方格for (m = -1; m<2; m++) // 挖开此方格周围的方格for (n = -1; n<2; n++){x = temp_x + m;y = temp_y + n;if (x == temp_x && y == temp_y) // 如果不加此条件,则无限递归continue;if (x >= 0 && x<10 && y >= 0 && y<10)// 限制边界并递归open_mine();}}else // 如果数字非0挖开方格,如果标记非0挖开方格,但不会挖开地雷,地雷周围有非0数字方格包围{ // 而挖到数字方格时是递归函数返回的时候,所以挖到数字方格停止翻开方格mine[x][y].flag = 1;draw_rect(1);}x = temp_x;y = temp_y;}int is_win(void){int i, j;for (i = 0; i<10; i++)for (j = 0; j<10; j++){if (mine[i][j].flag == 0) // 方格没有挖完return 0;if (mine[i][j].flag == 2&&mine[i][j].mark !=true)return 0;}return 1; // 游戏胜利结束,正确的扫完了所有的雷}。

扫雷项目源代码详解

扫雷项目源代码详解

主函数所在处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实现简单扫雷小游戏

java实现简单扫雷小游戏

java实现简单扫雷⼩游戏本⽂实例为⼤家分享了java实现扫雷游戏的具体代码,供⼤家参考,具体内容如下import java.awt.BorderLayout;import java.awt.Color;import java.awt.Container;import java.awt.GridLayout;import java.awt.Insets;import bel;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.ItemEvent;import java.awt.event.ItemListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.util.Random;import javax.swing.JButton;import javax.swing.JComboBox;import javax.swing.JFrame;import javax.swing.JOptionPane;import javax.swing.JPanel;public class SaoLei implements MouseListener,ActionListener{JPanel p=new JPanel();JFrame frame = new JFrame("扫雷");@SuppressWarnings("rawtypes")JComboBox combobox = new JComboBox();JButton reset = new JButton("重新开始");Container container = new Container();//游戏数据结构SaoLeiConstant constant = new SaoLeiConstant();JButton[][] buttons = new JButton[constant.row][constant.col];//定义按钮int[][] counts = new int [constant.row][constant.col];//定义整型数组保存按钮下⽅雷数//创建构造⽅法public SaoLei() {//显⽰窗⼝frame.setSize(600,700);//600*700frame.setResizable(false);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setLayout(new BorderLayout());//添加重来、选择难度按钮addtopButton();//添加雷区按钮addButtons();//埋雷addLei();//添加雷的计数calcNeiboLei();frame.setVisible(true);}void addtopButton() {p.removeAll();p.add(reset);reset.setBackground(Color.green);reset.setOpaque(true);reset.addActionListener(this);//combobox.addItem("选择难度");combobox.addItem("新⼿难度");combobox.addItem("初级难度");combobox.addItem("中级难度");combobox.addItem("⾼级难度");combobox.addItem("⼤师难度");combobox.setBackground(Color.GREEN);@Overridepublic void itemStateChanged(ItemEvent e) {String item = e.getItem().toString();if(item == "新⼿难度") {constant.leiCount = 20;ResetGame();} else if(item == "初级难度") {constant.leiCount = 43;ResetGame();} else if(item == "中级难度"){constant.leiCount = 63;ResetGame();} else if(item == "⾼级难度"){constant.leiCount = 99;ResetGame();} else if(item == "⼤师难度") {constant.leiCount = 119;ResetGame();}}});p.add(combobox);frame.add(p,BorderLayout.NORTH);//p.add(new Label("总雷数:"+constant.leiCount,Label.CENTER)); //p.add(new Label("总雷数:"+constant.leiCount,Label.RIGHT)); }/*void addnanduButton() {nandu.setBackground(Color.green);nandu.setOpaque(true);nandu.addActionListener(this);frame.add(nandu,BorderLayout.WEST);}void addResetButton() {reset.setBackground(Color.green);reset.setOpaque(true);reset.addActionListener(this);//reset.addMouseListener(this);frame.add(reset,BorderLayout.NORTH);}*/void addLei() {Random rand = new Random();int randRow,randCol;for(int i=0; i<constant.leiCount; i++) {randRow = rand.nextInt(constant.row);randCol = rand.nextInt(constant.col);if(counts[randRow][randCol] == constant.LEICODE) {i--;} else {counts[randRow][randCol] = constant.LEICODE;//buttons[randRow][randCol].setText("X");}}}void addButtons() {frame.add(container,BorderLayout.CENTER);container.setLayout(new GridLayout(constant.row,constant.col)); for(int i=0;i<constant.row;i++) {for(int j=0;j<constant.col;j++) {JButton button = new JButton();button.setBackground(Color.white);button.setOpaque(true);button.addActionListener(this);button.addMouseListener((MouseListener) this);buttons[i][j] = button;}}void calcNeiboLei() {int count;for(int i=0;i<constant.row;i++) {for(int j=0;j<constant.col;j++) {count =0;if(counts[i][j] == constant.LEICODE) continue;if(i>0 && j>0 && counts[i-1][j-1] == constant.LEICODE) count++;if(i>0 && counts[i-1][j] == constant.LEICODE) count++;if(i>0 && j<19 &&counts[i-1][j+1] == constant.LEICODE) count++;if(j>0 && counts[i][j-1] == constant.LEICODE) count++;if(j<19 && counts[i][j+1] == constant.LEICODE) count++;if(i<19 && j>0 && counts[i+1][j-1] == constant.LEICODE) count++;if(i<19 && counts[i+1][j] == constant.LEICODE) count++;if(i<19 && j<19 && counts[i+1][j+1] == constant.LEICODE) count++; counts[i][j] = count;buttons[i][j].setMargin(new Insets(0,0,0,0));//让按钮随按钮上的图案变化 //buttons[i][j].setText(counts[i][j] + "");}}}@Overridepublic void actionPerformed(ActionEvent e) {JButton button = (JButton)e.getSource();if(button.equals(reset)) {ResetGame();//重新开始游戏} else {int count = 0;for(int i=0;i<constant.row;i++) {for(int j=0;j<constant.col;j++) {if(button.equals(buttons[i][j])) {count = counts[i][j];if(count == constant.LEICODE) {loseGame();} else {openCell(i,j);checkWin();}return;}}}}}public void mouseClicked(MouseEvent e) {JButton button = (JButton)e.getSource();if (e.getButton() == MouseEvent.BUTTON3) {//判断⿏标右击动作for(int i=0;i<constant.row;i++) {for(int j=0;j<constant.col;j++) {if(button.equals(buttons[i][j])) {if((buttons[i][j].isEnabled() == true)) {//buttons[i][j].setEnabled(false);buttons[i][j].setMargin(new Insets(0,0,0,0));//让按钮随按钮上的图案变化 buttons[i][j].setText("?");return;}}}}}}void ResetGame() {for(int i=0;i<constant.row;i++) {for(int j=0;j<constant.col;j++) {buttons[i][j].setText("");buttons[i][j].setEnabled(true);buttons[i][j].setBackground(Color.white);counts[i][j] = 0;calcNeiboLei();}void checkWin() {for(int i=0;i<constant.row;i++) {for(int j=0;j<constant.col;j++) {if(buttons[i][j].isEnabled() == true && counts[i][j] != constant.LEICODE ) return; }}JOptionPane.showMessageDialog(frame,"Yeah,你赢了!");}//使⽤递归⽅法打开格⼦void openCell(int i, int j) {if(buttons[i][j].isEnabled() == false) return;buttons[i][j].setBackground(Color.yellow);buttons[i][j].setOpaque(true);buttons[i][j].setEnabled(false);if(counts[i][j] == 0) {if(i>0 && j>0 && counts[i-1][j-1] != constant.LEICODE) openCell(i-1,j-1);if(i>0 && j<19 && counts[i-1][j] != constant.LEICODE) openCell(i-1,j);if(i>0 && j<19 &&counts[i-1][j+1] != constant.LEICODE) openCell(i-1,j+1);if(j>0 && counts[i][j-1] != constant.LEICODE) openCell(i,j-1);if(j<19 && counts[i][j+1] != constant.LEICODE) openCell(i,j+1);if(i<19 && j>0 && counts[i+1][j-1] != constant.LEICODE) openCell(i+1,j-1);if(i<19 && counts[i+1][j] != constant.LEICODE) openCell(i+1,j);if(i<19 && j<19 && counts[i+1][j+1] != constant.LEICODE) openCell(i+1,j+1); } else {buttons[i][j].setMargin(new Insets(0,0,0,0));buttons[i][j].setText(counts[i][j] + "");}}void loseGame() {for(int i=0;i<constant.row;i++) {for(int j=0;j<constant.col;j++) {int count = counts[i][j];if(count == constant.LEICODE) {buttons[i][j].setMargin(new Insets(0,0,0,0));buttons[i][j].setText("雷");buttons[i][j].setBackground(Color.red);buttons[i][j].setEnabled(false);} else {buttons[i][j].setMargin(new Insets(0,0,0,0));buttons[i][j].setText(count + "");buttons[i][j].setEnabled(false);}}}JOptionPane.showMessageDialog(frame,"error,你输了!");}public static void main(String[] args) {new SaoLei();}@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 stubpublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}}常量类public class SaoLeiConstant {final int row = 20;//⾏数30final int col = 20;//列数30final int LEICODE = 10;//定义雷下⽅的数字protected int temp = 20;protected int leiCount = temp;//雷数30}效果图更多精彩游戏,请参考专题以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

教你使用Java实现扫雷小游戏(最新完整版)

教你使用Java实现扫雷小游戏(最新完整版)

教你使⽤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的⾯向对象编程有了更加深⼊的理解。

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();}}}。

java扫雷程序(完整)

java扫雷程序(完整)
card.show(this,"cover");
validate();
}
public JButton getBlockCover(){
return blockCover;
}
}
/question/194399790.html
public JButton start = new JButton(" 开始 ");
public Panel MenuPamel = new Panel();
public Panel mainPanel = new Panel();
public Bomb[][] bombButton;
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"); //疑惑是否有雷
public boolean isBomb; //是否为雷
public boolean isClicked; //是否被点击
public int BombFlag; //探雷标记
public boolean isRight; //是否点击右键
public Bomb(int x,int y)
CardLayout card; //卡片式布局
BlockView(){
card=new CardLayout();

java版扫雷

java版扫雷

java版扫雷package com.titian.bean;import java.awt.CardLayout;import java.awt.Point;public class Grid {char content;boolean state;Point point;public char getContent() {return content;}public void setContent(char content) {this.content = content;}public boolean isState() {return state;}public void setState(boolean state) {this.state = state;}public Point getPoint() {return point;}public void setPoint(Point point) {this.point = point;}}package com.titian.core;import java.awt.Point;import java.util.Random;import com.titian.bean.Grid;public class Game {Grid[][] grid = new Grid[9][9];int count = 10;Random r = new Random();public void addGrid() {for (int i = 0; i < grid.length; i++) {for (int j = 0; j < grid[i].length; j++) {grid[i][j] = new Grid();grid[i][j].setContent(' ');grid[i][j].setState(false);grid[i][j].setPoint(new Point(i,j));}}}public void paint() {for (int i = 0; i < grid.length; i++) {for (int j = 0; j < grid[i].length; j++) {if(grid[i][j].isState()) {System.out.print(grid[i][j].getContent() + " ");}else {System.out.print("■ ");}}System.out.println();}}public void setMine() {int i = 0;do {int x = r.nextInt(9);int y = r.nextInt(9);if(grid[x][y].getContent() != '*') {grid[x][y].setContent('*');i++;}}while(i < count);}public Point[] getPoint(int x, int y) {Point[] point = new Point[8];point[0] = new Point(x - 1, y);point[1] = new Point(x - 1, y - 1);point[2] = new Point(x, y - 1);point[3] = new Point(x + 1, y - 1);point[4] = new Point(x + 1, y);point[5] = new Point(x + 1, y + 1);point[6] = new Point(x, y + 1);point[7] = new Point(x - 1, y + 1);return point;}public void setNumber() {for (int i = 0; i < grid.length; i++) {for (int j = 0; j < grid[i].length; j++) {int sum = 0;if(grid[i][j].getContent() == '*') {continue;}else {Point[] point = getPoint(i, j);for (int k = 0; k < point.length; k++) {Point p = point[k];if(p.x >=0 && p.y >= 0 && p.x < 9 && p.y < 9) {if(grid[p.x][p.y].getContent() == '*') {sum++;}}}}if(sum > 0) {grid[i][j].setContent((char)(48 + sum));}}}}public void stamp(int x, int y) {if(grid[x][y].getContent() == '*') {System.out.println("game over");}else {grid[x][y].setState(true);if(grid[x][y].getContent() == ' ') {Point[] point = getPoint(x, y);for (int k = 0; k < point.length; k++) {Point p = point[k];if(p.x >=0 && p.y >= 0 && p.x < 9 && p.y < 9) {if(grid[p.x][p.y].getContent() == ' ' && grid[p.x][p.y].isState() == false) { stamp(p.x,p.y);}else if(grid[p.x][p.y].getContent() != ' ') {grid[p.x][p.y].setState(true);}}}}}}}package com.titian.test;import java.util.Scanner;import com.titian.core.Game;public class Test1 {public static void main(String[] args) {Game g = new Game();g.addGrid();g.setMine();g.setNumber();Scanner s = new Scanner(System.in);g.paint();while(true) {System.out.println("x坐标");int x = s.nextInt();System.out.println("y坐标");int y = s.nextInt();g.stamp(x, y);g.paint();}}}。

扫雷JAVA代码制作

扫雷JAVA代码制作

Grids中 如何挖地雷,打开方块:递归调用
public void digMine(int row,int col){ if(m_GridTL.getCell(col, row)!=1){ //方块已经打开 return; } if(m_Mine[row][col]){ //方块内藏有地雷 showAllMines(); return; } //计算方块周围地雷总数 int num=0; for( int r = -1; r<=1; r ++ ){ //已经排除自身不是地雷 for( int c = -1; c <=1; c ++ ){ if((row+r)>=0&&(row+r)<nRows && (col+c) >=0 &&(col+c)<nCols){ if(m_Mine[row+r][col+c]){ num++; } } } } m_GridTL.setCell(col, row, 3+num); if(num==0){ for( int r = -1; r <= 1; r ++ ){ //空块炸开 for( int c = -1; c <= 1; c ++ ){ if((row+r)>=0&&(row+r)<nRows && (col+c) >=0 &&(col+c)<nCols){ digMine(row+r,col+c); } } } }
//
//
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

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();}}}。

相关文档
最新文档