Android的扫雷游戏源代码
扫雷游戏部分代码
//设置状态#define freed 0 //初始状态#define click 1 //点击状态#define market 2 //标记为雷状态#define choose 3 //键盘选在状态#define nochoose 4 //为选在状态//设置地雷struct Mine{int x;int y;int status;//0为初始状态,1为被点击状态,2为标记为雷状态int value;//0为空,10为地雷,1-8为数字int ischoose;//是否被键盘选中int tag; //标记位};//一维数组存储地雷区域Mine mine[256];//初始化地雷区域void initpt(){i nt i=0;n owmine=0;f or(int y=0;y<16;y++)for(int x=0;x<16;x++){mine[i].x=x*2+dx+2;mine[i].y=y+dy+1;if(i==0)mine[i].ischoose=choose;//初始化为键盘所在位置elsemine[i].ischoose=nochoose;mine[i].status=freed;mine[i].value=0;mine[i].tag=0;i++;}}//设置地雷个数void setmine(int n){i nt num=0;s rand(time(NULL));w hile(num<n){int n=rand()%256;if(mine[n].value!=MINE_TAG) //如果没有重复的地雷{mine[n].value=MINE_TAG;num++;}}}//查询每个方块周围有几个地雷并标记为数字void setvalue(){f or(int i=0;i<256;i++){if(mine[i].value!=MINE_TAG){if((i+1)%16==0){if((i-16-1)>=0)if(mine[i-16-1].value==MINE_TAG)mine[i].value++;if((i-16)>=0)if(mine[i-16].value==MINE_TAG)mine[i].value++;if((i-1)>=0) //4if(mine[i-1].value==MINE_TAG)mine[i].value++;if((i+16-1)<=255) //6if(mine[i+16-1].value==MINE_TAG)mine[i].value++;if((i+16)<=255) //7if(mine[i+16].value==MINE_TAG)mine[i].value++;}else if(i%16==0){····}int movekey(){HANDLE handle;char buf[1];handle = initiate();WORD wColors[1];wColors[0]=FOREGROUND_RED| FOREGROUND_GREEN|FOREGROUND_INTENSITY; WORD wColors1[1];wColors1[0]=FOREGROUND_BLUE|FOREGROUND_GREEN|FOREGROUND_INTENSITY; //设置颜色WORD wColors2[1]={FOREGROUND_RED|FOREGROUND_INTENSITY};while(1){if(_kbhit()){int key=_getch();int k;switch(key){case right:mine[nowmine].ischoose=nochoose;nowmine++;mine[nowmine].ischoose=choose;break;case left:mine[nowmine].ischoose=nochoose;nowmine--;mine[nowmine].ischoose=choose;break;…case space:if(mine[nowmine].status==market)mine[nowmine].status=freed;elsemine[nowmine].status=market;break;case enter:mine[nowmine].status=click;if(mine[nowmine].value==MINE_TAG){showmine();textout(handle,mine[nowmine].x,mine[nowmine].y,wColors2,1,"¤");textout(handle,dx+10,dy+6,wColors1,1,"你被炸得粉身碎骨!");textout(handle,dx+40,dy,wColors1,1,"重新开始按空格键!");textout(handle,dx+40,dy+1,wColors1,1,"退出按ESC键!");while(1){k=_getch();switch(k){case esc:return 0;break;case space:textout(handle,dx+10,dy+7,wColors1,1," ");return 1;break;}}}if(mine[nowmine].value==0)findnull(nowmine);break;}showtable();}}}//寻找空的小方块void findnull(int i){mine[i].tag=1;if(i%16==0) //如果在左边界,判断上,右,下三个方向有没有雷{if((i-16)>=0)//如果没有出界{if(mine[i-16].tag==0)//如果还没有判断,就判断有没有雷{if(mine[i-16].value==0){mine[i-16].status=click;findnull(i-16);}else if(mine[i-16].value!=MINE_TAG ){mine[i-16].status=click;mine[i-16].tag=1;//标记为已经被判断}}}if(mine[i+1].tag==0){if(mine[i+1].value==0){mine[i+1].status=click;findnull(i+1);}else if(mine[i+1].value!=MINE_TAG){mine[i+1].status=click;mine[i+1].tag=1;}}if((i+16)<=255){if(mine[i+16].tag==0){if(mine[i+16].value==0){mine[i+16].status=click;findnull(i+16);}else if(mine[i+16].value!=MINE_TAG){mine[i+16].status=click;mine[i+16].tag=1;}}}}else if((i+1)%16==0) //如果在右边界,判断左,上,下有没有雷{····}}。
扫雷游戏源代码
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.awt.BorderLayout;import java.awt.Container;import java.awt.Font;import java.awt.GridLayout;import java.awt.Insets;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JPanel;import javax.swing.Timer;public class ScanLei1 extends JFrame implements ActionListener{ private static final long serialVersionUID = 1L;private Container contentPane;private JButton btn;private JButton[] btns;private JLabel b1;private JLabel b2;private JLabel b3;private Timer timer;private int row=9;private int col=9;private int bon=10;private int[][] a;private int b;private int[] a1;private JPanel p,p1,p2,p3;public ScanLei1(String title){super(title);contentPane=getContentPane();setSize(297,377);this.setBounds(400, 100, 400, 500);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);timer =new Timer(1000,(ActionListener) this);a = new int[row+2][col+2];initGUI();}public void initGUI(){p3=new JPanel();b=bon;JMenuBar menuBar=new JMenuBar();JMenu menu1=new JMenu("游戏");JMenu menu2=new JMenu("帮助");JMenuItem mi1=new JMenuItem("初级");JMenuItem mi2 = new JMenuItem("中级");JMenuItem mi3 =new JMenuItem("高级");mi1.addActionListener(this);menu1.add(mi1);mi2.addActionListener(this);menu1.add(mi2);mi3.addActionListener(this);menu1.add(mi3);menuBar.add(menu1);menuBar.add(menu2);p3.add(menuBar);b1=new JLabel(bon+"");a1=new int[bon];btn =new JButton("开始");btn.addActionListener(this);b2=new JLabel("0");b3=new JLabel("");btns=new JButton[row*col];p=new JPanel();p.setLayout(new BorderLayout());contentPane.add(p);p.add(p3,BorderLayout.NORTH);//combo=new JComboBox(new Object[]{"初级","中级","高级"} );//加监听/*combo.addItemListener(new ItemListener(){}});*/p1=new JPanel();//在那个位置//(( FlowLayout)p1.getLayout()).setAlignment( FlowLayout.RIGHT);p1.add(b1);p1.add(btn);p1.add(b2);p1.add(b3);p.add(p3,BorderLayout.NORTH);p.add(p1,BorderLayout.CENTER);p2=new JPanel();p2.setLayout(new GridLayout(row,col,0,0));for(int i=0;i<row*col;i++){btns[i]=new JButton("");btns[i].setMargin(new Insets(0,0,0,0));btns[i].setFont(new Font(null,Font.BOLD,25));btns[i].addActionListener(this);btns[i].addMouseListener(new NormoreMouseEvent());p2.add(btns[i]);}contentPane.add(p,BorderLayout.NORTH);contentPane.add(p2,BorderLayout.CENTER);}public void go(){setVisible(true);}public static void main(String[] args){new ScanLei1("扫雷").go();}public void out(int[][] a,JButton[] btns,ActionEvent e,int i,int x,int y){int p=1;if(a[x][y]==0){a[x][y]=10;btns[i].setEnabled(false); //33for(int l=y-1;l<=y+1;l++){int m=x-1-1;int n=l-1;p=1;System.out.println(a[1][2]);if(n>-1&&n<col&&m>-1&&m<row){for(int q=0;q<row&&p==1;q++){//col-->row;if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){if(a[x-1][l]!=0&&a[x-1][l]!=10){btns[n+col*q].setText(a[x-1][l]+"");a[x-1][l]=10;btns[n+col*q].setEnabled(false);}else if(a[x-1][l]==0){//a[x-1][l]=10;btns[n+col*q].setEnabled(false);out(a,btns,e,n+col*q,x-1,l);////55////a[x-1][l]=10;btns[n+col*q].setEnabled(false);}p=0;}}}p=1;m=x;if(n>-1&&n<col&&m>-1&&m<col){for(int q=0;q<row&&p==1;q++){if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){if(a[x+1][l]!=0&&a[x+1][l]!=10){btns[n+col*q].setText(a[x+1][l]+"");a[x+1][l]=10;btns[n+col*q].setEnabled(false);}else if(a[x+1][l]==0){out(a,btns,e,n+col*q,x+1,l);///55////a[x+1][l]=10;btns[n+col*q].setEnabled(false);}p=0;}}}}int m=x-1;int n=y-1-1;p=1;if(n>-1&&n<col&&m>-1&&m<col){for(int q=0;q<row&&p==1;q++){if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){if(a[x][y-1]!=0&&a[x][y-1]!=10){btns[n+col*q].setText(a[x][y-1]+"");a[x][y-1]=10;btns[n+col*q].setEnabled(false);}else if(a[x][y-1]==0){out(a,btns,e,n+col*q,x,y-1);a[x][y-1]=10;btns[n+col*q].setEnabled(false);}p=0;}}}p=1;m=x-1;n=y+1-1;if(n>-1&&n<col&&m>-1&&m<col){for(int q=0;q<row&&p==1;q++){if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){if(a[x][y+1]!=0&&a[x][y+1]!=10){btns[n+col*q].setText(a[x][y+1]+"");a[x][y+1]=10;btns[n+col*q].setEnabled(false);}else if(a[x][y+1]==0){out(a,btns,e,n+col*q,x,y+1);a[x][y+1]=10;btns[n+col*q].setEnabled(false);}p=0;}}}}}public void actionPerformed(ActionEvent e) {if(e.getActionCommand()=="初级"){row=9;col=9;bon=10;a1=new int[bon];b=bon;//setSize(297,377);a = new int[row+2][col+2];this.remove(p2);timer.stop();b1.setText("10");b2.setText("0");b3.setText("");btns=new JButton[row*col];p2=new JPanel();p2.setLayout(new GridLayout(row,col,0,0));for(int i=0;i<row*col;i++){btns[i]=new JButton(" ");btns[i].setMargin(new Insets(0,0,0,0));btns[i].setFont(new Font(null,Font.BOLD,25));btns[i].addActionListener(this);btns[i].addMouseListener(new NormoreMouseEvent());p2.add(btns[i]);}contentPane.add(p2,BorderLayout.CENTER);//setSize(297,377);this.pack();for(int i=0;i<row*col;i++){btns[i].setText(" ");btns[i].setEnabled(true);}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){a[i][j]=0;}}}else if(e.getActionCommand()=="中级"){row=16;col=16;bon=40;//setSize(33*col,33*row+80);a1=new int[bon];a = new int[row+2][col+2];b=bon;this.remove(p2);timer.stop();b1.setText("40");b2.setText("0");b3.setText("");btns=new JButton[row*col];p2=new JPanel();p2.setLayout(new GridLayout(row,col,0,0));for(int i=0;i<row*col;i++){btns[i]=new JButton(" ");btns[i].setMargin(new Insets(0,0,0,0));btns[i].setFont(new Font(null,Font.BOLD,25));btns[i].addActionListener(this);btns[i].addMouseListener(new NormoreMouseEvent());p2.add(btns[i]);}contentPane.add(p2,BorderLayout.CENTER);this.pack();//setSize(33*col,33*row+80);for(int i=0;i<row*col;i++){btns[i].setText("");btns[i].setEnabled(true);}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){a[i][j]=0;}}}else if(e.getActionCommand()=="高级"){row=16;col=32;bon=99;setSize(33*col,33*row+80);a1=new int[bon];a = new int[row+2][col+2];b=bon;this.remove(p2);timer.stop();b1.setText("99");b2.setText("0");b3.setText("");btns=new JButton[row*col];p2=new JPanel();p2.setLayout(new GridLayout(row,col,0,0));for(int i=0;i<row*col;i++){btns[i]=new JButton(" ");btns[i].setMargin(new Insets(0,0,0,0));btns[i].setFont(new Font(null,Font.BOLD,25));btns[i].addActionListener(this);btns[i].addMouseListener(new NormoreMouseEvent());p2.add(btns[i]);}contentPane.add(p2,BorderLayout.CENTER);//setSize(33*col,33*row+80);this.pack();for(int i=0;i<row*col;i++){btns[i].setText("");btns[i].setEnabled(true);}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){a[i][j]=0;}}}if(e.getSource()==btn){timer.start();b=bon;b3.setText("");//System.out.println(bon);//清空for(int i=0;i<row*col;i++){btns[i].setText("");btns[i].setEnabled(true);}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){a[i][j]=0;}}//产生随机数for(int i=0;i<bon;i++){ int p=1;int m=(int)(Math.random()*row*col);while(p==1){int l=1;int j;for( j=0;j<i&&l==1;j++){if(a1[j]==m){m=(int)(Math.random()*row*col);l=0;}}if(j==i){a1[i]=m;p=0;}}}b1.setText(bon+"");b2.setText("0");//布雷for(int i=0;i<bon;i++){int x=(a1[i]/col+1);int y=(a1[i]%col+1);a[x][y]=100;}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){if(i==0||j==0||i==row+1||j==col+1){a[i][j]=0;}}}for(int i=1;i<=row;i++){for(int j=1;j<=col;j++){if(a[i][j]!=100){for(int l=j-1;l<=j+1;l++){if(a[i-1][l]==100){a[i][j]++;}if(a[i+1][l]==100){a[i][j]++;}}if(a[i][j-1]==100){a[i][j]++;}if(a[i][j+1]==100){a[i][j]++;}}}}}if(e.getSource()==timer){String time=b2.getText().trim();int t=Integer.parseInt(time);//System.out.println(t);if(t>=600){timer.stop();}else{t++;b2.setText(t+"");}}for(int i=0;i<col*row;i++){if(btns[i].getText()!="★"){int x=i/col+1;int y=i%col+1;if(e.getSource()==btns[i]&&a[x][y]==100){ btns[i].setText("★");btns[i].setEnabled(false);a[x][y]=10;for(int k=0;k<col*row;k++){int m1=k/col+1;int n1=k%col+1;if(a[m1][n1]!=10&&btns[k].getText()=="★"){btns[k].setText("*o*");}}for(int j=0;j<col*row;j++){int m=j/col+1;int n=j%col+1;if(a[m][n]==100){btns[j].setText("★");btns[j].setEnabled(false);b3.setText("你输了!!");}btns[j].setEnabled(false);a[m][n]=10;}timer.stop();}else if(e.getSource()==btns[i]){if(a[x][y]==0){out(a,btns,e,i,x,y);a[x][y]=10;btns[i].setEnabled(false);}if(a[x][y]!=0&&a[x][y]!=10){btns[i].setText(a[x][y]+"");btns[i].setEnabled(false);a[x][y]=10;}}}else if(btns[i].getText()=="★"){}}}class NormoreMouseEvent extends MouseAdapter{ public void mouseClicked(MouseEvent e) {System.out.println(b);for(int i=0;i<col*row;i++){int x1=i/col+1;int y1=i%col+1;if(e.getSource()==btns[i]&&btns[i].getText()!="★"&&a[x1][y1]!=10){if(e.getButton()==MouseEvent.BUTTON3){btns[i].setText("★");b--;if(b==0){int flag=0;for(int j=0;j<col*row;j++){int x=j/col+1;int y=j%col+1;if(a[x][y]==100&&btns[j].getText()=="★"){flag++;}}if(flag==bon){timer.stop();b3.setText("你赢了!");}}b1.setText(b+"");}}else if(e.getSource()==btns[i]&&btns[i].getText()=="★"&&a[x1][y1]!=-1){if(e.getButton()==MouseEvent.BUTTON3){btns[i].setText("");b++;if(b>bon){b1.setText(bon+"");}else{b1.setText(b+"");}btns[i].setEnabled(true);}}}}}}import java.awt.BorderLayout;import java.awt.Container;import java.awt.Font;import java.awt.GridLayout;import java.awt.Insets;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JPanel;import javax.swing.Timer;public class ScanLei1 extends JFrame implements ActionListener{ private static final long serialVersionUID = 1L;private Container contentPane;private JButton btn;private JButton[] btns;private JLabel b1;private JLabel b2;private JLabel b3;private Timer timer;private int row=9;private int col=9;private int bon=10;private int[][] a;private int b;private int[] a1;private JPanel p,p1,p2,p3;public ScanLei1(String title){super(title);contentPane=getContentPane();setSize(297,377);this.setBounds(400, 100, 400, 500);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);timer =new Timer(1000,(ActionListener) this);a = new int[row+2][col+2];initGUI();}public void initGUI(){p3=new JPanel();b=bon;JMenuBar menuBar=new JMenuBar();JMenu menu1=new JMenu("游戏");JMenu menu2=new JMenu("帮助");JMenuItem mi1=new JMenuItem("初级");JMenuItem mi2 = new JMenuItem("中级");JMenuItem mi3 =new JMenuItem("高级");mi1.addActionListener(this);menu1.add(mi1);mi2.addActionListener(this);menu1.add(mi2);mi3.addActionListener(this);menu1.add(mi3);menuBar.add(menu1);menuBar.add(menu2);p3.add(menuBar);b1=new JLabel(bon+"");a1=new int[bon];btn =new JButton("开始");btn.addActionListener(this);b2=new JLabel("0");b3=new JLabel("");btns=new JButton[row*col];p=new JPanel();p.setLayout(new BorderLayout());contentPane.add(p);p.add(p3,BorderLayout.NORTH);//combo=new JComboBox(new Object[]{"初级","中级","高级"} );//加监听/*combo.addItemListener(new ItemListener(){}});*/p1=new JPanel();//在那个位置//(( FlowLayout)p1.getLayout()).setAlignment( FlowLayout.RIGHT);p1.add(b1);p1.add(btn);p1.add(b2);p1.add(b3);p.add(p3,BorderLayout.NORTH);p.add(p1,BorderLayout.CENTER);p2=new JPanel();p2.setLayout(new GridLayout(row,col,0,0));for(int i=0;i<row*col;i++){btns[i]=new JButton("");btns[i].setMargin(new Insets(0,0,0,0));btns[i].setFont(new Font(null,Font.BOLD,25));btns[i].addActionListener(this);btns[i].addMouseListener(new NormoreMouseEvent());p2.add(btns[i]);}contentPane.add(p,BorderLayout.NORTH);contentPane.add(p2,BorderLayout.CENTER);}public void go(){setVisible(true);}public static void main(String[] args){new ScanLei1("扫雷").go();}public void out(int[][] a,JButton[] btns,ActionEvent e,int i,int x,int y){ int p=1;if(a[x][y]==0){a[x][y]=10;btns[i].setEnabled(false); //33for(int l=y-1;l<=y+1;l++){int m=x-1-1;int n=l-1;p=1;System.out.println(a[1][2]);if(n>-1&&n<col&&m>-1&&m<row){for(int q=0;q<row&&p==1;q++){//col-->row;if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){if(a[x-1][l]!=0&&a[x-1][l]!=10){btns[n+col*q].setText(a[x-1][l]+"");a[x-1][l]=10;btns[n+col*q].setEnabled(false);}else if(a[x-1][l]==0){//a[x-1][l]=10;btns[n+col*q].setEnabled(false);out(a,btns,e,n+col*q,x-1,l); ////55////a[x-1][l]=10;btns[n+col*q].setEnabled(false);}p=0;}}}p=1;m=x;if(n>-1&&n<col&&m>-1&&m<col){for(int q=0;q<row&&p==1;q++){if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){if(a[x+1][l]!=0&&a[x+1][l]!=10){btns[n+col*q].setText(a[x+1][l]+"");a[x+1][l]=10;btns[n+col*q].setEnabled(false);}else if(a[x+1][l]==0){out(a,btns,e,n+col*q,x+1,l);///55////a[x+1][l]=10;btns[n+col*q].setEnabled(false);}p=0;}}}}int m=x-1;int n=y-1-1;p=1;if(n>-1&&n<col&&m>-1&&m<col){for(int q=0;q<row&&p==1;q++){if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){if(a[x][y-1]!=0&&a[x][y-1]!=10){btns[n+col*q].setText(a[x][y-1]+"");a[x][y-1]=10;btns[n+col*q].setEnabled(false);}else if(a[x][y-1]==0){out(a,btns,e,n+col*q,x,y-1);a[x][y-1]=10;btns[n+col*q].setEnabled(false);}p=0;}}}p=1;m=x-1;n=y+1-1;if(n>-1&&n<col&&m>-1&&m<col){for(int q=0;q<row&&p==1;q++){if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){if(a[x][y+1]!=0&&a[x][y+1]!=10){btns[n+col*q].setText(a[x][y+1]+"");a[x][y+1]=10;btns[n+col*q].setEnabled(false);}else if(a[x][y+1]==0){out(a,btns,e,n+col*q,x,y+1);a[x][y+1]=10;btns[n+col*q].setEnabled(false);}p=0;}}}}}public void actionPerformed(ActionEvent e) {if(e.getActionCommand()=="初级"){row=9;col=9;bon=10;a1=new int[bon];b=bon;//setSize(297,377);a = new int[row+2][col+2];this.remove(p2);timer.stop();b1.setText("10");b2.setText("0");b3.setText("");btns=new JButton[row*col];p2=new JPanel();p2.setLayout(new GridLayout(row,col,0,0));for(int i=0;i<row*col;i++){btns[i]=new JButton(" ");btns[i].setMargin(new Insets(0,0,0,0));btns[i].setFont(new Font(null,Font.BOLD,25));btns[i].addActionListener(this);btns[i].addMouseListener(new NormoreMouseEvent());p2.add(btns[i]);}contentPane.add(p2,BorderLayout.CENTER);//setSize(297,377);this.pack();for(int i=0;i<row*col;i++){btns[i].setText(" ");btns[i].setEnabled(true);}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){a[i][j]=0;}}}else if(e.getActionCommand()=="中级"){row=16;col=16;bon=40;//setSize(33*col,33*row+80);a1=new int[bon];a = new int[row+2][col+2];b=bon;this.remove(p2);timer.stop();b1.setText("40");b2.setText("0");b3.setText("");btns=new JButton[row*col];p2=new JPanel();p2.setLayout(new GridLayout(row,col,0,0));for(int i=0;i<row*col;i++){btns[i]=new JButton(" ");btns[i].setMargin(new Insets(0,0,0,0));btns[i].setFont(new Font(null,Font.BOLD,25));btns[i].addActionListener(this);btns[i].addMouseListener(new NormoreMouseEvent());p2.add(btns[i]);}contentPane.add(p2,BorderLayout.CENTER);this.pack();//setSize(33*col,33*row+80);for(int i=0;i<row*col;i++){btns[i].setText("");btns[i].setEnabled(true);}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){a[i][j]=0;}}}else if(e.getActionCommand()=="高级"){row=16;col=32;bon=99;setSize(33*col,33*row+80);a1=new int[bon];a = new int[row+2][col+2];b=bon;this.remove(p2);timer.stop();b1.setText("99");b2.setText("0");b3.setText("");btns=new JButton[row*col];p2=new JPanel();p2.setLayout(new GridLayout(row,col,0,0));for(int i=0;i<row*col;i++){btns[i]=new JButton(" ");btns[i].setMargin(new Insets(0,0,0,0));btns[i].setFont(new Font(null,Font.BOLD,25));btns[i].addActionListener(this);btns[i].addMouseListener(new NormoreMouseEvent());p2.add(btns[i]);}contentPane.add(p2,BorderLayout.CENTER);//setSize(33*col,33*row+80);this.pack();for(int i=0;i<row*col;i++){btns[i].setText("");btns[i].setEnabled(true);}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){a[i][j]=0;}}}if(e.getSource()==btn){timer.start();b=bon;b3.setText("");//System.out.println(bon);//清空for(int i=0;i<row*col;i++){btns[i].setText("");btns[i].setEnabled(true);}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){a[i][j]=0;}}//产生随机数for(int i=0;i<bon;i++){ int p=1;int m=(int)(Math.random()*row*col);while(p==1){int l=1;int j;for( j=0;j<i&&l==1;j++){if(a1[j]==m){m=(int)(Math.random()*row*col);l=0;}}if(j==i){a1[i]=m;p=0;}}}b1.setText(bon+"");b2.setText("0");//布雷for(int i=0;i<bon;i++){int x=(a1[i]/col+1);int y=(a1[i]%col+1);a[x][y]=100;}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){if(i==0||j==0||i==row+1||j==col+1){a[i][j]=0;}}}for(int i=1;i<=row;i++){for(int j=1;j<=col;j++){if(a[i][j]!=100){for(int l=j-1;l<=j+1;l++){if(a[i-1][l]==100){a[i][j]++;}if(a[i+1][l]==100){a[i][j]++;}}if(a[i][j-1]==100){a[i][j]++;}if(a[i][j+1]==100){a[i][j]++;}}}}}if(e.getSource()==timer){String time=b2.getText().trim();int t=Integer.parseInt(time);//System.out.println(t);if(t>=600){timer.stop();}else{t++;b2.setText(t+"");}}for(int i=0;i<col*row;i++){if(btns[i].getText()!="★"){int x=i/col+1;int y=i%col+1;if(e.getSource()==btns[i]&&a[x][y]==100){btns[i].setText("★");btns[i].setEnabled(false);a[x][y]=10;for(int k=0;k<col*row;k++){int m1=k/col+1;int n1=k%col+1;if(a[m1][n1]!=10&&btns[k].getText()=="★"){btns[k].setText("*o*");}}for(int j=0;j<col*row;j++){int m=j/col+1;int n=j%col+1;if(a[m][n]==100){btns[j].setText("★");btns[j].setEnabled(false);b3.setText("你输了!!");}btns[j].setEnabled(false);a[m][n]=10;}timer.stop();}else if(e.getSource()==btns[i]){if(a[x][y]==0){out(a,btns,e,i,x,y);a[x][y]=10;btns[i].setEnabled(false);}if(a[x][y]!=0&&a[x][y]!=10){btns[i].setText(a[x][y]+"");btns[i].setEnabled(false);a[x][y]=10;}}}else if(btns[i].getText()=="★"){}}}class NormoreMouseEvent extends MouseAdapter{public void mouseClicked(MouseEvent e) {System.out.println(b);for(int i=0;i<col*row;i++){int x1=i/col+1;int y1=i%col+1;if(e.getSource()==btns[i]&&btns[i].getText()!="★"&&a[x1][y1]!=10){if(e.getButton()==MouseEvent.BUTTON3){btns[i].setText("★");b--;if(b==0){int flag=0;for(int j=0;j<col*row;j++){int x=j/col+1;int y=j%col+1;if(a[x][y]==100&&btns[j].getText()=="★"){flag++;}}if(flag==bon){timer.stop();b3.setText("你赢了!");}}b1.setText(b+"");}}else if(e.getSource()==btns[i]&&btns[i].getText()=="★"&&a[x1][y1]!=-1){ if(e.getButton()==MouseEvent.BUTTON3){btns[i].setText("");b++;if(b>bon){b1.setText(bon+"");}else{b1.setText(b+"");}btns[i].setEnabled(true);}}}}}}。
C语言编写的扫雷游戏源代码
C语言编写的扫雷嬉戏源代码/* 源程序*/#include <graphics.h>#include <stdlib.h>#include <dos.h>#define LE 0xff01#define LEFTCLICK 0xff10#define LEFTDRAG 0xff19#define MOUSEMOVE 0xff08struct{int num;/*格子当前处于什么状态,1有雷,0已经显示过数字或者空白格子*/ int roundnum;/*统计格子四周有多少雷*/int flag;/*右键按下显示红旗的标记,0没有红旗标记,1有红旗标记*/}Mine[10][10];int gameAGAIN=0;/*是否重来的变量*/int gamePLAY=0;/*是否是第一次玩嬉戏的标记*/int mineNUM;/*统计处理过的格子数*/char randmineNUM[3];/*显示数字的字符串*/int Keystate;int MouseExist;int MouseButton;int MouseX;int MouseY;void Init(void);/*图形驱动*/void MouseOn(void);/*鼠标光标显示*/void MouseOff(void);/*鼠标光标隐藏*/void MouseSetXY(int,int);/*设置当前位置*/int Le(void);/*左键按下*/int RightPress(void);/*鼠标右键按下*/void MouseGetXY(void);/*得到当前位置*/void Control(void);/*嬉戏开场,重新,关闭*/void GameBegain(void);/*嬉戏开场画面*/void DrawSmile(void);/*画笑脸*/void DrawRedflag(int,int);/*显示红旗*/void DrawEmpty(int,int,int,int);/*两种空格子的显示*/void GameOver(void);/*嬉戏完毕*/void GameWin(void);/*显示成功*/int MineStatistics(int,int);/*统计每个格子四周的雷数*/int ShowWhite(int,int);/*显示无雷区的空白局部*/void GamePlay(void);/*嬉戏过程*/void Close(void);/*图形关闭*/void main(void)Init();Control();Close();}void Init(void)/*图形开场*/{int gd=DETECT,gm;initgraph(&gd,&gm,"c:\\tc");}void Close(void)/*图形关闭*/{closegraph();}void MouseOn(void)/*鼠标光标显示*/{_AX=0x01;geninterrupt(0x33);}void MouseOff(void)/*鼠标光标隐藏*/{_AX=0x02;geninterrupt(0x33);}void MouseSetXY(int x,int y)/*设置当前位置*/ {_CX=x;_DX=y;_AX=0x04;geninterrupt(0x33);}int Le(void)/*鼠标左键按下*/{_AX=0x03;geninterrupt(0x33);return(_BX&1);}int RightPress(void)/*鼠标右键按下*/{_AX=0x03;geninterrupt(0x33);return(_BX&2);}void MouseGetXY(void)/*得到当前位置*/_AX=0x03;geninterrupt(0x33);MouseX=_CX;MouseY=_DX;}void Control(void)/*嬉戏开场,重新,关闭*/{int gameFLAG=1;/*嬉戏失败后推断是否重新开场的标记*/while(1){if(gameFLAG)/*嬉戏失败后没推断出重新开场或者退出嬉戏的话就接着推断*/ {GameBegain(); /*嬉戏初始画面*/GamePlay();/*详细嬉戏*/if(gameAGAIN==1)/*嬉戏中重新开场*/{gameAGAIN=0;continue;}}MouseOn();gameFLAG=0;if(Le())/*推断是否重新开场*/{MouseGetXY();if(MouseX>280&&MouseX<300&&MouseY>65&&MouseY<85){gameFLAG=1;continue;}}if(kbhit())/*推断是否按键退出*/break;}MouseOff();}void DrawSmile(void)/*画笑脸*/{setfillstyle(SOLID_FILL,YELLOW);fillellipse(290,75,10,10);setcolor(YELLOW);setfillstyle(SOLID_FILL,BLACK);/*眼睛*/fillellipse(285,75,2,2);setcolor(BLACK);/*嘴巴*/bar(287,80,293,81);}void DrawRedflag(int i,int j)/*显示红旗*/{setcolor(7);setfillstyle(SOLID_FILL,RED);bar(198+j*20,95+i*20,198+j*20+5,95+i*20+5);setcolor(BLACK);line(198+j*20,95+i*20,198+j*20,95+i*20+10);}void DrawEmpty(int i,int j,int mode,int color)/*两种空格子的显示*/ {setcolor(color);setfillstyle(SOLID_FILL,color);if(mode==0)/*没有单击过的大格子*/bar(200+j*20-8,100+i*20-8,200+j*20+8,100+i*20+8);elseif(mode==1)/*单击过后显示空白的小格子*/bar(200+j*20-7,100+i*20-7,200+j*20+7,100+i*20+7);}void GameBegain(void)/*嬉戏开场画面*/{int i,j;cleardevice();if(gamePLAY!=1){MouseSetXY(290,70); /*鼠标一开场的位置,并作为它的初始坐标*/ MouseX=290;MouseY=70;}gamePLAY=1;/*下次按重新开场的话鼠标不重新初始化*/mineNUM=0;setfillstyle(SOLID_FILL,7);bar(190,60,390,290);for(i=0;i<10;i++)/*画格子*/for(j=0;j<10;j++)DrawEmpty(i,j,0,8);setcolor(7);DrawSmile();/*画脸*/randomize();for(i=0;i<10;i++)/*100个格子随机赋值有没有地雷*/for(j=0;j<10;j++)Mine[i][j].num=random(8);/*假如随机数的结果是1表示这个格子有地雷*/if(Mine[i][j].num==1)mineNUM++;/*现有雷数加1*/elseMine[i][j].num=2;Mine[i][j].flag=0;/*表示没红旗标记*/}sprintf(randmineNUM,"%d",mineNUM); /*显示这次总共有多少雷数*/setcolor(1);settextstyle(0,0,2);outtextxy(210,70,randmineNUM);mineNUM=100-mineNUM;/*变量取空白格数量*/MouseOn();}void GameOver(void)/*嬉戏完毕画面*/{int i,j;setcolor(0);for(i=0;i<10;i++)for(j=0;j<10;j++)if(Mine[i][j].num==1)/*显示全部的地雷*/{DrawEmpty(i,j,0,RED);setfillstyle(SOLID_FILL,BLACK);fillellipse(200+j*20,100+i*20,7,7);}}void GameWin(void)/*显示成功*/{setcolor(11);settextstyle(0,0,2);outtextxy(230,30,"YOU WIN!");}int MineStatistics(int i,int j)/*统计每个格子四周的雷数*/{int nNUM=0;if(i==0&&j==0)/*左上角格子的统计*/{if(Mine[0][1].num==1)nNUM++;if(Mine[1][0].num==1)nNUM++;if(Mine[1][1].num==1)}elseif(i==0&&j==9)/*右上角格子的统计*/{if(Mine[0][8].num==1)nNUM++;if(Mine[1][9].num==1)nNUM++;if(Mine[1][8].num==1)nNUM++;}elseif(i==9&&j==0)/*左下角格子的统计*/{if(Mine[8][0].num==1)nNUM++;if(Mine[9][1].num==1)nNUM++;if(Mine[8][1].num==1)nNUM++;}elseif(i==9&&j==9)/*右下角格子的统计*/{if(Mine[9][8].num==1)nNUM++;if(Mine[8][9].num==1)nNUM++;if(Mine[8][8].num==1)nNUM++;}else if(j==0)/*左边第一列格子的统计*/{if(Mine[i][j+1].num==1)nNUM++;if(Mine[i+1][j].num==1)nNUM++;if(Mine[i-1][j].num==1)nNUM++;if(Mine[i-1][j+1].num==1)nNUM++;if(Mine[i+1][j+1].num==1)nNUM++;else if(j==9)/*右边第一列格子的统计*/ {if(Mine[i][j-1].num==1)nNUM++;if(Mine[i+1][j].num==1)nNUM++;if(Mine[i-1][j].num==1)nNUM++;if(Mine[i-1][j-1].num==1)nNUM++;if(Mine[i+1][j-1].num==1)nNUM++;}else if(i==0)/*第一行格子的统计*/{if(Mine[i+1][j].num==1)nNUM++;if(Mine[i][j-1].num==1)nNUM++;if(Mine[i][j+1].num==1)nNUM++;if(Mine[i+1][j-1].num==1)nNUM++;if(Mine[i+1][j+1].num==1)nNUM++;}else if(i==9)/*最终一行格子的统计*/ {if(Mine[i-1][j].num==1)nNUM++;if(Mine[i][j-1].num==1)nNUM++;if(Mine[i][j+1].num==1)nNUM++;if(Mine[i-1][j-1].num==1)nNUM++;if(Mine[i-1][j+1].num==1)nNUM++;}else/*一般格子的统计*/{if(Mine[i-1][j].num==1)nNUM++;nNUM++;if(Mine[i][j+1].num==1)nNUM++;if(Mine[i+1][j+1].num==1)nNUM++;if(Mine[i+1][j].num==1)nNUM++;if(Mine[i+1][j-1].num==1)nNUM++;if(Mine[i][j-1].num==1)nNUM++;if(Mine[i-1][j-1].num==1)nNUM++;}return(nNUM);/*把格子四周一共有多少雷数的统计结果返回*/}int ShowWhite(int i,int j)/*显示无雷区的空白局部*/{if(Mine[i][j].flag==1||Mine[i][j].num==0)/*假如有红旗或该格处理过就不对该格进展任何推断*/return;mineNUM--;/*显示过数字或者空格的格子就表示多处理了一个格子,当全部格子都处理过了表示成功*/if(Mine[i][j].roundnum==0&&Mine[i][j].num!=1)/*显示空格*/{DrawEmpty(i,j,1,7);Mine[i][j].num=0;}elseif(Mine[i][j].roundnum!=0)/*输出雷数*/{DrawEmpty(i,j,0,8);sprintf(randmineNUM,"%d",Mine[i][j].roundnum);setcolor(RED);outtextxy(195+j*20,95+i*20,randmineNUM);Mine[i][j].num=0;/*已经输出雷数的格子用0表示已经用过这个格子*/return ;}/*8个方向递归显示全部的空白格子*/if(i!=0&&Mine[i-1][j].num!=1)ShowWhite(i-1,j);if(i!=0&&j!=9&&Mine[i-1][j+1].num!=1)ShowWhite(i-1,j+1);ShowWhite(i,j+1);if(j!=9&&i!=9&&Mine[i+1][j+1].num!=1)ShowWhite(i+1,j+1);if(i!=9&&Mine[i+1][j].num!=1)ShowWhite(i+1,j);if(i!=9&&j!=0&&Mine[i+1][j-1].num!=1)ShowWhite(i+1,j-1);if(j!=0&&Mine[i][j-1].num!=1)ShowWhite(i,j-1);if(i!=0&&j!=0&&Mine[i-1][j-1].num!=1)ShowWhite(i-1,j-1);}void GamePlay(void)/*嬉戏过程*/{int i,j,Num;/*Num用来接收统计函数返回一个格子四周有多少地雷*/for(i=0;i<10;i++)for(j=0;j<10;j++)Mine[i][j].roundnum=MineStatistics(i,j);/*统计每个格子四周有多少地雷*/while(!kbhit()){if(Le())/*鼠标左键盘按下*/{MouseGetXY();if(MouseX>280&&MouseX<300&&MouseY>65&&MouseY<85)/*重新来*/{MouseOff();gameAGAIN=1;break;}if(MouseX>190&&MouseX<390&&MouseY>90&&MouseY<290)/*当前鼠标位置在格子范围内*/{j=(MouseX-190)/20;/*x坐标*/i=(MouseY-90)/20;/*y坐标*/if(Mine[i][j].flag==1)/*假如格子有红旗那么左键无效*/continue;if(Mine[i][j].num!=0)/*假如格子没有处理过*/{if(Mine[i][j].num==1)/*鼠标按下的格子是地雷*/{MouseOff();GameOver();/*嬉戏失败*/}else/*鼠标按下的格子不是地雷*/{MouseOff();Num=MineStatistics(i,j);if(Num==0)/*四周没地雷就用递归算法来显示空白格子*/ShowWhite(i,j);else/*按下格子四周有地雷*/{sprintf(randmineNUM,"%d",Num);/*输出当前格子四周的雷数*/setcolor(RED);outtextxy(195+j*20,95+i*20,randmineNUM);mineNUM--;}MouseOn();Mine[i][j].num=0;/*点过的格子四周雷数的数字变为0表示这个格子已经用过*/if(mineNUM<1)/*成功了*/{GameWin();break;}}}}}if(RightPress())/*鼠标右键键盘按下*/{MouseGetXY();if(MouseX>190&&MouseX<390&&MouseY>90&&MouseY<290)/*当前鼠标位置在格子范围内*/{j=(MouseX-190)/20;/*x坐标*/i=(MouseY-90)/20;/*y坐标*/MouseOff();if(Mine[i][j].flag==0&&Mine[i][j].num!=0)/*原来没红旗现在显示红旗*/{DrawRedflag(i,j);Mine[i][j].flag=1;}elseif(Mine[i][j].flag==1)/*有红旗标记再按右键就红旗消逝*/DrawEmpty(i,j,0,8);Mine[i][j].flag=0;}}MouseOn();sleep(1);}}}。
扫雷游戏源码
Mine_Draw(TotalMineData[i].Pos_X, TotalMineData[i].Pos_Y,IMG_ID_MINE_NUM6);
break;
}
case MS_NUM7:
{
Mine_Draw(TotalMineData[i].Pos_X, TotalMineData[i].Pos_Y,IMG_ID_MINE_NUM7);
//#define GAME_MINE
#if 1
//def GAME_MINE
#define Total_Col 12 //行
#define Total_Row 11 //列
#define Total_BlockNum (Total_Row * Total_Col)
#define SCR_ID_MINE_MAIN 5370 //SCR_ID_CALC_APP
#define SCR_ID_MINE_VICTORY (SCR_ID_MINE_MAIN + 1)
#define SCR_ID_MINE_FAILED (SCR_ID_MINE_MAIN + 2)
break;
}
case MS_MINE:
{
Mine_Draw(TotalMineData[i].Pos_X, TotalMineData[i].Pos_Y,IMG_ID_MINE_MINE);
break;
}
case MS_EXPLODE:
}
else
{
return -1;
}
}
static int Mine_GetTop(int nCurMine)
扫雷游戏代码
扫雷游戏代码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();}。
扫雷游戏源代码
int x,y,z,cc;
bool lei=false;
now_time = time(NULL);
h=now_time;
cc=c;
//初始化数组
for(int i=0;i<maxcell;i++)
for(int y=0;y<maxcell;y++)
void cell(int a,int b,int c)
{
//
time_t now_time;
time_t h;
srand( (unsigned)time( NULL ) );
initgraph((a+2)*cel,(b+5)*cel);
MOUSEMSG m;
int mimi[maxcell][maxcell];
case WM_RBUTTONDOWN:
x=m.x/cel-1;
y=m.y/cel-1;
if(mimi[x][y]==0)
{
mimi[x][y]=2;
cc--;
}
else if(mimi[x][y]==2)
{
/////////////////////////
//@挚爱
//vc6.0 EasyX库
///////////////////////////
#include<graphics.h>
#include <conio.h>
#include<time.h>
#include <stdio.h>
扫雷游戏Java源代码
扫雷游戏Java源代码import java.awt.BorderLayout;import java.awt.Container;import java.awt.Font;import java.awt.GridLayout;import java.awt.Insets;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JPanel;import javax.swing.Timer;public class ScanLei1 extends JFrame implements ActionListener{private static final long serialVersionUID = 1L;private Container contentPane;private JButton btn;private JButton[] btns;private JLabel b1;private JLabel b2;private JLabel b3;private Timer timer;private int row=9;private int col=9;private int bon=10;private int[][] a;private int b;private int[] a1;private JPanel p,p1,p2,p3;public ScanLei1(String title){super(title);contentPane=getContentPane();setSize(297,377);this.setBounds(400, 100, 400, 500);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);timer =new Timer(1000,(ActionListener) this);a = new int[row+2][col+2];initGUI();}public void initGUI(){p3=new JPanel();b=bon;JMenuBar menuBar=new JMenuBar();JMenu menu1=new JMenu("游戏");JMenu menu2=new JMenu("帮助");JMenuItem mi1=new JMenuItem("初级");JMenuItem mi2 = new JMenuItem("中级");JMenuItem mi3 =new JMenuItem("高级");mi1.addActionListener(this);menu1.add(mi1);mi2.addActionListener(this);menu1.add(mi2);mi3.addActionListener(this);menu1.add(mi3);menuBar.add(menu1);menuBar.add(menu2);p3.add(menuBar);b1=new JLabel(bon+"");a1=new int[bon];btn =new JButton("开始");btn.addActionListener(this);b2=new JLabel("0");b3=new JLabel("");btns=new JButton[row*col];p=new JPanel();p.setLayout(new BorderLayout());contentPane.add(p);p.add(p3,BorderLayout.NORTH);//combo=new JComboBox(new Object[]{"初级","中级","高级"} );//加监听/*combo.addItemListener(new ItemListener(){}});*/p1=new JPanel();//在那个位置//(( FlowLayout)p1.getLayout()).setAlignment( FlowLayout.RIGHT);p1.add(b1);p1.add(btn);p1.add(b2);p1.add(b3);p.add(p3,BorderLayout.NORTH);p.add(p1,BorderLayout.CENTER);p2=new JPanel();p2.setLayout(new GridLayout(row,col,0,0));for(int i=0;i<row*col;i++){btns[i]=new JButton("");btns[i].setMargin(new Insets(0,0,0,0));btns[i].setFont(new Font(null,Font.BOLD,25));btns[i].addActionListener(this);btns[i].addMouseListener(new NormoreMouseEvent());p2.add(btns[i]);}contentPane.add(p,BorderLayout.NORTH);contentPane.add(p2,BorderLayout.CENTER);}public void go(){setVisible(true);}public static void main(String[] args){new ScanLei1("扫雷").go();}public void out(int[][] a,JButton[] btns,ActionEvent e,int i,int x,int y){int p=1;if(a[x][y]==0){a[x][y]=10;btns[i].setEnabled(false); //33for(int l=y-1;l<=y+1;l++){int m=x-1-1;int n=l-1;p=1;System.out.println(a[1][2]);if(n>-1&&n<col&&m>-1&&m<row){for(int q=0;q<row&&p==1;q++){//col-->row;if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){if(a[x-1][l]!=0&&a[x-1][l]!=10){btns[n+col*q].setText(a[x-1][l]+"");a[x-1][l]=10;btns[n+col*q].setEnabled(false);}else if(a[x-1][l]==0){//a[x-1][l]=10;btns[n+col*q].setEnabled(false);out(a,btns,e,n+col*q,x-1,l);////55////a[x-1][l]=10;btns[n+col*q].setEnabled(false);}p=0;}}}p=1;m=x;if(n>-1&&n<col&&m>-1&&m<col){for(int q=0;q<row&&p==1;q++){if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){if(a[x+1][l]!=0&&a[x+1][l]!=10){btns[n+col*q].setText(a[x+1][l]+"");a[x+1][l]=10;btns[n+col*q].setEnabled(false);}else if(a[x+1][l]==0){out(a,btns,e,n+col*q,x+1,l);///55////a[x+1][l]=10;btns[n+col*q].setEnabled(false);}p=0;}}}}int m=x-1;int n=y-1-1;if(n>-1&&n<col&&m>-1&&m<col){for(int q=0;q<row&&p==1;q++){if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){if(a[x][y-1]!=0&&a[x][y-1]!=10){btns[n+col*q].setText(a[x][y-1]+"");a[x][y-1]=10;btns[n+col*q].setEnabled(false);}else if(a[x][y-1]==0){out(a,btns,e,n+col*q,x,y-1);a[x][y-1]=10;btns[n+col*q].setEnabled(false);}p=0;}}}p=1;m=x-1;n=y+1-1;if(n>-1&&n<col&&m>-1&&m<col){for(int q=0;q<row&&p==1;q++){if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){if(a[x][y+1]!=0&&a[x][y+1]!=10){btns[n+col*q].setText(a[x][y+1]+"");a[x][y+1]=10;btns[n+col*q].setEnabled(false);}else if(a[x][y+1]==0){out(a,btns,e,n+col*q,x,y+1);a[x][y+1]=10;btns[n+col*q].setEnabled(false);}p=0;}}}}public void actionPerformed(ActionEvent e) {if(e.getActionCommand()=="初级"){row=9;col=9;bon=10;a1=new int[bon];b=bon;//setSize(297,377);a = new int[row+2][col+2];this.remove(p2);timer.stop();b1.setText("10");b2.setText("0");b3.setText("");btns=new JButton[row*col];p2=new JPanel();p2.setLayout(new GridLayout(row,col,0,0));for(int i=0;i<row*col;i++){btns[i]=new JButton(" ");btns[i].setMargin(new Insets(0,0,0,0));btns[i].setFont(new Font(null,Font.BOLD,25));btns[i].addActionListener(this);btns[i].addMouseListener(new NormoreMouseEvent());p2.add(btns[i]);}contentPane.add(p2,BorderLayout.CENTER);//setSize(297,377);this.pack();for(int i=0;i<row*col;i++){btns[i].setText(" ");btns[i].setEnabled(true);}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){a[i][j]=0;}}}else if(e.getActionCommand()=="中级"){row=16;col=16;bon=40;//setSize(33*col,33*row+80);a1=new int[bon];a = new int[row+2][col+2];b=bon;this.remove(p2);timer.stop();b1.setText("40");b2.setText("0");b3.setText("");btns=new JButton[row*col];p2=new JPanel();p2.setLayout(new GridLayout(row,col,0,0));for(int i=0;i<row*col;i++){btns[i]=new JButton(" ");btns[i].setMargin(new Insets(0,0,0,0));btns[i].setFont(new Font(null,Font.BOLD,25));btns[i].addActionListener(this);btns[i].addMouseListener(new NormoreMouseEvent());p2.add(btns[i]);}contentPane.add(p2,BorderLayout.CENTER);this.pack();//setSize(33*col,33*row+80);for(int i=0;i<row*col;i++){btns[i].setText("");btns[i].setEnabled(true);}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){a[i][j]=0;}}}else if(e.getActionCommand()=="高级"){row=16;col=32;bon=99;setSize(33*col,33*row+80);a1=new int[bon];a = new int[row+2][col+2];b=bon;this.remove(p2);timer.stop();b1.setText("99");b2.setText("0");b3.setText("");btns=new JButton[row*col];p2=new JPanel();p2.setLayout(new GridLayout(row,col,0,0));for(int i=0;i<row*col;i++){btns[i]=new JButton(" ");btns[i].setMargin(new Insets(0,0,0,0));btns[i].setFont(new Font(null,Font.BOLD,25));btns[i].addActionListener(this);btns[i].addMouseListener(new NormoreMouseEvent());p2.add(btns[i]);}contentPane.add(p2,BorderLayout.CENTER);//setSize(33*col,33*row+80);this.pack();for(int i=0;i<row*col;i++){btns[i].setText("");btns[i].setEnabled(true);}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){a[i][j]=0;}}}if(e.getSource()==btn){timer.start();b=bon;b3.setText("");//System.out.println(bon);//清空for(int i=0;i<row*col;i++){btns[i].setText("");btns[i].setEnabled(true);}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){a[i][j]=0;}}//产生随机数for(int i=0;i<bon;i++){ int p=1;int m=(int)(Math.random()*row*col);while(p==1){int l=1;int j;for( j=0;j<i&&l==1;j++){if(a1[j]==m){m=(int)(Math.random()*row*col);l=0;}}if(j==i){a1[i]=m;p=0;}}}b1.setText(bon+"");b2.setText("0");//布雷for(int i=0;i<bon;i++){int x=(a1[i]/col+1);int y=(a1[i]%col+1);a[x][y]=100;}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){if(i==0||j==0||i==row+1||j==col+1){a[i][j]=0;}}}for(int i=1;i<=row;i++){for(int j=1;j<=col;j++){if(a[i][j]!=100){for(int l=j-1;l<=j+1;l++){if(a[i-1][l]==100){a[i][j]++;}if(a[i+1][l]==100){a[i][j]++;}}if(a[i][j-1]==100){a[i][j]++;}if(a[i][j+1]==100){a[i][j]++;}}}}}if(e.getSource()==timer){String time=b2.getText().trim();int t=Integer.parseInt(time);//System.out.println(t);if(t>=600){timer.stop();}else{t++;b2.setText(t+"");}}for(int i=0;i<col*row;i++){if(btns[i].getText()!="★"){int x=i/col+1;int y=i%col+1;if(e.getSource()==btns[i]&&a[x][y]==100){btns[i].setText("★");btns[i].setEnabled(false);a[x][y]=10;for(int k=0;k<col*row;k++){int m1=k/col+1;int n1=k%col+1;if(a[m1][n1]!=10&&btns[k].getText()=="★"){btns[k].setText("*o*");}}for(int j=0;j<col*row;j++){int m=j/col+1;int n=j%col+1;if(a[m][n]==100){btns[j].setText("★");btns[j].setEnabled(false);b3.setText("你输了!!");}btns[j].setEnabled(false);a[m][n]=10;}timer.stop();}else if(e.getSource()==btns[i]){if(a[x][y]==0){out(a,btns,e,i,x,y);a[x][y]=10;btns[i].setEnabled(false);}if(a[x][y]!=0&&a[x][y]!=10){btns[i].setText(a[x][y]+"");btns[i].setEnabled(false);a[x][y]=10;}}}else if(btns[i].getText()=="★"){}}}class NormoreMouseEvent extends MouseAdapter{public void mouseClicked(MouseEvent e) {System.out.println(b);for(int i=0;i<col*row;i++){int x1=i/col+1;int y1=i%col+1;if(e.getSource()==btns[i]&&btns[i].getText()!="★"&&a[x1][y1]!=10) {if(e.getButton()==MouseEvent.BUTTON3){btns[i].setText("★");b--;if(b==0){int flag=0;for(int j=0;j<col*row;j++){int x=j/col+1;int y=j%col+1;if(a[x][y]==100&&btns[j].getText()=="★"){flag++;}}if(flag==bon){timer.stop();b3.setText("你赢了!");}}b1.setText(b+"");}}elseif(e.getSource()==btns[i]&&btns[i].getText()=="★"&&a[x1][y1]!=-1){if(e.getButton()==MouseEvent.BUTTON3){btns[i].setText("");b++;if(b>bon){b1.setText(bon+"");}else{b1.setText(b+"");}btns[i].setEnabled(true);}}}}}}。
扫雷源代码
namespace saolei { public class LeiButton:Button { //返回按钮所在的矩阵点,即二维数组的两个参数。在鼠标单击控件时可通过这连个变 量的属性值返回得到,进而可确定扫雷函数(在窗体类中定义)的两个参数 private int x; private int y; //0表示无地雷。1表示有地雷 private int youlei;
Program.form = this; restlie = Leishu; label4.Text = ""; groupBox1.Location = new Point(26, 26); groupBox1.Text = ""; groupBox1.Size = new System.Drawing.Size(908, 488); groupBox1.FlatStyle = FlatStyle.Standard; lei.Text = " "+restlie.ToString() + "颗"; this.Location = new Point(20, 20); timer1.Enabled = true; Leizheng(); Bulei(); this.StartPosition = FormStartPosition.Manual; timer1.Tick += new EventHandler(timer1_Tick); timer1.Interval = 1000; } /// <summary> /// 定义timer组件的Tick事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void timer1_Tick(object sender, EventArgs e) { yongshi++; if (yongshi < 60) label4.Text = yongshi.ToString() + "秒"; else label4.Text = (yongshi /60).ToString() + "分" + (yongshi % 60).ToString() + "秒"; }
扫雷游戏开发代码
}
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();
扫雷4Android(附源码)
扫雷4Android(附源码) 最近由于项⽬需要学习了⼀下Android ,感觉汗不错。
做了⼀个Android版的扫雷游戏。
游戏简介 在此游戏中,我们使⽤⼀个块的⽹格,其中有⼀些随机的地雷下⾯是效果图⼀、应⽤程序布局使⽤TableLayout布局控件。
设置3⾏。
⼆、地雷块Block.java/*** 地雷的块,继承⾃Button* @author 记忆的永恒**/public class Block extends Button {private boolean isCovered; // 块是否覆盖private boolean isMined; // 下个块private boolean isFlagged; // 是否将该块标记为⼀个潜在的地雷private boolean isQuestionMarked; // 是否是块的问题标记private boolean isClickable; // 是否可以单击private int numberOfMinesInSurrounding; // 在附近的地雷数量块public Block(Context context) {super(context);// TODO Auto-generated constructor stub}public Block(Context context, AttributeSet attrs) {super(context, attrs);// TODO Auto-generated constructor stub}public Block(Context context, AttributeSet attrs, int defStyle){super(context, attrs, defStyle);}/*** 设置默认参数*/public void setDefaults() {isCovered = true;isMined = false;isFlagged = false;isQuestionMarked = false;isClickable = true;numberOfMinesInSurrounding = 0;this.setBackgroundResource(R.drawable.square_blue);setBoldFont();}public void setNumberOfSurroundingMines(int number) {this.setBackgroundResource(R.drawable.square_grey);updateNumber(number);}public void setMineIcon(boolean enabled) {this.setText("M");if (!enabled) {this.setBackgroundResource(R.drawable.square_grey);this.setTextColor(Color.RED);}else {this.setTextColor(Color.BLACK);}}public void setFlagIcon(boolean enabled) {this.setText("F");if (!enabled) {this.setBackgroundResource(R.drawable.square_grey);this.setTextColor(Color.RED);}else {this.setTextColor(Color.BLACK);}}public void setQuestionMarkIcon(boolean enabled) {this.setText("?");if (!enabled) {this.setBackgroundResource(R.drawable.square_grey);this.setTextColor(Color.RED);}else {this.setTextColor(Color.BLACK);}}public void setBlockAsDisabled(boolean enabled) {if (!enabled) {this.setBackgroundResource(R.drawable.square_grey);}else {this.setTextColor(R.drawable.square_blue);}}public void clearAllIcons() {this.setText("");}private void setBoldFont() {this.setTypeface(null, Typeface.BOLD);}public void OpenBlock() {if (!isCovered) {return;}setBlockAsDisabled(false);isCovered = false;if (hasMine()) {setMineIcon(false);}else {setNumberOfSurroundingMines(numberOfMinesInSurrounding); }}public void updateNumber(int text) {if (text != 0) {this.setText(Integer.toString(text));switch (text) {case 1:this.setTextColor(Color.BLUE);break;case 2:this.setTextColor(Color.rgb(0, 100, 0));break;case 3:this.setTextColor(Color.RED);break;case 4:this.setTextColor(Color.rgb(85, 26, 139));break;case 5:this.setTextColor(Color.rgb(139, 28, 98));break;case 6:this.setTextColor(Color.rgb(238, 173, 14));break;case 7:this.setTextColor(Color.rgb(47, 79, 79));break;case 8:this.setTextColor(Color.rgb(71, 71, 71));break;case 9:this.setTextColor(Color.rgb(205, 205, 0));break;}}}public void plantMine() {isMined = true;}public void triggerMine() {setMineIcon(true);this.setTextColor(Color.RED);}public boolean isCovered() {return isCovered;}public boolean hasMine() {return isMined;}public void setNumberOfMinesInSurrounding(int number) {numberOfMinesInSurrounding = number;}public int getNumberOfMinesInSorrounding() {return numberOfMinesInSurrounding;}public boolean isFlagged() {return isFlagged;}public void setFlagged(boolean flagged) {isFlagged = flagged;}public boolean isQuestionMarked() {return isQuestionMarked;}public void setQuestionMarked(boolean questionMarked) {isQuestionMarked = questionMarked;}public boolean isClickable() {return isClickable;}public void setClickable(boolean clickable) {isClickable = clickable;}}三、主界⾯1.TableLayout动态添加⾏mineField = (TableLayout)findViewById(R.id.MineField);private void showMineField(){for (int row = 1; row < numberOfRowsInMineField + 1; row++){TableRow tableRow = new TableRow(this);tableRow.setLayoutParams(new LayoutParams((blockDimension + 2 * blockPadding) * numberOfColumnsInMineField, blockDimension + 2 * blockPadding));for (int column = 1; column < numberOfColumnsInMineField + 1; column++){blocks[row][column].setLayoutParams(new LayoutParams(blockDimension + 2 * blockPadding,blockDimension + 2 * blockPadding));blocks[row][column].setPadding(blockPadding, blockPadding, blockPadding, blockPadding);tableRow.addView(blocks[row][column]);}mineField.addView(tableRow,new youtParams((blockDimension + 2 * blockPadding) * numberOfColumnsInMineField, blockDimension + 2 * blockPadding)); }}2.定时器Handlerprivate Handler timer = new Handler();private int secondsPassed = 0;public void startTimer(){ if (secondsPassed == 0){timer.removeCallbacks(updateTimeElasped);// tell timer to run call back after 1 secondtimer.postDelayed(updateTimeElasped, 1000);}}public void stopTimer(){// disable call backstimer.removeCallbacks(updateTimeElasped);}// timer call back when timer is tickedprivate Runnable updateTimeElasped = new Runnable(){public void run(){long currentMilliseconds = System.currentTimeMillis();++secondsPassed;txtTimer.setText(Integer.toString(secondsPassed));// add notificationtimer.postAtTime(this, currentMilliseconds);// notify to call back after 1 seconds// basically to remain in the timer looptimer.postDelayed(updateTimeElasped, 1000);}};3.第⼀次点击private boolean isTimerStarted; // check if timer already started or notblocks[row][column].setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View view){// start timer on first clickif (!isTimerStarted){startTimer();isTimerStarted = true;}...}});4.第⼀次点击⽆雷private boolean areMinesSet; // check if mines are planted in blocksblocks[row][column].setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View view){...// set mines on first clickif (!areMinesSet){areMinesSet = true;setMines(currentRow, currentColumn);}}});private void setMines(int currentRow, int currentColumn){// set mines excluding the location where user clickedRandom rand = new Random();int mineRow, mineColumn;for (int row = 0; row < totalNumberOfMines; row++){mineRow = rand.nextInt(numberOfColumnsInMineField);mineColumn = rand.nextInt(numberOfRowsInMineField);if ((mineRow + 1 != currentColumn) || (mineColumn + 1 != currentRow)){if (blocks[mineColumn + 1][mineRow + 1].hasMine()){row--; // mine is already there, don't repeat for same block}// plant mine at this locationblocks[mineColumn + 1][mineRow + 1].plantMine();}// exclude the user clicked locationelse{row--;}}int nearByMineCount;// count number of mines in surrounding blocks...}5.点击雷块的效果private void rippleUncover(int rowClicked, int columnClicked){// don't open flagged or mined rowsif (blocks[rowClicked][columnClicked].hasMine() || blocks[rowClicked][columnClicked].isFlagged()) {return;}// open clicked blockblocks[rowClicked][columnClicked].OpenBlock();// if clicked block have nearby mines then don't open furtherif (blocks[rowClicked][columnClicked].getNumberOfMinesInSorrounding() != 0 ){return;}// open next 3 rows and 3 columns recursivelyfor (int row = 0; row < 3; row++){for (int column = 0; column < 3; column++){// check all the above checked conditions// if met then open subsequent blocksif (blocks[rowClicked + row - 1][columnClicked + column - 1].isCovered()&& (rowClicked + row - 1 > 0) && (columnClicked + column - 1 > 0)&& (rowClicked + row - 1 < numberOfRowsInMineField + 1)&& (columnClicked + column - 1 < numberOfColumnsInMineField + 1)){rippleUncover(rowClicked + row - 1, columnClicked + column - 1 );}}}return;}6.以问好标记空⽩blocks[row][column].setOnLongClickListener(new OnLongClickListener(){public boolean onLongClick(View view){// simulate a left-right (middle) click// if it is a long click on an opened mine then// open all surrounding blocks...// if clicked block is enabled, clickable or flaggedif (blocks[currentRow][currentColumn].isClickable() &&(blocks[currentRow][currentColumn].isEnabled() || blocks[currentRow][currentColumn].isFlagged())){// for long clicks set:// 1. empty blocks to flagged// 2. flagged to question mark// 3. question mark to blank// case 1. set blank block to flaggedif (!blocks[currentRow][currentColumn].isFlagged() && !blocks[currentRow][currentColumn].isQuestionMarked()) {blocks[currentRow][currentColumn].setBlockAsDisabled(false);blocks[currentRow][currentColumn].setFlagIcon(true);blocks[currentRow][currentColumn].setFlagged(true);minesToFind--; //reduce mine countupdateMineCountDisplay();}// case 2. set flagged to question markelse if (!blocks[currentRow][currentColumn].isQuestionMarked()){blocks[currentRow][currentColumn].setBlockAsDisabled(true);blocks[currentRow][currentColumn].setQuestionMarkIcon(true);blocks[currentRow][currentColumn].setFlagged(false);blocks[currentRow][currentColumn].setQuestionMarked(true);minesToFind++; // increase mine countupdateMineCountDisplay();}// case 3. change to blank squareelse{blocks[currentRow][currentColumn].setBlockAsDisabled(true);blocks[currentRow][currentColumn].clearAllIcons();blocks[currentRow][currentColumn].setQuestionMarked(false);// if it is flagged then increment mine countif (blocks[currentRow][currentColumn].isFlagged()){minesToFind++; // increase mine countupdateMineCountDisplay();}// remove flagged statusblocks[currentRow][currentColumn].setFlagged(false);}updateMineCountDisplay(); // update mine display}return true;}});7.记录胜负// check status of the game at each stepif (blocks[currentRow + previousRow][currentColumn + previousColumn].hasMine()){// oops game overfinishGame(currentRow + previousRow, currentColumn + previousColumn);}// did we win the gameif (checkGameWin()){// mark game as winwinGame();}private boolean checkGameWin(){for (int row = 1; row < numberOfRowsInMineField + 1; row++){for (int column = 1; column < numberOfColumnsInMineField + 1; column++){if (!blocks[row][column].hasMine() && blocks[row][column].isCovered()){return false;}}}return true;}8.完整代码MinesweeperGame.javapackage com.VertexVerveInc.Games;import java.util.Random;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.util.Log;import android.view.Gravity;import android.view.View;import android.view.View.OnClickListener;import android.view.View.OnLongClickListener;import android.widget.ImageButton;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TableLayout;import android.widget.TableRow;import android.widget.TextView;import android.widget.Toast;import youtParams;public class MinesweeperGame extends Activity {private TextView txtMineCount;private TextView txtTimer;private ImageButton btnSmile;private TableLayout mineField;private Block blocks[][]; // blocks for mine fieldprivate int blockDimension = 24; // width of each blockprivate int blockPadding = 2; // padding between blocksprivate int numberOfRowsInMineField = 9;private int numberOfColumnsInMineField = 9;private int totalNumberOfMines = 10;// timer to keep track of time elapsedprivate Handler timer = new Handler();private int secondsPassed = 0;private boolean isTimerStarted; // check if timer already started or not private boolean areMinesSet; // check if mines are planted in blocks private boolean isGameOver;private int minesToFind; // number of mines yet to be discovered/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.test);txtMineCount = (TextView) findViewById(R.id.minecount);txtTimer = (TextView) findViewById(R.id.timer);btnSmile = (ImageButton) findViewById(R.id.smiley);btnSmile.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View view){endExistingGame();startNewGame();}});mineField = (TableLayout)findViewById(R.id.minefield);showDialog("Click smiley to start New Game", 2000, true, false); }private void startNewGame() {createMineField();// display all blocks in UIshowMineField();minesToFind = totalNumberOfMines;isGameOver = false;secondsPassed = 0;}private void createMineField() {// we take one row extra row for each side// overall two extra rows and two extra columns// first and last row/column are used for calculations purposes only// x|xxxxxxxxxxxxxx|x// ------------------// x| |x// x| |x// ------------------// x|xxxxxxxxxxxxxx|x// the row and columns marked as x are just used to keep counts of near// by minesblocks = new Block[numberOfRowsInMineField + 2][numberOfColumnsInMineField + 2]; for (int row = 0; row < numberOfColumnsInMineField + 2; row++) {for (int column = 0; column < numberOfColumnsInMineField + 2; column++) {blocks[row][column] = new Block(this);blocks[row][column].setDefaults();// pass current row and column number as final int's to event// listeners// this way we can ensure that each event listener is associated// to// particular instance of block onlyfinal int currentRow = row;final int currentColumn = column;blocks[row][column].setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// start timer on first clickif (!isTimerStarted) {startTimer();isTimerStarted = true;}// set mines on first clickif (!areMinesSet) {areMinesSet = true;setMines(currentRow, currentColumn);}// this is not first click// check if current block is flagged// if flagged the don't do anything// as that operation is handled by LongClick// if block is not flagged then uncover nearby blocks// till we get numbered minesif (!blocks[currentRow][currentColumn].isFlagged()) {// open nearby blocks till we get numbered blocksrippleUncover(currentRow, currentColumn);// did we clicked a mineif (blocks[currentRow][currentColumn].hasMine()) {// Oops, game overfinishGame(currentRow, currentColumn);}// check if we win the gameif (checkGameWin()) {// mark game as winwinGame();}}}});// add Long Click listener// this is treated as right mouse click listenerblocks[row][column].setOnLongClickListener(new OnLongClickListener() {public boolean onLongClick(View view) {// simulate a left-right (middle) click// if it is a long click on an opened mine then// open all surrounding blocks.isCovered()&& (blocks[currentRow][currentColumn].getNumberOfMinesInSorrounding() > 0)&& !isGameOver) {int nearbyFlaggedBlocks = 0;for (int previousRow = -1; previousRow < 2; previousRow++) {for (int previousColumn = -1; previousColumn < 2; previousColumn++) { if (blocks[currentRow + previousRow][currentColumn+ previousColumn].isFlagged()) {nearbyFlaggedBlocks++;}}}// if flagged block count is equal to nearby// mine count// then open nearby blocksif (nearbyFlaggedBlocks == blocks[currentRow][currentColumn].getNumberOfMinesInSorrounding()) {for (int previousRow = -1; previousRow < 2; previousRow++) {for (int previousColumn = -1; previousColumn < 2; previousColumn++) { // don't open flagged blocksif (!blocks[currentRow+ previousRow][currentColumn+ previousColumn].isFlagged()) {// open blocks till we get// numbered blockrippleUncover(currentRow+ previousRow,currentColumn+ previousColumn);// did we clicked a mineif (blocks[currentRow+ previousRow][currentColumn+ previousColumn].hasMine()) {// oops game overfinishGame(currentRow+ previousRow,currentColumn+ previousColumn);}// did we win the gameif (checkGameWin()) {// mark game as winwinGame();}}}}}// as we no longer want to judge this// gesture so return// not returning from here will actually// trigger other action// which can be marking as a flag or// question mark or blankreturn true;}// if clicked block is enabled, clickable or// flaggedif (blocks[currentRow][currentColumn].isClickable()&& (blocks[currentRow][currentColumn].isEnabled() || blocks[currentRow][currentColumn].isFlagged())) {// for long clicks set:// 1. empty blocks to flagged// 2. flagged to question mark// 3. question mark to blank// case 1. set blank block to flaggedif (!blocks[currentRow][currentColumn].isFlagged().isQuestionMarked()) {blocks[currentRow][currentColumn].setBlockAsDisabled(false);blocks[currentRow][currentColumn].setFlagIcon(true);blocks[currentRow][currentColumn].setFlagged(true);minesToFind--; // reduce mine countupdateMineCountDisplay();}// case 2. set flagged to question markelse if (!blocks[currentRow][currentColumn].isQuestionMarked()) {blocks[currentRow][currentColumn].setBlockAsDisabled(true);blocks[currentRow][currentColumn].setQuestionMarkIcon(true);blocks[currentRow][currentColumn].setFlagged(false);blocks[currentRow][currentColumn].setQuestionMarked(true);minesToFind++; // increase mine countupdateMineCountDisplay();}// case 3. change to blank squareelse {blocks[currentRow][currentColumn].setBlockAsDisabled(true);blocks[currentRow][currentColumn].clearAllIcons();blocks[currentRow][currentColumn].setQuestionMarked(false);// if it is flagged then increment mine// countif (blocks[currentRow][currentColumn].isFlagged()) {minesToFind++; // increase mine// countupdateMineCountDisplay();}// remove flagged statusblocks[currentRow][currentColumn].setFlagged(false);}updateMineCountDisplay();// update mine// display}return true;}});}}}private void showMineField() {for (int row = 1; row < numberOfRowsInMineField + 1; row++) {TableRow tableRow = new TableRow(this);tableRow.setLayoutParams(new LayoutParams((blockDimension + 2 * blockPadding)* numberOfColumnsInMineField, blockDimension + 2* blockPadding));for (int column = 1; column < numberOfColumnsInMineField + 1; column++) { blocks[row][column].setLayoutParams(new LayoutParams(blockDimension + 2 * blockPadding, blockDimension + 2* blockPadding));blocks[row][column].setPadding(blockPadding, blockPadding,blockPadding, blockPadding);tableRow.addView(blocks[row][column]);}mineField.addView(tableRow, new youtParams((blockDimension + 2 * blockPadding)* numberOfColumnsInMineField, blockDimension + 2* blockPadding));}}private void endExistingGame() {stopTimer(); // stop if timer is runningtxtTimer.setText("000"); // revert all texttxtMineCount.setText("000"); // revert mines countbtnSmile.setBackgroundResource(R.drawable.smile);// remove all rows from mineField TableLayoutmineField.removeAllViews();// set all variables to support end of gameisTimerStarted = false;areMinesSet = false;isGameOver = false;minesToFind = 0;}private boolean checkGameWin() {for (int row = 1; row < numberOfRowsInMineField + 1; row++) {for (int column = 1; column < numberOfColumnsInMineField + 1; column++) { if (!blocks[row][column].hasMine()&& blocks[row][column].isCovered()) {return false;}}}return true;}private void updateMineCountDisplay() {if (minesToFind < 0) {txtMineCount.setText(Integer.toString(minesToFind));} else if (minesToFind < 10) {txtMineCount.setText("00" + Integer.toString(minesToFind));} else if (minesToFind < 100) {txtMineCount.setText("0" + Integer.toString(minesToFind));} else {txtMineCount.setText(Integer.toString(minesToFind));}}private void winGame() {stopTimer();isTimerStarted = false;isGameOver = true;minesToFind = 0; // set mine count to 0// set icon to cool dudebtnSmile.setBackgroundResource(R.drawable.cool);updateMineCountDisplay(); // update mine count// disable all buttons// set flagged all un-flagged blocksfor (int row = 1; row < numberOfRowsInMineField + 1; row++) {for (int column = 1; column < numberOfColumnsInMineField + 1; column++) { blocks[row][column].setClickable(false);if (blocks[row][column].hasMine()) {blocks[row][column].setBlockAsDisabled(false);blocks[row][column].setFlagIcon(true);}}}// show messageshowDialog("You won in " + Integer.toString(secondsPassed)+ " seconds!", 1000, false, true);}private void finishGame(int currentRow, int currentColumn) {isGameOver = true; // mark game as overstopTimer(); // stop timerisTimerStarted = false;btnSmile.setBackgroundResource(R.drawable.sad);// show all mines// disable all blocksfor (int row = 1; row < numberOfRowsInMineField + 1; row++) {for (int column = 1; column < numberOfColumnsInMineField + 1; column++) { // disable blockblocks[row][column].setBlockAsDisabled(false);// block has mine and is not flaggedif (blocks[row][column].hasMine()&& !blocks[row][column].isFlagged()) {// set mine iconblocks[row][column].setMineIcon(false);}// block is flagged and doesn't not have mineif (!blocks[row][column].hasMine()&& blocks[row][column].isFlagged()) {// set flag iconblocks[row][column].setFlagIcon(false);}// block is flaggedif (blocks[row][column].isFlagged()) {// disable the blockblocks[row][column].setClickable(false);}}}// trigger mineblocks[currentRow][currentColumn].triggerMine();// show messageshowDialog("You tried for " + Integer.toString(secondsPassed)+ " seconds!", 1000, false, false);}private void setMines(int currentRow, int currentColumn) {// set mines excluding the location where user clickedRandom rand = new Random();int mineRow, mineColumn;for (int row = 0; row < totalNumberOfMines; row++) {mineRow = rand.nextInt(numberOfColumnsInMineField);mineColumn = rand.nextInt(numberOfRowsInMineField);if ((mineRow + 1 != currentColumn)|| (mineColumn + 1 != currentRow)) {if (blocks[mineColumn + 1][mineRow + 1].hasMine()) {row--; // mine is already there, don't repeat for same block}// plant mine at this locationblocks[mineColumn + 1][mineRow + 1].plantMine();}// exclude the user clicked locationelse {row--;}}int nearByMineCount;for (int row = 0; row < numberOfRowsInMineField + 2; row++) {for (int column = 0; column < numberOfColumnsInMineField + 2; column++) { // for each block find nearby mine countnearByMineCount = 0;if ((row != 0) && (row != (numberOfRowsInMineField + 1))&& (column != 0)&& (column != (numberOfColumnsInMineField + 1))) {// check in all nearby blocksfor (int previousRow = -1; previousRow < 2; previousRow++) {for (int previousColumn = -1; previousColumn < 2; previousColumn++) {if (blocks[row + previousRow][column+ previousColumn].hasMine()) {// a mine was found so increment the counternearByMineCount++;}}}blocks[row][column].setNumberOfMinesInSurrounding(nearByMineCount);}// for side rows (0th and last row/column)// set count as 9 and mark it as openedelse {blocks[row][column].setNumberOfMinesInSurrounding(9);blocks[row][column].OpenBlock();}}}}private void rippleUncover(int rowClicked, int columnClicked) {// don't open flagged or mined rowsif (blocks[rowClicked][columnClicked].hasMine()|| blocks[rowClicked][columnClicked].isFlagged()) {return;}// open clicked blockblocks[rowClicked][columnClicked].OpenBlock();// if clicked block have nearby mines then don't open furtherif (blocks[rowClicked][columnClicked].getNumberOfMinesInSorrounding() != 0) { return;}// open next 3 rows and 3 columns recursivelyfor (int row = 0; row < 3; row++) {for (int column = 0; column < 3; column++) {// check all the above checked conditions// if met then open subsequent blocksif (blocks[rowClicked + row - 1][columnClicked + column - 1].isCovered()&& (rowClicked + row - 1 > 0)&& (columnClicked + column - 1 > 0)&& (rowClicked + row - 1 < numberOfRowsInMineField + 1)&& (columnClicked + column - 1 < numberOfColumnsInMineField + 1)) {rippleUncover(rowClicked + row - 1, columnClicked + column- 1);}}}return;}public void startTimer() {if (secondsPassed == 0) {timer.removeCallbacks(updateTimeElasped);// tell timer to run call back after 1 secondtimer.postDelayed(updateTimeElasped, 1000);Log.i("tag",String.valueOf((timer.postDelayed(updateTimeElasped, 1000))) ); }}public void stopTimer() {// disable call backstimer.removeCallbacks(updateTimeElasped);}// timer call back when timer is tickedprivate Runnable updateTimeElasped = new Runnable() {public void run() {long currentMilliseconds = System.currentTimeMillis();++secondsPassed;txtTimer.setText(Integer.toString(secondsPassed));// add notificationtimer.postAtTime(this, currentMilliseconds);// notify to call back after 1 seconds// basically to remain in the timer looptimer.postDelayed(updateTimeElasped, 1000);}};private void showDialog(String message, int milliseconds,boolean useSmileImage, boolean useCoolImage) {// show messageToast dialog = Toast.makeText(getApplicationContext(), message,Toast.LENGTH_LONG);dialog.setGravity(Gravity.CENTER, 0, 0);LinearLayout dialogView = (LinearLayout) dialog.getView();ImageView coolImage = new ImageView(getApplicationContext());if (useSmileImage) {coolImage.setImageResource(R.drawable.smile);} else if (useCoolImage) {coolImage.setImageResource(R.drawable.cool);} else {coolImage.setImageResource(R.drawable.sad);}dialogView.addView(coolImage, 0);dialog.setDuration(milliseconds);dialog.show();Log.i("tag", "showDialog()");}}。
扫雷源代码(精)
#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。
c语言编写扫雷代码
c语言编写扫雷代码示例编写扫雷游戏的代码涉及到图形界面、事件处理等,因此需要使用相应的库来简化这些操作。
下面是一个使用C语言和Simple DirectMedia Layer (SDL)库编写的简单扫雷游戏的代码示例。
请注意,这只是一个基本的示例,实际的扫雷游戏可能需要更多功能和复杂性。
首先,确保你已经安装了SDL库。
接下来,你可以使用以下代码作为一个简单的扫雷游戏的起点。
```c#include <SDL.h>#include <stdio.h>#include <stdlib.h>#include <time.h>// 游戏常量#define SCREEN_WIDTH 640#define SCREEN_HEIGHT 480#define CELL_SIZE 20#define ROWS 15#define COLS 20#define MINES 40// 游戏状态typedef struct {int revealed; // 是否被揭示int mine; // 是否是地雷int adjacent; // 相邻地雷数量} Cell;// 游戏数据Cell board[ROWS][COLS];// SDL 相关变量SDL_Window* window = NULL;SDL_Renderer* renderer = NULL;// 初始化游戏板void initializeBoard() {// 初始化每个单元格for (int i = 0; i < ROWS; ++i) {for (int j = 0; j < COLS; ++j) {board[i][j].revealed = 0;board[i][j].mine = 0;board[i][j].adjacent = 0;}}// 随机生成地雷位置srand(time(NULL));for (int k = 0; k < MINES; ++k) {int i = rand() % ROWS;int j = rand() % COLS;if (!board[i][j].mine) {board[i][j].mine = 1;// 增加相邻地雷数量for (int ni = i - 1; ni <= i + 1; ++ni) {for (int nj = j - 1; nj <= j + 1; ++nj) {if (ni >= 0 && ni < ROWS && nj >= 0 && nj < COLS && !(ni == i && nj == j)) {board[ni][nj].adjacent++;}}}} else {// 如果已经有地雷,重新生成k--;}}}// 渲染游戏板void renderBoard() {// 清空屏幕SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);SDL_RenderClear(renderer);// 绘制每个单元格for (int i = 0; i < ROWS; ++i) {for (int j = 0; j < COLS; ++j) {if (board[i][j].revealed) {// 已揭示的单元格if (board[i][j].mine) {SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255); // 地雷} else {SDL_SetRenderDrawColor(renderer, 192, 192, 192, 255); // 其他}} else {// 未揭示的单元格SDL_SetRenderDrawColor(renderer, 128, 128, 128, 255);}// 绘制单元格SDL_Rect cellRect = {j * CELL_SIZE, i * CELL_SIZE, CELL_SIZE, CELL_SIZE};SDL_RenderFillRect(renderer, &cellRect);// 绘制地雷数量(已揭示的单元格)if (board[i][j].revealed && !board[i][j].mine && board[i][j].adjacent > 0) {char text[2];snprintf(text, sizeof(text), "%d", board[i][j].adjacent);SDL_Color textColor = {0, 0, 0, 255};SDL_Surface* surface = TTF_RenderText_Solid(font, text, textColor);SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);SDL_Rect textRect = {j * CELL_SIZE + CELL_SIZE / 3, i * CELL_SIZE + CELL_SIZE / 3, CELL_SIZE / 2, CELL_SIZE / 2};SDL_RenderCopy(renderer, texture, NULL, &textRect);SDL_DestroyTexture(texture);SDL_FreeSurface(surface);}}}// 刷新屏幕SDL_RenderPresent(renderer);}// 处理鼠标点击事件void handleMouseClick(int x, int y) {int i = y / CELL_SIZE;int j = x / CELL_SIZE;if (!board[i][j].revealed) {board[i][j].revealed = 1;if (board[i][j].mine) {// 点击到地雷,游戏结束printf("Game Over!\n");SDL_Quit();exit(1);} else {// 递归揭示相邻单元格if (board[i][j].adjacent == 0) {for (int ni = i - 1; ni <= i + 1; ++ni) {for (int nj = j - 1; nj <= j + 1; ++nj) {if (ni >= 0 && ni < ROWS && nj >= 0 && nj < COLS && !(ni == i && nj == j)) {handleMouseClick(nj * CELL_SIZE, ni * CELL_SIZE);}}}}}}}int main() {// 初始化SDLSDL_Init(SDL_INIT_VIDEO);// 创建窗口和渲染器window = SDL_CreateWindow("Minesweeper", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);// 初始化游戏板initializeBoard();// 游戏循环int quit = 0;SDL_Event e;while (!quit) {// 处理事件while (SDL_PollEvent(&e) != 0) {if (e.type == SDL_QUIT) {quit = 1;} else if (e.type == SDL_MOUSEBUTTONDOWN) {if (e.button.button == SDL_BUTTON_LEFT) {handleMouseClick(e.button.x, e.button.y);}}}//渲染游戏板renderBoard();}// 清理资源SDL_DestroyWindow(window);SDL_DestroyRenderer(renderer);SDL_Quit();return 0;}```这是一个简单的扫雷游戏的C语言代码,使用SDL库来创建窗口、处理事件和渲染图形。
扫雷程序源代码
frmMainOption ExplicitDim picFace(0 To 4) As StdPicture '存放笑脸图片Dim picNum(0 To 9) As StdPicture '存放雷区数字图片Dim picArea(0 To 6) As StdPicture '存放雷区非数字图片Dim picTime(0 To 11) As StdPicture '存放时间数字图片Dim Bomb() As Integer '存放地雷位置周围雷数Dim Status() As Integer '记录所在位置状态,0为原状,1为红旗,2为问号,3为点开Dim LeftbombNum As Integer '剩余雷数Dim iTime As Integer '时间Private Sub Form_Load()Dim i As IntegerFor i = 0 To 4 '加载表情图片Set picFace(i) = LoadResPicture(140 + i, 0)NextFor i = 0 To 8Set picNum(i) = LoadResPicture(115 - i, 0) '加载雷区数字图片NextFor i = 0 To 6Set picArea(i) = LoadResPicture(100 + i, 0) '加载雷区非数字图片NextFor i = 0 To 11Set picTime(i) = LoadResPicture(120 + i, 0) '加载时间数字图片NextCall mnuBegin_ClickEnd SubPublic Sub Start() '开始LeftbombNum = Num '初始剩余雷数Text1.Text = NumpicboxArea.Enabled = TruepicboxFace.PaintPicture picFace(4), 0, 0 '显示笑脸图片Dim i As Integer, j As IntegerpicboxArea.Width = 260 * X '布置窗体和控件picboxArea.Height = 260 * YpicboxArea.ScaleWidth = picboxArea.WidthpicboxArea.ScaleHeight = picboxArea.HeightpicboxShow.Width = picboxArea.WidthpicboxShow.ScaleHeight = picboxShow.HeightpicboxShow.ScaleWidth = picboxShow.WidthfrmMain.Width = picboxArea.Width + 180frmMain.Height = picboxArea.Height + picboxShow.Height + 950picboxShow.Left = 50picboxArea.Left = 50picboxShow.Top = 50picboxArea.Top = picboxShow.Height + 140picboxFace.Height = 420picboxFace.Width = 420picboxFace.Left = picboxShow.Width / 2 - 210picboxFace.Top = picboxShow.Height / 2 - 210PicboxNum(5).Left = picboxArea.ScaleWidth - 670PicboxNum(6).Left = picboxArea.ScaleWidth - 415PicboxNum(4).Left = picboxArea.ScaleWidth - 925Call Drawbomb(Val(Text1.Text))PicboxNum(3).PaintPicture picTime(0), 0, 0, 13, 26 '加载时间图像(初始为0)PicboxNum(2).PaintPicture picTime(0), 0, 0, 13, 26PicboxNum(1).PaintPicture picTime(0), 0, 0, 13, 26Timer1.Enabled = FalseiTime = 0Call ArrangeFor j = 1 To Y '绘制雷区For i = 1 To XpicboxArea.PaintPicture picArea(0), (i - 1) * 260, (j - 1) * 260NextNextEnd SubPublic Sub Arrange() '程随机放置地雷Dim i As Integer, j As Integer, k As Integer, l As IntegerReDim Bomb(0 To X + 1, 0 To Y + 1)ReDim Status(0 To X + 1, 0 To Y + 1)RandomizeFor i = 1 To Numxx = Int(Rnd * X + 1): yy = Int(Rnd * Y + 1)If Bomb(xx, yy) <> 10 Then '值为10表示此格有雷Bomb(xx, yy) = 10Else '若此格已有雷,则重新随机选格i = i - 1End IfNextFor j = 1 To YFor i = 1 To XIf Bomb(i, j) <> 10 ThenFor k = -1 To 1For l = -1 To 1If Bomb(i + k, j + l) = 10 Then Bomb(i, j) = Bomb(i, j) + 1 '数周围雷数NextNextEnd IfNextNextFor i = 0 To X + 1 Step X + 1 '设定边界,防止出现无定义For j = 0 To Y + 1Bomb(i, j) = 9NextNextFor j = 0 To Y + 1 Step Y + 1For i = 0 To X + 1Bomb(i, j) = 9NextNextEnd SubPrivate Sub mnuStart_Click() '开局Call mnuBegin_ClickEnd SubPrivate Sub mnuBegin_Click() '初级mnuBegin.Checked = TruemnuMiddle.Checked = FalsemnuExpert.Checked = FalsemnuCust.Checked = FalseX = 9: Y = 9: Num = 10Call StartEnd SubPrivate Sub mnuMiddle_Click() '中级X = 16: Y = 16: Num = 40mnuBegin.Checked = FalsemnuMiddle.Checked = TruemnuCust.Checked = FalsemnuExpert.Checked = FalseCall StartEnd SubPrivate Sub mnuExpert_Click() '高级X = 16: Y = 30: Num = 99mnuBegin.Checked = FalsemnuMiddle.Checked = FalsemnuExpert.Checked = TruemnuCust.Checked = FalseCall StartEnd SubPrivate Sub mnuCust_Click() '自定义mnuCust.Checked = TruefrmCustom.Show 1, Me '显示子顶替对话框,模态窗口,暂停执行位于Show后面的语句End SubPrivate Sub mnuAbout_Click()frmAbout.Show 1, Me '显示关于扫雷对话框,模态窗口,暂停执行位于Show后面的语句End SubPrivate Sub mnuExit_Click() '退出游戏Unload MeEnd SubPrivate Sub mnuRecord_Click()frmRecord.Show 1, Me '显示扫雷英雄榜对话框,模态窗口,暂停执行位于Show后面的语句End SubPrivate Sub picboxFace_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)picboxFace.Picture = picFace(0)End SubPrivate Sub picboxFace_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) picboxFace.Picture = picFace(4)Call StartEnd SubPrivate Sub picboxArea_MouseDown(Button As Integer, Shift As Integer, x1 As Single, y1 As Single)picboxFace.Picture = picFace(3)Dim x2 As Integer, y2 As IntegerPosition x1, y1, x2, y2 '定位If Status(x2, y2) = 0 Then '若鼠标点击的方格为初始状态If Button = 1 Then '左击picboxArea.PaintPicture picNum(0), (x2 - 1) * 260, (y2 - 1) * 260ElseIf Button = 2 Then '右击picboxArea.PaintPicture picArea(1), (x2 - 1) * 260, (y2 - 1) * 260End IfElseIf Status(x2, y2) = 1 Then '若鼠标点击的方格为红旗状态If Button = 2 Then '右击picboxArea.PaintPicture picArea(2), (x2 - 1) * 260, (y2 - 1) * 260End IfElseIf Status(x2, y2) = 2 Then '若鼠标点击的方格为问号状态If Button = 1 Then '左击picboxArea.PaintPicture picArea(6), (x2 - 1) * 260, (y2 - 1) * 260ElseIf Button = 2 Then '右击picboxArea.PaintPicture picArea(0), (x2 - 1) * 260, (y2 - 1) * 260End IfEnd IfTimer1.Enabled = True '计时器开始计时Text1.Text = LeftbombNum - 1 '剩余雷数减少一个End SubPrivate Sub picboxArea_MouseMove(Button As Integer, Shift As Integer, x1 As Single, y1 As Single)If Button = 0 Then Exit SubDim i As Integer, j As IntegerFor i = 1 To XFor j = 1 To YIf Status(i, j) = 0 ThenpicboxArea.PaintPicture picArea(0), (i - 1) * 260, (j - 1) * 260 '当鼠标离开后按下去的按键恢复原状End IfNextNextDim x2 As Integer, y2 As IntegerPosition x1, y1, x2, y2If x2 > 0 And y2 > 0 And x2 < X + 1 And y2 < Y + 1 ThenIf Status(x2, y2) = 0 Then picboxArea.PaintPicture picNum(0), (x2 - 1) * 260, (y2 - 1) *260 '鼠标所在处按键显示按下End IfEnd SubPrivate Sub picboxArea_MouseUp(Button As Integer, Shift As Integer, x1 As Single, y1 As Single)Dim x2 As Integer, y2 As Integer, i As Integer, j As IntegerPosition x1, y1, x2, y2 '定位If x2 > 0 And y2 > 0 And x2 < X + 1 And y2 < Y + 1 ThenIf Status(x2, y2) = 0 Then '若鼠标点击的方格为初始状态If Button = 1 Then '左击If Bomb(x2, y2) <> 0 And Bomb(x2, y2) <> 10 ThenStatus(x2, y2) = 3 '方格被点开picboxArea.PaintPicture picNum(Bomb(x2, y2)), (x2 - 1) * 260, (y2 - 1) * 260 '显示周围雷的个数ElseIf Bomb(x2, y2) = 0 Then '若周围没有雷Status(x2, y2) = 3picboxArea.PaintPicture picNum(0), (x2 - 1) * 260, (y2 - 1) * 260For i = -2 To 0For j = -2 To 0picboxArea_MouseUp 1, 0, 260 * (x2 + i), 260 * (y2 + j) '检查周围八个格子NextNextElseIf Bomb(x2, y2) = 10 Then '若有雷For i = 1 To XFor j = 1 To YIf Bomb(i, j) = 10 And Status(i, j) = 0 ThenpicboxArea.PaintPicture picArea(5), (i - 1) * 260, (j - 1) * 260 '未被标记的雷显示ElseIf Bomb(i, j) = 10 And Status(i, j) = 1 ThenpicboxArea.PaintPicture picArea(4), (i - 1) * 260, (j - 1) * 260 '被标记的雷显示ElseIf Bomb(i, j) = 10 And Status(i, j) = 2 ThenpicboxArea.PaintPicture picArea(5), (i - 1) * 260, (j - 1) * 260 '疑似的雷显示End IfNextNextpicboxArea.PaintPicture picArea(3), (x2 - 1) * 260, (y2 - 1) * 260 '被点开的雷显示picboxArea.Enabled = False '雷区不响应任何事件End IfElseIf Button = 2 Then '右击picboxArea.PaintPicture picArea(1), (x2 - 1) * 260, (y2 - 1) * 260 '方格被标记红旗Status(x2, y2) = 1LeftbombNum = LeftbombNum - 1 '剩余雷数减少一个End IfElseIf Status(x2, y2) = 1 Then '若鼠标点击的方格为红旗If Button = 2 Then '右击picboxArea.PaintPicture picArea(2), (i - 1) * 260, (j - 1) * 260 '方格状态变为问号Status(x2, y2) = 2LeftbombNum = LeftbombNum + 1 '剩余雷数增加一End IfElseIf Status(x2, y2) = 2 Then '若鼠标点击的方格为问号If Button = 1 Then '左击If Bomb(x2, y2) <> 0 And Bomb(x2, y2) <> 10 ThenStatus(x2, y2) = 3 '方格被点开picboxArea.PaintPicture picNum(Bomb(x2, y2)), (x2 - 1) * 260, (y2 - 1) * 260ElseIf Bomb(x2, y2) = 0 Then '若周围无雷Status(x2, y2) = 3 '方格被点开picboxArea.PaintPicture picNum(0), (x2 - 1) * 260, (y2 - 1) * 260For i = -2 To 0 '检查周围八个格子For j = -2 To 0picboxArea_MouseUp 1, 0, 260 * (x2 + i), 260 * (y2 + j)NextNextElseIf Bomb(x2, y2) = 10 Then '若有雷For i = 1 To XFor j = 1 To YIf Bomb(i, j) = 10 And Status(i, j) = 0 ThenpicboxArea.PaintPicture picArea(5), (i - 1) * 260, (j - 1) * 260 '未被标记的雷显示ElseIf Bomb(i, j) = 10 And Status(i, j) = 1 ThenpicboxArea.PaintPicture picArea(4), (i - 1) * 260, (j - 1) * 260 '被标记的雷显示ElseIf Bomb(i, j) = 10 And Status(i, j) = 2 ThenpicboxArea.PaintPicture picArea(5), (i - 1) * 260, (j - 1) * 260 '疑似的雷显示End IfNextNextpicboxArea.PaintPicture picArea(3), (x2 - 1) * 260, (y2 - 1) * 260 '被点开的雷显示picboxArea.Enabled = False '雷区不响应任何事件End IfElseIf Button = 2 Then '右击picboxArea.PaintPicture picArea(0), (i - 1) * 260, (j - 1) * 260Status(x2, y2) = 0End IfEnd IfElseIf Status(x2, y2) = 3 Then '若方格被点开Dim n As IntegerFor i = -1 To 1For j = -1 To 1If Status(x2 + i, y2 + j) = 1 Then n = n + 1NextNextIf n = Bomb(x2, y2) ThenFor i = -2 To 0 '检查周围八个格子For j = -2 To 0picboxArea_MouseUp 1, 0, (x2) * 260, (y2) * 260NextNextEnd IfEnd IfIf picboxArea.Enabled ThenpicboxFace.Picture = picFace(4)ElsepicboxFace.Picture = picFace(2)Timer1.Enabled = False '计时器停止iTime = 0 '时间清零frmCheer.Show 1, Me '显示加油窗体End IfText1.Text = LeftbombNum '文本框中显示剩余雷数Dim time1 As Integer, time2 As Integer, time3 As Integer '把含有时间信息的字符串转换为数值time1 = Val(frmRecord.lblTime1.Caption)time2 = Val(frmRecord.lblTime2.Caption)time3 = Val(frmRecord.lblTime3.Caption)If Text1.Text = 0 ThenIf Bomb(xx, yy) = 10 ThenIf Status(xx, yy) = 1 Then '若所有地雷全部标记出来了Timer1.Enabled = False '计时器停止计时If Y = 9 And iTime >= time1 Then '若为初级,未破纪录frmWin.Show 1, Me '显示胜利对话框picboxFace.PaintPicture picFace(1), 0, 0ElseIf Y = 9 And iTime < time1 Then '若为初级,破了纪录frmMessage1.Show 1, Me '显示扫雷英雄榜信息提示对话框End IfIf Y = 16 And iTime >= time2 Then '若为中级,未破纪录frmWin.Show 1, Me '显示胜利对话框picboxFace.PaintPicture picFace(1), 0, 0ElseIf Y = 16 And iTime < time2 Then '若为中级,破了纪录frmMessage2.Show 1, Me '显示扫雷英雄榜信息提示对话框End IfIf Y = 40 And iTime >= time3 Then '若为高级,未破纪录frmWin.Show 1, Me '显示胜利对话框picboxFace.PaintPicture picFace(1), 0, 0ElseIf Y = 30 And iTime < time3 Then '若为高级,破了纪录frmMessage3.Show 1, Me '显示扫雷英雄榜信息提示对话框End IfEnd IfEnd IfEnd IfEnd SubPrivate Sub Position(x1 As Single, y1 As Single, x2 As Integer, y2 As Integer)x2 = x1 \ 260 + 1: y2 = y1 \ 260 + 1 '显示鼠标所在格子坐标End SubSub DrawNum(inum As Integer)If iTime >= "0" And iTime <= "9" Then '绘制数字0-9PicboxNum(3).PaintPicture picTime(Val(iTime)), 0, 0, 13, 26PicboxNum(2).PaintPicture picTime(Val(0)), 0, 0, 13, 26PicboxNum(1).PaintPicture picTime(Val(0)), 0, 0, 13, 26ElseIf iTime >= "10" And iTime <= "99" ThenPicboxNum(3).PaintPicture picTime(Val(iTime Mod 10)), 0, 0, 13, 26PicboxNum(2).PaintPicture picTime(Val(iTime \ 10)), 0, 0, 13, 26PicboxNum(1).PaintPicture picTime(Val(0)), 0, 0, 13, 26ElseIf iTime >= "100" And iTime <= "999" ThenPicboxNum(1).PaintPicture picTime(Val(iTime \ 100)), 0, 0, 13, 26PicboxNum(2).PaintPicture picTime(Val(iTime \ 10 - 10 * (iTime \ 100))), 0, 0, 13, 26PicboxNum(3).PaintPicture picTime(Val(iTime Mod 10)), 0, 0, 13, 26 '绘制时间显示图像End IfCall Drawbomb(Val(LeftbombNum))End SubPrivate Sub Timer1_Timer() '显示游戏时间If iTime < 999 TheniTime = iTime + 1DrawNum iTimeTimer1.Interval = 1000End IfCall DrawNum(Val(Text1.Text))End SubSub Drawbomb(LeftbombNum As Integer) '绘制剩余雷数图像LeftbombNum = Val(Text1.Text)If LeftbombNum >= "0" ThenIf LeftbombNum >= "0" And LeftbombNum <= "9" ThenPicboxNum(6).PaintPicture picTime(Val(LeftbombNum)), 0, 0, 13, 26PicboxNum(5).PaintPicture picTime(Val(0)), 0, 0, 13, 26PicboxNum(4).PaintPicture picTime(Val(0)), 0, 0, 13, 26ElsePicboxNum(6).PaintPicture picTime(Val(LeftbombNum Mod 10)), 0, 0, 13, 26PicboxNum(5).PaintPicture picTime(Val(LeftbombNum \ 10)), 0, 0, 13, 26PicboxNum(4).PaintPicture picTime(Val(0)), 0, 0, 13, 26End IfElseIf LeftbombNum >= "-9" And LeftbombNum <= "-1" ThenPicboxNum(6).PaintPicture picTime(-Val(Text1.Text)), 0, 0, 13, 26PicboxNum(5).PaintPicture picTime(Val(0)), 0, 0, 13, 26PicboxNum(4).PaintPicture picTime(Val(11)), 0, 0, 13, 26ElseIf LeftbombNum >= "-99" And LeftbombNum <= "-10" ThenPicboxNum(6).PaintPicture picTime(-Val(Text1.Text) Mod 10), 0, 0, 13, 26PicboxNum(5).PaintPicture picTime(-Val(Text1.Text \ 10)), 0, 0, 13, 26PicboxNum(4).PaintPicture picTime(Val(11)), 0, 0, 13, 26End IfEnd SubfrmCustomOption ExplicitPrivate Sub cmdCancle_Click()Unload MeEnd SubPrivate Sub cmdOK_Click()frmMain.mnuBegin.Checked = False '属性为True时,菜单标题前显示复选标记,False则不显示frmMain.mnuMiddle.Checked = FalsefrmMain.mnuExpert.Checked = FalsefrmMain.mnuCust.Checked = TrueX = Val(txtCol.Text) '把含有数值信息的字符串转换为数值Y = Val(txtRow.Text)Num = Val(txtNum.Text)Call frmMain.Start ‘开始游戏Unload MeEnd SubPrivate Sub Form_Load()txtRow.Text = 20 ‘自动加载初始值txtCol.Text = 20txtNum.Text = 20End SubfrmAboutPrivate Sub cmdOK_Click()Unload MeEnd SubfrmRecordPrivate Sub cmdClose_Click()Unload MeEnd SubfrmCheerPrivate Sub Command1_Click()Unload MeEnd SubfrmWinPrivate Sub cmdOK_Click()Unload MeCall frmMain.StartEnd SubfrmMessage1Private Sub cmdCancle_Click()Unload MeEnd SubPrivate Sub cmdOK_Click()frmRecord.lblName1.Caption = Text1.Text ‘保存英雄榜信息frmRecord.lblTime1.Caption = iTimeUnload MeEnd SubfrmMessage2Private Sub cmdCancle_Click()Unload MeEnd SubPrivate Sub cmdOK_Click()frmRecord.lblName2.Caption = Text1.Text ‘保存英雄榜信息frmRecord.lblTime2.Caption = iTimeUnload MeEnd SubfrmMessage3Private Sub cmdCancle_Click()Unload MeEnd SubPrivate Sub cmdOK_Click()frmRecord.lblName3.Caption = Text1.Text ‘保存英雄榜信息frmRecord.lblTime3.Caption = iTimeUnload MeEnd Sub标准模块Public X As Integer, Y As Integer, Num As Integer 'x为横宽,y为竖长,num为雷数Public xx As Integer, yy As Integer 'x1,y1为布雷的位置坐标。
Android扫雷游戏源码分析
第1章游戏源码1.1 MinesweeperGamepackage com.VertexVerveInc.Games;import java.util.Random;import android.app.Activity;import android.graphics.Typeface;import android.os.Bundle;import android.os.Handler;import android.view.Gravity;import android.view.View;import android.view.View.OnClickListener;import android.view.View.OnLongClickListener;import android.widget.ImageButton;import android.widget.ImageView;import android.widget.LinearLayout;import youtParams;import android.widget.TableLayout;import android.widget.TableRow;import android.widget.TextView;import android.widget.Toast;public class MinesweeperGame extends Activity{private TextView txtMineCount;private TextView txtTimer;private ImageButton btnSmile;private TableLayout mineField; // table layout to add mines toprivate Block blocks[][]; // blocks for mine fieldprivate int blockDimension = 24; // width of each blockprivate int blockPadding = 2; // padding between blocksprivate int numberOfRowsInMineField = 9;private int numberOfColumnsInMineField = 9;private int totalNumberOfMines = 10;// timer to keep track of time elapsedprivate Handler timer = new Handler();private int secondsPassed = 0;private boolean isTimerStarted; // check if timer already started or not private boolean areMinesSet; // check if mines are planted in blocks private boolean isGameOver;private int minesToFind; // number of mines yet to be discovered@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(yout.main);txtMineCount = (TextView) findViewById(R.id.MineCount);txtTimer = (TextView) findViewById(R.id.Timer);// set font style for timer and mine count to LCD styleTypeface lcdFont = Typeface.createFromAsset(getAssets(),"fonts/lcd2mono.ttf");txtMineCount.setTypeface(lcdFont);txtTimer.setTypeface(lcdFont);btnSmile = (ImageButton) findViewById(R.id.Smiley);btnSmile.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View view){endExistingGame();startNewGame();}});mineField = (TableLayout)findViewById(R.id.MineField);showDialog("Click smiley to start New Game", 2000, true, false);}private void startNewGame(){// plant mines and do rest of the calculationscreateMineField();// display all blocks in UIshowMineField();minesToFind = totalNumberOfMines;isGameOver = false;secondsPassed = 0;}private void showMineField(){// remember we will not show 0th and last Row and Columns// they are used for calculation purposes onlyfor (int row = 1; row < numberOfRowsInMineField + 1; row++){TableRow tableRow = new TableRow(this);tableRow.setLayoutParams(new LayoutParams((blockDimension + 2 * blockPadding)* numberOfColumnsInMineField, blockDimension + 2 * blockPadding));for (int column = 1; column < numberOfColumnsInMineField + 1; column++){blocks[row][column].setLayoutParams(new LayoutParams(blockDimension + 2 * blockPadding,blockDimension + 2 * blockPadding));blocks[row][column].setPadding(blockPadding, blockPadding, blockPadding, blockPadding);tableRow.addView(blocks[row][column]);}mineField.addView(tableRow,new youtParams((blockDimension + 2 * blockPadding) * numberOfColumnsInMineField, blockDimension + 2 * blockPadding));}}private void endExistingGame(){stopTimer(); // stop if timer is runningtxtTimer.setText("000"); // revert all texttxtMineCount.setText("000"); // revert mines countbtnSmile.setBackgroundResource(R.drawable.smile);// remove all rows from mineField TableLayoutmineField.removeAllViews();// set all variables to support end of gameisTimerStarted = false;areMinesSet = false;isGameOver = false;minesToFind = 0;}private void createMineField(){// we take one row extra row for each side// overall two extra rows and two extra columns// first and last row/column are used for calculations purposes only// x|xxxxxxxxxxxxxx|x// ------------------// x| |x// x| |x// ------------------// x|xxxxxxxxxxxxxx|x// the row and columns marked as x are just used to keep counts of near by mines blocks = new Block[numberOfRowsInMineField + 2][numberOfColumnsInMineField + 2];for (int row = 0; row < numberOfRowsInMineField + 2; row++)for (int column = 0; column < numberOfColumnsInMineField + 2; column++) {blocks[row][column] = new Block(this);blocks[row][column].setDefaults();// pass current row and column number as final int's to event listeners // this way we can ensure that each event listener is associated to// particular instance of block onlyfinal int currentRow = row;final int currentColumn = column;// add Click Listener// this is treated as Left Mouse clickblocks[row][column].setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View view){// start timer on first clickif (!isTimerStarted){startTimer();isTimerStarted = true;}// set mines on first clickif (!areMinesSet){areMinesSet = true;setMines(currentRow, currentColumn);}// this is not first click// check if current block is flagged// if flagged the don't do anything// as that operation is handled by LongClick// if block is not flagged then uncover nearby blocks// till we get numbered minesif (!blocks[currentRow][currentColumn].isFlagged()){// open nearby blocks till we get numbered blocksrippleUncover(currentRow, currentColumn);// did we clicked a mineif (blocks[currentRow][currentColumn].hasMine()){// Oops, game overfinishGame(currentRow,currentColumn);// check if we win the gameif (checkGameWin()){// mark game as winwinGame();}}}});// add Long Click listener// this is treated as right mouse click listenerblocks[row][column].setOnLongClickListener(new OnLongClickListener(){public boolean onLongClick(View view){// simulate a left-right (middle) click// if it is a long click on an opened mine then// open all surrounding blocksif (!blocks[currentRow][currentColumn].isCovered() && (blocks[currentRow][currentColumn].getNumberOfMinesInSorrounding() > 0) && !isGameOver){int nearbyFlaggedBlocks = 0;for (int previousRow = -1; previousRow < 2; previousRow++){for (int previousColumn = -1; previousColumn < 2; previousColumn++){if (blocks[currentRow + previousRow][currentColumn + previousColumn].isFlagged()){nearbyFlaggedBlocks++;}}}// if flagged block count is equal to nearby mine count// then open nearby blocksif (nearbyFlaggedBlocks == blocks[currentRow][currentColumn].getNumberOfMinesInSorrounding()) {for (int previousRow = -1; previousRow < 2; previousRow++){for (int previousColumn = -1; previousColumn < 2; previousColumn++){// don't open flagged blocksif (!blocks[currentRow + previousRow][currentColumn + previousColumn].isFlagged()){// open blocks till we get numbered blockrippleUncover(currentRow + previousRow, currentColumn + previousColumn);// did we clicked a mineif (blocks[currentRow + previousRow][currentColumn + previousColumn].hasMine()){// oops game overfinishGame(currentRow + previousRow, currentColumn + previousColumn);}// did we win the gameif (checkGameWin()){// mark game as winwinGame();}}}}}// as we no longer want to judge this gesture so return// not returning from here will actually trigger other action// which can be marking as a flag or question mark or blankreturn true;}// if clicked block is enabled, clickable or flaggedif (blocks[currentRow][currentColumn].isClickable() &&(blocks[currentRow][currentColumn].isEnabled() || blocks[currentRow][currentColumn].isFlagged())){// for long clicks set:// 1. empty blocks to flagged// 2. flagged to question mark// 3. question mark to blank// case 1. set blank block to flaggedif (!blocks[currentRow][currentColumn].isFlagged() && !blocks[currentRow][currentColumn].isQuestionMarked()){blocks[currentRow][currentColumn].setBlockAsDisabled(false);blocks[currentRow][currentColumn].setFlagIcon(true);blocks[currentRow][currentColumn].setFlagged(true);minesToFind--; //reduce mine countupdateMineCountDisplay();}// case 2. set flagged to question markelse if (!blocks[currentRow][currentColumn].isQuestionMarked()){blocks[currentRow][currentColumn].setBlockAsDisabled(true);blocks[currentRow][currentColumn].setQuestionMarkIcon(true);blocks[currentRow][currentColumn].setFlagged(false);blocks[currentRow][currentColumn].setQuestionMarked(true); minesToFind++; // increase mine countupdateMineCountDisplay();}// case 3. change to blank squareelse{blocks[currentRow][currentColumn].setBlockAsDisabled(true);blocks[currentRow][currentColumn].clearAllIcons();blocks[currentRow][currentColumn].setQuestionMarked(false);// if it is flagged then increment mine countif (blocks[currentRow][currentColumn].isFlagged()){minesToFind++; // increase mine countupdateMineCountDisplay();}// remove flagged statusblocks[currentRow][currentColumn].setFlagged(false);}updateMineCountDisplay(); // update mine display}return true;}});}}}private boolean checkGameWin(){for (int row = 1; row < numberOfRowsInMineField + 1; row++){for (int column = 1; column < numberOfColumnsInMineField + 1; column++) {if (!blocks[row][column].hasMine() && blocks[row][column].isCovered()) {return false;}}}return true;}private void updateMineCountDisplay(){if (minesToFind < 0){txtMineCount.setText(Integer.toString(minesToFind));}else if (minesToFind < 10){txtMineCount.setText("00" + Integer.toString(minesToFind));}else if (minesToFind < 100){txtMineCount.setText("0" + Integer.toString(minesToFind));}else{txtMineCount.setText(Integer.toString(minesToFind));}}private void winGame(){stopTimer();isTimerStarted = false;isGameOver = true;minesToFind = 0; //set mine count to 0//set icon to cool dudebtnSmile.setBackgroundResource(R.drawable.cool); updateMineCountDisplay(); // update mine count// disable all buttons// set flagged all un-flagged blocksfor (int row = 1; row < numberOfRowsInMineField + 1; row++){for (int column = 1; column < numberOfColumnsInMineField + 1; column++) {blocks[row][column].setClickable(false);if (blocks[row][column].hasMine()){blocks[row][column].setBlockAsDisabled(false);blocks[row][column].setFlagIcon(true);}}}// show messageshowDialog("You won in " + Integer.toString(secondsPassed) + " seconds!", 1000, false, true);}private void finishGame(int currentRow, int currentColumn){isGameOver = true; // mark game as overstopTimer(); // stop timerisTimerStarted = false;btnSmile.setBackgroundResource(R.drawable.sad);// show all mines// disable all blocksfor (int row = 1; row < numberOfRowsInMineField + 1; row++){for (int column = 1; column < numberOfColumnsInMineField + 1; column++){// disable blockblocks[row][column].setBlockAsDisabled(false);// block has mine and is not flaggedif (blocks[row][column].hasMine() && !blocks[row][column].isFlagged()){// set mine iconblocks[row][column].setMineIcon(false);}// block is flagged and doesn't not have mineif (!blocks[row][column].hasMine() && blocks[row][column].isFlagged()){// set flag iconblocks[row][column].setFlagIcon(false);}// block is flaggedif (blocks[row][column].isFlagged()){// disable the blockblocks[row][column].setClickable(false);}}}// trigger mineblocks[currentRow][currentColumn].triggerMine();// show messageshowDialog("You tried for " + Integer.toString(secondsPassed) + " seconds!", 1000, false, false);}private void setMines(int currentRow, int currentColumn){// set mines excluding the location where user clickedRandom rand = new Random();int mineRow, mineColumn;for (int row = 0; row < totalNumberOfMines; row++){mineRow = rand.nextInt(numberOfColumnsInMineField);mineColumn = rand.nextInt(numberOfRowsInMineField);if ((mineRow + 1 != currentColumn) || (mineColumn + 1 != currentRow)){if (blocks[mineColumn + 1][mineRow + 1].hasMine()){row--; // mine is already there, don't repeat for same block}// plant mine at this locationblocks[mineColumn + 1][mineRow + 1].plantMine();}// exclude the user clicked locationelse{row--;}}int nearByMineCount;// count number of mines in surrounding blocksfor (int row = 0; row < numberOfRowsInMineField + 2; row++){for (int column = 0; column < numberOfColumnsInMineField + 2; column++){// for each block find nearby mine countnearByMineCount = 0;if ((row != 0) && (row != (numberOfRowsInMineField + 1)) && (column != 0) && (column != (numberOfColumnsInMineField + 1))){// check in all nearby blocksfor (int previousRow = -1; previousRow < 2; previousRow++){for (int previousColumn = -1; previousColumn < 2; previousColumn++){if (blocks[row + previousRow][column + previousColumn].hasMine()){// a mine was found so increment the counternearByMineCount++;}}}blocks[row][column].setNumberOfMinesInSurrounding(nearByMineCount);}// for side rows (0th and last row/column)// set count as 9 and mark it as openedelse{blocks[row][column].setNumberOfMinesInSurrounding(9);blocks[row][column].OpenBlock();}}}}private void rippleUncover(int rowClicked, int columnClicked){// don't open flagged or mined rowsif (blocks[rowClicked][columnClicked].hasMine() || blocks[rowClicked][columnClicked].isFlagged()){return;}// open clicked blockblocks[rowClicked][columnClicked].OpenBlock();// if clicked block have nearby mines then don't open furtherif (blocks[rowClicked][columnClicked].getNumberOfMinesInSorrounding() != 0 ) {return;}// open next 3 rows and 3 columns recursivelyfor (int row = 0; row < 3; row++){for (int column = 0; column < 3; column++){// check all the above checked conditions// if met then open subsequent blocksif (blocks[rowClicked + row - 1][columnClicked + column - 1].isCovered() && (rowClicked + row - 1 > 0) && (columnClicked + column - 1 > 0)&& (rowClicked + row - 1 < numberOfRowsInMineField + 1) && (columnClicked +column - 1 < numberOfColumnsInMineField + 1)){rippleUncover(rowClicked + row - 1, columnClicked + column - 1 );}}}return;}public void startTimer(){if (secondsPassed == 0){timer.removeCallbacks(updateTimeElasped);// tell timer to run call back after 1 secondtimer.postDelayed(updateTimeElasped, 1000);}}public void stopTimer(){// disable call backstimer.removeCallbacks(updateTimeElasped);}// timer call back when timer is tickedprivate Runnable updateTimeElasped = new Runnable(){public void run(){long currentMilliseconds = System.currentTimeMillis();++secondsPassed;if (secondsPassed < 10){txtTimer.setText("00" + Integer.toString(secondsPassed));}else if (secondsPassed < 100){txtTimer.setText("0" + Integer.toString(secondsPassed));}else{txtTimer.setText(Integer.toString(secondsPassed));}// add notificationtimer.postAtTime(this, currentMilliseconds);// notify to call back after 1 seconds// basically to remain in the timer looptimer.postDelayed(updateTimeElasped, 1000);}};private void showDialog(String message, int milliseconds, boolean useSmileImage, boolean useCoolImage){// show messageToast dialog = Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG);dialog.setGravity(Gravity.CENTER, 0, 0);LinearLayout dialogView = (LinearLayout) dialog.getView();ImageView coolImage = new ImageView(getApplicationContext());if (useSmileImage){coolImage.setImageResource(R.drawable.smile);}else if (useCoolImage){coolImage.setImageResource(R.drawable.cool);}else{coolImage.setImageResource(R.drawable.sad);}dialogView.addView(coolImage, 0);dialog.setDuration(milliseconds);dialog.show();}}1.2 Blockpackage com.VertexVerveInc.Games;import android.content.Context;import android.graphics.Color;import android.graphics.Typeface;import android.util.AttributeSet;import android.widget.Button;public class Block extends Button{private boolean isCovered; // is block covered yetprivate boolean isMined; // does the block has a mine underneathprivate boolean isFlagged; // is block flagged as a potential mineprivate boolean isQuestionMarked; // is block question markedprivate boolean isClickable; // can block accept click eventsprivate int numberOfMinesInSurrounding; // number of mines in nearby blocks public Block(Context context){super(context);}public Block(Context context, AttributeSet attrs){super(context, attrs);}public Block(Context context, AttributeSet attrs, int defStyle){super(context, attrs, defStyle);}// set default properties for the blockpublic void setDefaults(){isCovered = true;isMined = false;isFlagged = false;isQuestionMarked = false;isClickable = true;numberOfMinesInSurrounding = 0;this.setBackgroundResource(R.drawable.square_blue); setBoldFont();}// mark the block as disabled/opened// update the number of nearby minespublic void setNumberOfSurroundingMines(int number) {this.setBackgroundResource(R.drawable.square_grey); updateNumber(number);}// set mine icon for block// set block as disabled/opened if false is passed public void setMineIcon(boolean enabled){this.setText("M");if (!enabled){this.setBackgroundResource(R.drawable.square_grey); this.setTextColor(Color.RED);}else{this.setTextColor(Color.BLACK);}}// set mine as flagged// set block as disabled/opened if false is passed public void setFlagIcon(boolean enabled){this.setText("F");if (!enabled){this.setBackgroundResource(R.drawable.square_grey); this.setTextColor(Color.RED);}else{this.setTextColor(Color.BLACK);}}// set mine as question mark// set block as disabled/opened if false is passed public void setQuestionMarkIcon(boolean enabled) {this.setText("?");if (!enabled){this.setBackgroundResource(R.drawable.square_grey); this.setTextColor(Color.RED);}else{this.setTextColor(Color.BLACK);}}// set block as disabled/opened if false is passed // else enable/close itpublic void setBlockAsDisabled(boolean enabled) {if (!enabled){this.setBackgroundResource(R.drawable.square_grey); }else{this.setBackgroundResource(R.drawable.square_blue); }}// clear all icons/textpublic void clearAllIcons(){this.setText("");}// set font as boldprivate void setBoldFont(){this.setTypeface(null, Typeface.BOLD);}// uncover this blockpublic void OpenBlock(){// cannot uncover a mine which is not coveredif (!isCovered)return;setBlockAsDisabled(false);isCovered = false;// check if it has mineif (hasMine()){setMineIcon(false);}// update with the nearby mine countelse{setNumberOfSurroundingMines(numberOfMinesInSurrounding); }}// set text as nearby mine countpublic void updateNumber(int text){if (text != 0){this.setText(Integer.toString(text));// select different color for each number// we have already skipped 0 mine countswitch (text){case 1:this.setTextColor(Color.BLUE);break;case 2:this.setTextColor(Color.rgb(0, 100, 0));break;case 3:this.setTextColor(Color.RED);break;case 4:this.setTextColor(Color.rgb(85, 26, 139));break;case 5:this.setTextColor(Color.rgb(139, 28, 98));break;case 6:this.setTextColor(Color.rgb(238, 173, 14));break;case 7:this.setTextColor(Color.rgb(47, 79, 79));break;case 8:this.setTextColor(Color.rgb(71, 71, 71));break;case 9:this.setTextColor(Color.rgb(205, 205, 0));break;}}}// set block as a mine underneathpublic void plantMine(){isMined = true;}// mine was opened// change the block icon and colorpublic void triggerMine(){setMineIcon(true);this.setTextColor(Color.RED);}// is block still coveredpublic boolean isCovered(){return isCovered;}// does the block have any mine underneathpublic boolean hasMine(){return isMined;}// set number of nearby minespublic void setNumberOfMinesInSurrounding(int number) {numberOfMinesInSurrounding = number;}// get number of nearby minespublic int getNumberOfMinesInSorrounding(){return numberOfMinesInSurrounding;}// is block marked as flaggedpublic boolean isFlagged(){return isFlagged;}// mark block as flaggedpublic void setFlagged(boolean flagged){isFlagged = flagged;}// is block marked as a question markpublic boolean isQuestionMarked(){return isQuestionMarked;}// set question mark for the blockpublic void setQuestionMarked(boolean questionMarked){isQuestionMarked = questionMarked;}// can block receive click eventpublic boolean isClickable(){return isClickable;}// disable block for receive click eventspublic void setClickable(boolean clickable){isClickable = clickable;}}第2章源码详细分析2.1 基本变量设置private TextView txtMineCount;//剩余地雷数private TextView txtTimer;//计时private ImageButton btnSmile;//新游戏按钮private TableLayout mineField; //表的布局添加地雷private Block blocks[][]; //所有的块private int blockDimension = 24; //每块的宽度private int blockPadding = 2; //块之间填充private int numberOfRowsInMineField = 9;//雷区为9行private int numberOfColumnsInMineField = 9;//雷区为9列private int totalNumberOfMines = 10;//总共有10个雷//定时器的运行时间保持跟踪private Handler timer = new Handler();private int secondsPassed = 0;private boolean isTimerStarted; //检查是否已经开始或不定时private boolean areMinesSet; //检查是否已经设置地雷private boolean isGameOver;//检查是否游戏结束private int minesToFind; //有待发现的地雷数量2.2 游戏初始化游戏的初始化函数中,要设置整个界面的背景图片和游戏开始按钮的图片,还有设置一个提示信息(当点击其它地方时弹出)。
扫雷游戏源代码报告书
课程设计报告书题目:扫雷游戏学院计算机科学与工程专业网络工程学生姓名马一宁学生学号 201536551381指导教师李家春课程编号SFA1451010369667课程学分3.5起始日期 2015.8扫雷游戏一、问题描述1.1问题描述设计并编写一个扫雷游戏,给定地雷分布区大小和地雷数,尽快找出所有不是地雷的方格,不许踩到地雷。
如踩到含地雷的方格,游戏失败;正确标记出所有地雷的方格,游戏胜利结束。
1.2开发平台开发环境:Windows10 64位专业版开发软件:Visual Studio 2015企业版二、系统设计2.1主要全局变量及数据结构2.1.1 charvis[MAX_N][MAX_N];用于记录该坐标点的状态,辅助控制游戏,初始化值为‘0’。
若用户访问打开该坐标或在递归中被打开则标记为‘1’,下次访问时将不会对该坐标再次进行处理。
若用户将该坐标标记为地雷,则若标记错误则为‘2’,若正确则标记则为‘3’。
2.1.2char check[MAX_N][MAX_N];用于辅助显示已标记数目功能,初始化为‘0’。
其值为‘1’表示用户将该坐标标记为地雷(无论是否正确标记),在递归打开坐标时,保证count_n对于同一坐标只在第一次自减。
2.1.3intcount_n;用于记录已标记数目,初始化为0。
每当用户新标记时自增1,配合check 数组在已标记的坐标被打开时自减1。
2.2主要局部变量及数据结构2.2.1set<int>st;使用C++STL容器set保证产生的地雷没有重复,用于存放随机产生的地雷坐标信息。
2.2.2 char *a = new char[m*n];本游戏中最核心的数组,在得知雷区大小后动态产生一个一维数组表示雷区分布,配合<set>容器布置地雷,初始化为‘0’。
用‘*’表示地雷,‘.’表示空地无雷区,并在雷区旁边标记数字表示九宫格内地雷个数‘1’-‘8’以供显示。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
}
}
私人无效endExistingGame()
{
stopTimer(); / /停止,如果计时器正在运行
{
/ /我们为每方一列额外的行
/ /整体两个额外的两个额外的行和列
/ /第一个和最后一个行/列用于计算仅
/ / x |的xxxxxxxxxxxxxx | x
/ / ------------------
/ / X的| | x
/ / X的| | x
/ / ------------------
块[行] [列] setPadding(blockPadding,blockPadding,blockPadding,blockPadding)。
tableRow.addView(块[行] [列]);
}
mineField.addView(TableRow的,新的youtParams(
txtTimer.setText(“000”); / /恢复所有文本
txtMineCount.setText(“000”); / /恢复矿山数量
btnSmile.setBackgroundResource(R.drawable.smile);
/ /删除所有行雷区TableL是处理LongClick
/ /如果块没有再发现标记附近区
/ /直到我们得到编号地雷
如果(!块[currentRow] [currentColumn]。isFlagged())
{
txtMineCount =(TextView的)findViewById(R.id.MineCount);
txtTimer =(TextView的)findViewById(R.id.Timer);
/ /设置定时器和矿山数液晶风格的字体样式
字体lcdFont = Typeface.createFromAsset(getAssets()
私人诠释blockDimension = 24; / /每块的宽度
私人诠释blockPadding = 2; / /块之间填充
私人诠释numberOfRowsInMineField = 9;
私人诠释numberOfColumnsInMineField = 9;
私人诠释totalNumberOfMines = 10;
/ / x |的xxxxxxxxxxxxxx | x
/ /行和列标记为x的只是用来保持近数地雷
块=新座[numberOfRowsInMineField + 2] [numberOfColumnsInMineField + 2];
为(int行= 0;行<numberOfRowsInMineField + 2;行+ +)
{
新的TableRow的TableRow的TableRow =(本);
tableRow.setLayoutParams(新的LayoutParams((blockDimension + 2 * blockPadding)* numberOfColumnsInMineField,blockDimension + 2 * blockPadding));
btnSmile.setOnClickListener(新OnClickListener()
{
@覆盖
公共无效的onClick(View视图)
{
endExistingGame();
startNewGame();
}
});
雷区=(TableLayout)findViewById(R.id.MineField);
/ /在第一次单击设置地雷
如果(!areMinesSet)
{
areMinesSet =真;
setMines(currentRow,currentColumn);
}
/ /这不是第一次点击
/ /检查当前块被标记
“fonts/lcd2mono.ttf”);
txtMineCount.setTypeface(lcdFont);
txtTimer.setTypeface(lcdFont);
btnSmile =(ImageButton)findViewById(R.id.Smiley);
私人诠释minesToFind / /的地雷数量尚未被发现
@覆盖
公共无效的onCreate(捆绑savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(yout.main);
winGame();
}
}
}
});
/ /添加监听长摁
/ /这被视为右击鼠标监听器
块[行] [列]。setOnLongClickListener(新OnLongClickListener()
{
{
如果(块[currentRow + previousRow] [currentColumn + previousColumn]。isFlagged())
{
nearbyFlaggedBlocks + +;
}
{
为(int列= 0;“列<numberOfColumnsInMineField + 2;柱+ +)
{
块[行] [列] =新的块(这个);
块[行] [列] setDefaults()。
/ /把当前行和列编号为最终诠释的给事件侦听器
/ /这样我们可以确保每一个事件侦听器关联
{
诠释nearbyFlaggedBlocks = 0;
为(int previousRow = -1; previousRow <2; previousRow + +)
{
为(int previousColumn = -1; previousColumn <2; previousColumn + +)
/ /定时器的运行时间保持跟踪
私人处理程序定时器=新的处理程序();
私人诠释secondsPassed = 0;
私人布尔isTimerStarted; / /检查是否已经开始或不定时
私人布尔areMinesSet; / /检查是否以块种植地雷
私人布尔isGameOver;
isGameOver = 0;
secondsPassed = 0;
}
私人无效showMineField()
{
/ /请记住,我们不会显示第0个和最后一个行和列
/ /他们是仅用于计算
为(int行= 1;行<numberOfRowsInMineField + 1;行+ +)
{
/ /糟糕,游戏结束
finishGame(currentRow,currentColumn);
}
/ /检查,如果我们赢了这场比赛
如果(checkGameWin())
{
/ /为赢得比赛大关
Android的扫雷游戏源代码:
公共类MinesweeperGame延伸活动
{
私人TextView的txtMineCount;
私人TextView的txtTimer;
私人ImageButton btnSmile;
私人TableLayout雷区; / /表的布局添加地雷
私人块多块[][]; / /块矿田
@覆盖
公共无效的onClick(View视图)
{
/ /在第一次单击启动定时器
如果(!isTimerStarted)
{
startTimer();
isTimerStarted =真;
}
/ /打开,直到我们得到的块数块附近
rippleUncover(currentRow,currentColumn);
/ /我们点击一??个地雷
如果(块[currentRow] [currentColumn]。hasMine())
公共布尔onLongClick(View视图)
{
/ /模拟左右(中)点击
/ /如果它是对一个开了我那么长摁
/ /打开所有周边街区
如果(!块[currentRow] [currentColumn]。isCovered()&&(块[currentRow] [currentColumn]。getNumberOfMinesInSorrounding()“0)&&!isGameOver)
ShowDialog的(“点击笑脸,开始新游戏”,2000年,真,假);
}
私人无效startNewGame()
{
/ /埋设地雷,并执行其他计算
createMineField();
/ /显示在用户界面的所有块
showMineField();
minesToFind = totalNumberOfMines;
{
为(int previousRow = -1; previousRow <2; previousRow + +)
{
为(int previousColumn = -1; previousColumn <2; previousColumn + +)