扫雷代码

合集下载

扫雷游戏部分代码

扫雷游戏部分代码

//设置状态#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);}}}}}}。

扫雷游戏代码

扫雷游戏代码

/*block.h*/#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"block.h"#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/normal.png")); }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/mine.png"));elsesetPixmap(QPixmap(":/images/mine_"+QString("%1").arg(numb er_)+".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/mine.png"));update();emit turn_over(true);}else{setPixmap(QPixmap(":/images/mine_"+QString("%1").arg(numb er_)+".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/flag.png"));}else{mark_flag_=false;setPixmap(QPixmap(":/images/normal.png"));}update();}}QLabel::mousePressEvent(event);}#ifndef BLOCK_AREA_H_#define BLOCK_AREA_H_#include"block.h"#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,int mine_number,intinit_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;//璁$畻浠,y涓轰腑蹇幂殑涔濆镙煎唴镄勯浄鏁void try_to_turn_over_more_blocks(int x,int y);private:QGridLayout*mainLayout;int row_;int column_;int total_block_number_;int total_mine_number_;int turn_over_block_number_;bool game_over_flag_;};#endif/*block_area.h*/#include"block_area.h"#include<algorithm>#include<QEvent>#include<QGridLayout>#include<QLayout>#include<QMouseEvent>#include<QObject>#include<QQueue>#include<QTime>#include<QWidget>/*雷的随机布置*/ptrdiff_t random(ptrdiff_t i){return qrand()%i;}ptrdiff_t(*p_random)(ptrdiff_t)=random;BlockArea::BlockArea(int row,int column,int mine_number,QWidget* parent):QWidget(parent){set_block_area(row,column,mine_number,true);}void BlockArea::set_block_area(int row,int column,int mine_number,int init_flag){if(!init_flag){for(int i=0;i<row_;i++)for(int j=0;j<column_;j++)deletestatic_cast<Block*>(mainLayout->itemAtPosition(i,j)->widget());delete mainLayout;}row_=row;column_=column;total_block_number_=row_*column_;total_mine_number_=mine_number;turn_over_block_number_=0;game_over_flag_=false;bool mine_flag[total_block_number_];for(int i=0;i<total_mine_number_;i++)mine_flag[i]=true;for(int i=total_mine_number_;i<total_block_number_;i++)mine_flag[i]=false;QTime time;time=QTime::currentTime();qsrand(time.msec()+time.second()*1000);std::random_shuffle(mine_flag,mine_flag+total_block_number_,p _random);mainLayout=new QGridLayout(this);for(int i=0;i<row_;i++)for(int j=0;j<column_;j++)mainLayout->addWidget(newBlock(mine_flag[i*column_+j]),i,j);for(int i=0;i<row_;i++){for(int j=0;j<column_;j++){Block*current_block=static_cast<Block*>(mainLayout->itemAtPosition(i,j)->wi dget());current_block->set_number(calculate_mines(i,j));connect(current_block,SIGNAL(turn_over(bool)),this,SLOT(slot_tu rn_over(bool)));current_block->installEventFilter(this);}}}bool BlockArea::eventFilter(QObject*watched,QEvent*event){if(game_over_flag_)if(event->type()==QEvent::MouseButtonPress)return true;return QWidget::eventFilter(watched,event);}void BlockArea::slot_turn_over(bool is_mine){if(is_mine){game_over_flag_=true;emit game_over(false);}else{++turn_over_block_number_;if(turn_over_block_number_==total_block_number_-total_mine_ number_){game_over_flag_=true;emit game_over(true);}else{for(int i=0;i<row_;i++)for(int j=0;j<column_;j++)if(sender()==static_cast<Block*>(mainLayout->itemAtPosition(i, j)->widget()))try_to_turn_over_more_blocks(i,j);}}}int BlockArea::calculate_mines(int x,int y)const{int number=0;for(int i=0;i<3;i++)for(int j=0;j<3;j++)if((x-1+i>=0)&&(x-1+i<row_)&&(y-1+j>=0) &&(y-1+j<column_))if(static_cast<Block*>(mainLayout->itemAtPosition(x-1+i,y-1+j) ->widget())->is_mine())++number;return number;}void BlockArea::try_to_turn_over_more_blocks(int x,int y){QQueue<QPair<int,int>>queue;QPair<int,int>pair;queue.enqueue(qMakePair(x,y));while(!queue.isEmpty()){pair=queue.head();queue.dequeue();if(calculate_mines(pair.first,pair.second)==0){for(int i=0;i<3;i++){for(int j=0;j<3;j++){if((pair.first-1+i>=0)&& (pair.first-1+i<row_)&&(pair.second-1+j>=0)&&(pair.second-1+j<column_)){if(!static_cast<Block*>(mainLayout->itemAtPosition(pair.first-1 +i,pair.second-1+j)->widget())->is_turn_over()){static_cast<Block*>(mainLayout->itemAtPosition(pair.first-1+i,p air.second-1+j)->widget())->turn_over();++turn_over_block_number_;queue.enqueue(qMakePair(pair.first-1+i,pair.second-1+j));}}}}}}if(turn_over_block_number_==total_block_number_-total_mine_ number_){game_over_flag_=true;emit game_over(true);}}#ifndef MAIN_WINDOW_H_#define MAIN_WINDOW_H_#include"block_area.h"#include<QMainWindow>#include<QTime>#include<QTimer>class QAction;class QActionGroup;class QCloseEvent;class QMenu;class QToolBar;class QWidget;class MainWindow:public QMainWindow{Q_OBJECTpublic:MainWindow(QWidget*parent=0); protected:void closeEvent(QCloseEvent*event);private slots:void slot_new_game();void slot_rank();void slot_show_game_toolBar(bool show);void slot_show_statusBar(bool show);void slot_standard(QAction*standard_action);void slot_about_game();void slot_game_over(bool is_win);void slot_timer();private:void read_settings();void write_settings();void create_actions();void create_menus();void create_game_toolBar();void create_statusBar();private:BlockArea*area_;int row_;int column_;int mine_number_;int easy_record_time_;int middle_record_time_;int hard_record_time_;QString easy_record_name_;QString middle_record_name_; QString hard_record_name_;int current_standard_;QMenu*game_menu;QMenu*setting_menu;QMenu*help_menu;QToolBar*game_toolBar;QAction*new_game_action; QAction*rank_action;QAction*exit_action;QAction*show_game_toolBar_action; QAction*show_statusBar_action; QAction*easy_standard_action; QAction*middle_standard_action; QAction*hard_standard_action; QAction*custom_standard_action; QActionGroup*standard_actionGroup; QAction*about_game_action;QAction*about_qt_action;QLabel*time_label;QTime time;QTimer timer;};#endif#include"main_window.h"#include<QAction>#include<QActionGroup>#include<QApplication>#include<QDialog>#include<QDialogButtonBox>#include<QHBoxLayout>#include<QIcon>#include<QInputDialog>#include<QLayout>#include<QMainWindow>#include<QMenu>#include<QMenuBar>#include<QMessageBox>#include<QPushButton>#include<QSettings>#include<QSpinBox>#include<QStatusBar>#include<QToolBar>#include<QVBoxLayout>#include<QWidget>/*关于游戏介绍的信息*/const QString g_software_name="Mine Sweeper";const QString g_software_version="1.2";const QString g_software_author="CHANGHUIZHEN";/*关于排行榜的信息*/const int g_no_record_time=9999;const QString g_no_record_name="";MainWindow::MainWindow(QWidget*parent):QMainWindow(parent){area_=new BlockArea(9,9,10);//一般设置connect(area_,SIGNAL(game_over(bool)),this,SLOT(slot_game_o ver(bool)));setCentralWidget(area_);create_actions();create_menus();create_game_toolBar();create_statusBar();QCoreApplication::setOrganizationName(g_software_author);QCoreApplication::setApplicationName(g_software_name);read_settings();layout()->setSizeConstraint(QLayout::SetFixedSize);setWindowTitle(g_software_name);setWindowIcon(QIcon(":/game.png"));/*等待最长时间,到时间就会提示游戏失败*/timer.start(1000);connect(&timer,SIGNAL(timeout()),this,SLOT(slot_timer()));slot_new_game();}void MainWindow::closeEvent(QCloseEvent*){write_settings();}void MainWindow::slot_new_game(){area_->set_block_area(row_,column_,mine_number_);time_label->setText("0");time.restart();timer.start();}void MainWindow::slot_rank(){QDialog dialog;dialog.setWindowTitle(tr("rank"));QGridLayout*up_layout=new QGridLayout;up_layout->addWidget(new QLabel(tr("Standard")),0,0);up_layout->addWidget(new QLabel(tr("Time")),0,1);up_layout->addWidget(new QLabel(tr("Name")),0,2);up_layout->addWidget(new QLabel(tr("Easy")),1,0);up_layout->addWidget(newQLabel(QString("%1").arg(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(new QLabel(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=new QPushButton(tr("recount"));QPushButton*close_button=new QPushButton(tr("close"));close_button->setDefault(true);connect(recount_button,SIGNAL(clicked()),&dialog,SLOT(accept( )));connect(close_button,SIGNAL(clicked()),&dialog,SLOT(reject()));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(dialog.exec()==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;dialog.setWindowTitle(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(ac cept()));connect(dialog_buttonBox,SIGNAL(rejected()),&dialog,SLOT(reje ct()));QHBoxLayout*bottom_layout=new QHBoxLayout;bottom_layout->addStretch();bottom_layout->addWidget(dialog_buttonBox);QVBoxLayout*main_layout=newQVBoxLayout(&dialog);main_layout->addLayout(up_layout);main_layout->addLayout(bottom_layout);if(dialog.exec()==QDialog::Accepted)if(row_spinBox->value()*column_spinBox->value()>mine_spinBo x->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 mines.if 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 modify.it under the terms of the GNU General Public License as published by the Software Foundation;either version3 of the License,or(at your option)any later version.")+"</p>"+"<p>"+tr("Please see")+"<ahref=/licenses/gpl-3.0.html>/lic enses/gpl-3.0.html</a>"+tr("for an overview of GPLv3 licensing")+"</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);messageBox.exec();}/*游戏的判断,及所给出的提示做出判断*/void MainWindow::slot_game_over(bool is_win){timer.stop();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(!name.isEmpty()){ 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(!name.isEmpty()){ 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(!name.isEmpty()){ 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("You win"));}}else{QMessageBox::information(this,tr("Result"),tr("You lose"));}}/*定时器的设置*/void MainWindow::slot_timer(){time_label->setText(QString("%1").arg(time.elapsed()/1000)); }/*关于菜单栏的设置是否显示游戏工具栏和状态栏*/void MainWindow::read_settings(){QSettings settings;settings.beginGroup("MainWindow");resize(settings.value("size").toSize());move(settings.value("pos").toPoint());boolshow_game_toolBar=settings.value("showGameToolBar").toBool();show_game_toolBar_action->setChecked(show_game_toolBar);slot_show_game_toolBar(show_game_toolBar);bool show_statusBar=settings.value("showStatusBar").toBool();show_statusBar_action->setChecked(show_statusBar);slot_show_statusBar(show_statusBar);settings.endGroup();settings.beginGroup("GameSetting");current_standard_=settings.value("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_=settings.value("row").toInt()==0?9:settings.value("row").to Int();column_=settings.value("column").toInt()==0?9:settings.value("c olumn").toInt();mine_number_=settings.value("mine_number").toInt()==0?10:se ttings.value("mine_number").toInt();settings.endGroup();settings.beginGroup("Rank");easy_record_time_=settings.value("easy_record_time").toInt()== 0?g_no_record_time:settings.value("easy_record_time").toInt();middle_record_time_=settings.value("middle_record_time").toInt ()==0?g_no_record_time:settings.value("middle_record_time").toInt();hard_record_time_=settings.value("hard_record_time").toInt()== 0?g_no_record_time:settings.value("hard_record_time").toInt();easy_record_name_=settings.value("easy_record_name").toStrin g()==""?g_no_record_name:settings.value("easy_record_name").toString ();middle_record_name_=settings.value("middle_record_name").to String()==""?g_no_record_name:settings.value("middle_record_name").t oString();hard_record_name_=settings.value("hard_record_name").toStrin g()==""?g_no_record_name:settings.value("hard_record_name").toString ();settings.endGroup();}void MainWindow::write_settings(){QSettings settings;settings.beginGroup("MainWindow");settings.setValue("size",size());settings.setValue("pos",pos());settings.setValue("showGameToolBar",show_game_toolBar_acti on->isChecked());settings.setValue("showStatusBar",show_statusBar_action->isCh ecked());settings.endGroup();settings.beginGroup("GameSetting");settings.setValue("current_standard",current_standard_);settings.setValue("row",row_);settings.setValue("column",column_);settings.setValue("mine_number",mine_number_);settings.endGroup();settings.beginGroup("Rank");settings.setValue("easy_record_time",easy_record_time_);settings.setValue("middle_record_time",middle_record_time_);settings.setValue("hard_record_time",hard_record_time_);settings.setValue("easy_record_name",easy_record_name_);settings.setValue("middle_record_name",middle_record_name_);settings.setValue("hard_record_name",hard_record_name_);settings.endGroup();}/*菜单栏里图片的显示*/void MainWindow::create_actions(){new_game_action=newQAction(QIcon(":/images/new_game.png"),tr("New Game"),this);new_game_action->setShortcut(QKeySequence::New);connect(new_game_action,SIGNAL(triggered()),this,SLOT(slot_ne w_game()));rank_action=newQAction(QIcon(":/images/rank.png"),tr("Rank"),this);connect(rank_action,SIGNAL(triggered()),this,SLOT(slot_rank()));exit_action=newQAction(QIcon(":/images/exit.png"),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)),this, 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/easy_standard.png"),tr("Easy"),this);easy_standard_action->setCheckable(true);middle_standard_action=newQAction(QIcon(":/images/middle_standard.png"),tr("Middle"),this);middle_standard_action->setCheckable(true);hard_standard_action=newQAction(QIcon(":/images/hard_standard.png"),tr("Hard"),this);hard_standard_action->setCheckable(true);custom_standard_action=newQAction(QIcon(":/images/custom_standard.png"),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/game.png"),tr("About Game"),this);connect(about_game_action,SIGNAL(triggered()),this,SLOT(slot_ about_game()));about_qt_action=newQAction(QIcon(":/images/qt.png"),tr("About Qt"),this);connect(about_qt_action,SIGNAL(triggered()),qApp,SLOT(about Qt()));}/*菜单栏的创建*/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::ToolButtonTextBesideIc on);}void MainWindow::create_statusBar(){time_label=new QLabel;statusBar()->addPermanentWidget(time_label);statusBar()->addPermanentWidget(new QLabel(tr("second"))); }#include"main_window.h"#include<QApplication>#include<QTranslator>int main(int argc,char*argv[]){QApplication app(argc,argv);QTranslator translator;translator.load(":/mine_sweeper_zh.qm");app.installTranslator(&translator);MainWindow window;window.show();return app.exec();}。

简版扫雷代码

简版扫雷代码
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define MAX 100//最大范围为100x100
struct place{
int show;//显示状态(-1为不显示,0为显示@,1为显示status)
char status;//身份(数字为周围8位地雷数,*为地雷,#号为边界标志)
//设置地雷
//初始条件:已有雷区,地雷数目,长度,宽度
//操作结果:在已有雷区放置指定定数目地雷
srand((unsigned)time(NULL));
int i;
for(i=1;i<=number;i++){
int l,w;
l=rand()%length+1;
w=rand()%width+1;
if(mine_area[w][l].status=='*'){
else if(mine_area[i][j].status=='#')
printf("#");
else if(mine_area[i][j].status=='*')
printf("*");
printf(":%d ",mine_area[i][j].show);
}
printf("\n");
}
}
void print_all(place mine_area[][MAX+2],int length,int width){
do{
int x,y;

Android的扫雷游戏源代码

Android的扫雷游戏源代码
(blockDimension + 2 * blockPadding)* numberOfColumnsInMineField,blockDimension + 2 * blockPadding));
}
}
私人无效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())

扫雷游戏代码

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

c语言扫雷程序代码

c语言扫雷程序代码
for(j=0;j<2;j++) if(b[x+i][y+j]==11) n++;
if(n==0) {
for(i=0;i<2;i++) for(j=0;j<2;j++) { if(b[x+i][x+j]==10) { b[x+i][y+j]=0; printf_0(b,x+i,y+j); } }
} else b[x][y]=n; } else if(x==0&&y<Map_list-1&&y>0) { n=0; for(i=0;i<2;i++)
for(j=-1;j<2;j++) if(b[x+i][y+j]==11) n++;
if(n!=0) b[x][y]=n;
else for(i=0;i<2;i++)
for(j=-1;j<2;j++) {
if(b[x+i][y+j]==10) {
b[x+i][y+j]=0; printf_0(b,x+i,y+j); } } } else if(x==0&&y==Map_list-1) { n=0; for(i=0;i<2;i++) for(j=-1;j<1;j++) if(b[x+i][y+j]==11) n++; if(n!=0) b[x][y]=n; else for(i=0;i<2;i++) for(j=-1;j<1;j++) { if(b[x+i][y+j]==10) { b[x+i][y+j]=0; printf_0(b,x+i,y+j); } } } else if(y==Map_list-1&&x!=0&x!=Map_line-1) { n=0; for(i=-1;i<2;i++) for(j=-1;j<1;j++) if(b[x+i][y+j]==11) n++; if(n!=0) b[x][y]=n; else for(i=-1;i<2;i++) for(j=-1;j<1;j++) { if(b[x+i][y+j]==10) {

python扫雷简易代码

python扫雷简易代码

python扫雷简易代码扫雷是一款经典的策略游戏,玩家需要在一个方格矩阵中找出所有没有地雷的格子。

在Python 中可以使用`pygame`库来实现扫雷游戏,`pygame`库是一个第三方库使用前请确保其已经安装,如下是一个代码示例:```pythonimport pygameimport sysimport random# 定义雷的数量和方格大小MINE_NUMBER = 10GRID_SIZE = 10# 定义颜色COLOR_BLACK = (0, 0, 0)COLOR_WHITE = (255, 255, 255)COLOR_RED = (255, 0, 0)COLOR_GREEN = (0, 255, 0)COLOR_GRAY = (192, 192, 192)# 初始化 pygamepygame.init()# 获取对显示系统的访问,并创建一个窗口 screenscreen = pygame.display.set_mode((GRID_SIZE * 20, GRID_SIZE * 20))# 设置画布的标题pygame.display.set_caption("扫雷游戏")# 定义游戏区域的坐标范围area_x = (0, GRID_SIZE * 20)area_y = (0, GRID_SIZE * 20)# 定义一个二维数组来表示游戏区域的状态grid = [[False for _ in range(GRID_SIZE)] for _ in range(GRID_SIZE)]# 生成地雷的位置mines = []for i in range(GRID_SIZE):for j in range(GRID_SIZE):if random.randint(0, MINE_NUMBER) == 0:mines.append((i, j))# 在游戏区域中标记地雷的位置for mine in mines:grid[mine[0]][mine[1]] = True# 用 0 表示空白,1 表示地雷,2 表示已标记的地雷,3 表示周围有地雷的格子,4 表示已翻开的空白格子for i in range(GRID_SIZE):for j in range(GRID_SIZE):if grid[i][j]:grid[i][j] = 1else:grid[i][j] = 0# 游戏循环running = Truewhile running:for event in pygame.event.get():if event.type == pygame.QUIT:running = Falseelif event.type == pygame.MOUSEBUTTONDOWN:x, y = pygame.mouse.get_pos()x = int((x - area_x[0]) / 20)y = int((y - area_y[0]) / 20)if x < 0 or x >= GRID_SIZE or y < 0 or y >= GRID_SIZE:continueif grid[x][y] == 1:running = Falseelif grid[x][y] == 0:grid[x][y] = 4elif grid[x][y] == 2:grid[x][y] = 3# 绘制游戏区域screen.fill(COLOR_WHITE)for i in range(GRID_SIZE):for j in range(GRID_SIZE):if grid[i][j] == 1:pygame.draw.rect(screen, COLOR_RED, (i * 20 + area_x[0], j * 20 + area_y[0], 20, 20))elif grid[i][j] == 2:pygame.draw.rect(screen, COLOR_GRAY, (i * 20 + area_x[0], j * 20 + area_y[0], 20, 20))elif grid[i][j] == 3:pygame.draw.rect(screen, COLOR_GREEN, (i * 20 + area_x[0], j * 20 + area_y[0], 20, 20))elif grid[i][j] == 4:pygame.draw.rect(screen, COLOR_WHITE, (i * 20 + area_x[0], j * 20 + area_y[0], 20, 20))# 刷新显示pygame.display.flip()# 退出程序pygame.quit()sys.exit()```上述代码中定义了一个`扫雷`游戏,首先初始化`pygame`,并创建了一个游戏窗口,设置了游戏区域的大小和坐标范围。

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

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

JAVA实现经典扫雷游戏的⽰例代码⽬录前⾔主要设计功能截图代码实现总结前⾔windows⾃带的游戏《扫雷》是陪伴了⽆数⼈的经典游戏,本程序参考《扫雷》的规则进⾏了简化,⽤java语⾔实现,采⽤了swing技术进⾏了界⾯化处理,设计思路⽤了⾯向对象思想。

主要需求1、要有难度等级,初级,中级,⾼级2、由玩家逐个翻开⽅块,以找出所有地雷为最终游戏⽬标。

如果玩家翻开的⽅块有地雷,则游戏结束3、游戏主区域由很多个⽅格组成。

使⽤⿏标左键随机点击⼀个⽅格,⽅格即被打开并显⽰出⽅格中的数字;⽅格中数字则表⽰其周围的8个⽅格隐藏了⼏颗雷。

4、⽤户右键可标记雷的位置5、雷都被标记出来则胜利主要设计1、格⼦格数固定为10*10格2、难度等级,初级:12,中级:24,⾼级:363、点击格⼦时,产⽣没有引爆的地图效果;4、点击格⼦时,此格⼦是雷,则显⽰所有雷的位置,并递归清空⾮雷格⼦,结束游戏5、实现检查所有的雷是否都被标记出来了,如果是,则胜利算法。

6、实现计时器算法,⽤来计时显⽰游戏开始多少秒7、实现难度等级,雷数的显⽰8、实现⿏标左键的实现逻辑9、实现⿏标右键的标记逻辑功能截图开始界⾯左键选中格⼦效果左键选中雷效果右键标记雷效果胜利效果代码实现程序启动类public class JMine extends JFrame implements MouseListener, ActionListener {private JMineArth mine;private JMineButton[][] mineButton;private GridBagConstraints constraints;private JPanel pane;private GridBagLayout gridbag;private boolean gameStarted;private static JCounter mineCounter;private static JCounter timeCounter;private Timer timer;private Timer winTimer = new Timer();public int numMine;public int numFlaged;private JMenuBar mb;private JMenu mGame;private JMenuItem miEasy;private JMenuItem miMiddle;private JMenuItem miHard;private JMenuItem miExit;private JMenu mHelp;private JMenuItem miAbout;private JPanel controlPane;private JButton bTest;private AboutFrame about;private WinFrame winFrame;private ImageIcon[] mineNumIcon = { new ImageIcon(JMine.class.getClassLoader().getResource("blank1.gif")),new ImageIcon(JMine.class.getClassLoader().getResource("1.gif")), new ImageIcon(JMine.class.getClassLoader().getResource("2.gif")),new ImageIcon(JMine.class.getClassLoader().getResource("3.gif")), new ImageIcon(JMine.class.getClassLoader().getResource("4.gif")),new ImageIcon(JMine.class.getClassLoader().getResource("5.gif")), new ImageIcon(JMine.class.getClassLoader().getResource("6.gif")),new ImageIcon(JMine.class.getClassLoader().getResource("7.gif")), new ImageIcon(JMine.class.getClassLoader().getResource("8.gif")),new ImageIcon(JMine.class.getClassLoader().getResource("0.gif"))};private ImageIcon[] mineStatus = { new ImageIcon(JMine.class.getClassLoader().getResource("blank1.gif")),new ImageIcon(JMine.class.getClassLoader().getResource("flag.gif")), new ImageIcon(JMine.class.getClassLoader().getResource("question.gif")) }; private ImageIcon[] mineBombStatus = { new ImageIcon(JMine.class.getClassLoader().getResource("0.gif")),new ImageIcon(JMine.class.getClassLoader().getResource("mine.gif")), new ImageIcon(JMine.class.getClassLoader().getResource("wrongmine.gif")), new ImageIcon(JMine.class.getClassLoader().getResource("bomb.gif")) };private ImageIcon[] faceIcon = { new ImageIcon(JMine.class.getClassLoader().getResource("smile.gif")),new ImageIcon(JMine.class.getClassLoader().getResource("Ooo.gif")) };// You loseprivate void bomb(int row, int col){try{//System.out.println("Bomb!");for (int i = 0; i < 10; i++) {for (int j = 0; j < 10; j++) {mineButton[i][j].setIcon(mineBombStatus[0]);int toShow;toShow = mine.mine[i][j] != 9 ? 0 : 1;mineButton[i][j].setClickFlag(true);if (toShow == 1 && (i != row || j != col)) {mineButton[i][j].setIcon(mineBombStatus[toShow]);mineButton[i][j].setClickFlag(true);} else if (toShow == 1 && (i == row && j == col)) {mineButton[i][j].setIcon(mineBombStatus[3]);mineButton[i][j].setClickFlag(true);} else if (toShow == 0 && mineButton[i][j].getFlag() != 1) { mineButton[i][j].setEnabled(false);} else if (toShow == 0 && mineButton[i][j].getFlag() == 1) { mineButton[i][j].setIcon(mineBombStatus[2]);mineButton[i][j].setClickFlag(true);}}}timer.cancel();}catch (Exception e){}}// check if you win() {private boolean isWin() {for (int i = 0; i < 10; i++) {for (int j = 0; j < 10; j++) {if (mine.mine[i][j] == 9 && mineButton[i][j].getFlag() != 1) { return (false);}if (mine.mine[i][j] != 9 && mineButton[i][j].getFlag() == 1) { return (false);}if (mine.mine[i][j] != 9&& mineButton[i][j].getClickFlag() == false) {return (false);}}}return (true);}// You Winprivate void win(){timer.cancel();winFrame.setVisible(true);winTimer.schedule(new TimerTask(){public void run() {while(!winFrame.getWinOk()){}numMine = winFrame.getMineNum();winFrame.setVisible(false);setNewGame(numMine);//System.out.println("Jerry Debug:"+numMine);this.cancel();winFrame.setWinOk(false);}},0L);}// Constructor of the gamepublic JMine() {super("JMine Game");setSize(250, 350);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);Insets space = new Insets(0, 0, 0, 0);// Game varsgameStarted = false;numMine = 12;numFlaged = 0;ImageIcon myIcon = new ImageIcon(JMine.class.getClassLoader().getResource("blank1.gif")); gridbag = new GridBagLayout();constraints = new GridBagConstraints();pane = new JPanel();pane.setLayout(gridbag);constraints.fill = GridBagConstraints.BOTH;constraints.anchor = GridBagConstraints.CENTER;// Begin Menu Setmb = new JMenuBar();mGame = new JMenu("Game");miEasy = new JMenuItem("Easy");miEasy.addActionListener(this);miMiddle = new JMenuItem("Middle");miMiddle.addActionListener(this);miHard = new JMenuItem("Hard");miHard.addActionListener(this);miExit = new JMenuItem("Exit");miExit.addActionListener(this);mGame.add(miEasy);mGame.add(miMiddle);mGame.add(miHard);mGame.addSeparator();mGame.add(miExit);mb.add(mGame);mHelp = new JMenu("Help");miAbout = new JMenuItem("About...");mHelp.add(miAbout);miAbout.addActionListener(this);mb.add(mHelp);this.setJMenuBar(mb);// end of Menu Set// Control PanelcontrolPane = new JPanel();bTest = new JButton(faceIcon[0]);bTest.setSize(26, 27);bTest.setMargin(space);bTest.addMouseListener(this);bTest.setPressedIcon(faceIcon[1]);mineCounter = new JCounter(numMine);timeCounter = new JCounter();controlPane.add(mineCounter);controlPane.add(bTest);controlPane.add(timeCounter);buildConstraints(constraints, 0, 0, 10, 2, 100, 100);gridbag.setConstraints(controlPane, constraints);pane.add(controlPane);// BottonsmineButton = new JMineButton[10][10];for (int i = 0; i < 10; i++) {for (int j = 0; j < 10; j++) {mineButton[i][j] = new JMineButton(i, j, myIcon);mineButton[i][j].addMouseListener(this);mineButton[i][j].setMargin(space);buildConstraints(constraints, j, i + 3, 1, 1, 100, 100);gridbag.setConstraints(mineButton[i][j], constraints);pane.add(mineButton[i][j]);}}// Content PanesetContentPane(pane);setLocation(200, 150);setVisible(true);// About Frameabout = new AboutFrame("JMine About");winFrame = new WinFrame("You win!");}// Set the GUI objects positionsvoid buildConstraints(GridBagConstraints gbc, int gx, int gy, int gw, int gh, int wx, int wy) {gbc.gridx = gx;gbc.gridy = gy;gbc.gridwidth = gw;gbc.gridheight = gh;gbc.weightx = wx;gbc.weighty = wy;}// the methods to check if there were mines, to be nestedvoid checkMine(int row, int col){int i, j;i = row < 0 ? 0 : row;i = i > 9 ? 9 : i;j = col < 0 ? 0 : col;j = j > 9 ? 9 : j;//System.out.println("Check Mine row:"+i + ",col:" +j);if (mine.mine[i][j] == 9) {bomb(i, j);} else if (mine.mine[i][j] == 0&& mineButton[i][j].getClickFlag() == false) {mineButton[i][j].setClickFlag(true);showLabel(i, j);for (int ii = i - 1; ii <= i + 1; ii++)for (int jj = j - 1; jj <= j + 1; jj++)checkMine(ii, jj);} else {showLabel(i, j);mineButton[i][j].setClickFlag(true);}if (isWin()) {win();}}private void clearAll(int row, int col){int top, bottom, left, right;top = row - 1 > 0 ? row - 1 : 0;bottom = row + 1 < 10 ? row + 1 : 9;left = col - 1 > 0 ? col - 1 : 0;right = col + 1 < 10 ? col + 1 : 9;for (int i = top; i <= bottom; i++) {for (int j = left; j <= right; j++) {if (mineButton[i][j].getFlag() != 1)checkMine(i, j);}}}private void resetAll() {for (int i = 0; i < 10; i++) {for (int j = 0; j < 10; j++) {mineButton[i][j].setFlag(0);mineButton[i][j].setClickFlag(false);mineButton[i][j].setIcon(mineStatus[0]);mineButton[i][j].setEnabled(true);mineButton[i][j].setVisible(true);}}}// to flag the mine you want to flag outvoid flagMine(int row, int col) {//System.out.println("Jerry Arrives here!");int i, j;i = row < 0 ? 0 : row;i = i > 9 ? 9 : i;j = col < 0 ? 0 : col;j = j > 9 ? 9 : j;if (mineButton[i][j].getFlag() == 0) {numFlaged++;} else if (mineButton[i][j].getFlag() == 1) {numFlaged--;}mineCounter.resetCounter(numMine - numFlaged >= 0 ? numMine - numFlaged: 0);mineButton[i][j].setFlag((mineButton[i][j].getFlag() + 1) % 3);showFlag(i, j);if (isWin()) {win();}}// show the numbers of the nearby minesvoid showLabel(int row, int col) {//System.out.println("ShowLabel row:" + row + ",col:" + col);int toShow;toShow = mine.mine[row][col];if (toShow != 0) {mineButton[row][col].setIcon(mineNumIcon[toShow]);mineButton[row][col].setClickFlag(true);//mineButton[row][col].setEnabled(false);} else {//mineButton[row][col].setIcon(mineNumIcon[0]);//mineButton[row][col].setClickFlag(true);mineButton[row][col].setEnabled(false);}}// circle the flag with blank, flaged, questionedvoid showFlag(int row, int col) {mineButton[row][col].setIcon(mineStatus[mineButton[row][col].getFlag()]);}// the mouse events listener methodspublic void mouseEntered(MouseEvent e) {//System.out.println("Jerry Test");}// method to start the new gameprivate void startNewGame(int num, int row, int col){mine = new JMineArth(num, row, col);//mine.printMine();gameStarted = true;timer = new Timer();timer.scheduleAtFixedRate(new TimerTask(){public void run() {timeCounter.counterAdd();//System.out.println(timeCounter.getCounterNum());}},1000,1000);}public void setNewGame(int num) {resetAll();numMine = num;numFlaged = 0;gameStarted = false;mineCounter.resetCounter(numMine);timeCounter.resetCounter(0);}// the event handle to deal with the mouse clickpublic void mouseClicked(MouseEvent e) {if (e.getSource() == bTest) {setNewGame(numMine);return;}int row, col;row = ((JMineButton) e.getSource()).getRow();col = ((JMineButton) e.getSource()).getCol();if (!gameStarted) {startNewGame(numMine, row, col);}if (e.getModifiers() == (InputEvent.BUTTON1_MASK + InputEvent.BUTTON3_MASK)) { //System.out.println("HA");clearAll(row, col);}if (!mineButton[row][col].getClickFlag()) {if (e.getModifiers() == InputEvent.BUTTON1_MASK) {//System.out.println("LeftButton");if (mineButton[row][col].getFlag() == 1) {return;} else {checkMine(row, col);}} else if (e.getModifiers() == InputEvent.BUTTON3_MASK) { //System.out.println("RightButton");flagMine(row, col);} else {//System.out.println("MiddleButton");}}}public void mousePressed(MouseEvent e) {//System.out.println("Jerry Press");}public void mouseReleased(MouseEvent e) {//System.out.println("Jerry Release");}public void mouseExited(MouseEvent e) {//System.out.println("Jerry Exited");}public void actionPerformed(ActionEvent e) {try {if (e.getSource() == miEasy) {setNewGame(12);return;}if (e.getSource() == miMiddle) {setNewGame(24);return;}if (e.getSource() == miHard) {setNewGame(36);return;}if (e.getSource() == miExit) {System.exit(0);}if (e.getSource() == miAbout) {about.setVisible(true);}} catch (Exception ie) {}}public static void main(String [] args) {JMine jmine = new JMine();jmine.setVisible(true);}}地雷分布图算法类public class JMineArth {public int [][] mine;private boolean fMineSet;JMineArth(int mineNum, int row, int col) {mine = new int[10][10];setMine(mineNum, row, col);setMineNum();}private void setMine(int mineNum, int Outrow, int Outcol) {int col=0, row = 0, i=0;//Math.srand(now);while (i < mineNum) {col = (int)(Math.random()*100)%10;row = (int)(Math.random()*100)%10;if (mine[col][row]==0 && (row!=Outrow || col!=Outcol || Outrow==10 )) {mine[row][col]=9;i++;}}}private void setMineNum() {for ( int i=0 ; i <10; i++) {for (int j=0; j < 10; j++) {mine[i][j]=mine[i][j]==9?9:checkMineNum(i,j);}}fMineSet = true;}private int checkMineNum(int ii,int jj) {int top,bottom, left, right, count=0;top=ii-1>0?ii-1:0;bottom=ii+1<10?ii+1:9;left=jj-1>0?jj-1:0;right=jj+1<10?jj+1:9;for (int i=top; i<=bottom; i++) {for(int j=left; j<= right; j++) {if (mine[i][j]==9) count++;}}return(count);}public void printMine() {for (int i = 0; i < 10; i++) {for (int j=0; j < 10; j++) {System.out.print(this.mine[i][j] + " ");}System.out.println();}}public static void main(String[] args) {JMineArth mine = new JMineArth(Integer.parseInt(args[0]),Integer.parseInt(args[1]),Integer.parseInt(args[2]));mine.printMine();}}总结通过此次的《扫雷》游戏实现,让我对swing的相关知识有了进⼀步的了解,对java这门语⾔也有了⽐以前更深刻的认识。

扫雷代码

扫雷代码
surface[i][j]=backstage[i][j]+'0';
num--;
}
}
}
}
else // 数字为零时 显示零周围的零
for(int j=c-1;j<=c+1;j++)
{
if(alls[i][j]!=alls[r][c]&&alls[i][j]==1){backstage[r][c]++;};
}
}; //else 结束
}; // for 结束
for(c=1;c<=Column;c++)
{
surface[r][c]='#';
}
for(r=1;r<=Row;r++) //输出 surface 界面 便于检查
{
for(c=1;c<=Column;c++) {cout<<" "<<surface[r][c];};
for(r=1;r<=Row;r++) //输了 输出backstage 显示正确答案
{
for(int c=1;c<=Column;c++)
{
cout<<" "<<(char)(backstage[r][c]==42?backstage[r][c]:backstage[r][c]+'0'); //输出backstage
{
if(surface[x][y]=='#'){num--;}; //数“#”

扫雷小游戏代码c++版

扫雷小游戏代码c++版

#include<iostream>#include<ctime>#include<cstdlib>using namespace std;int lei;int line,arrange,thunder1,thunder2,space;void saolei(char **&a,char **&c,int **&b,int **&d,int **&e,int **&g,int &line,int &arrange,int &thunder1,int &thunder2,int &space){int all=1;while(all){int i,j;a=new char*[line],c=new char*[line],b=new int*[line],d=new int*[line],e=new int*[line],g=new int*[line];for(i=0;i<=line-1;i++)a[i]=new char[arrange],c[i]=new char[arrange],b[i]=new int[arrange],d[i]=newint[arrange],e[i]=new int[arrange],g[i]=new int[arrange];for(i=0;i<line;i++)for(j=0;j<arrange;j++)a[i][j]='.',b[i][j]=0,c[i][j]='.',e[i][j]=0,g[i][j]=0;int k;srand(int(time(0)));int z=1;while(z){k=rand()%(thunder2+1);if(k>=thunder1)z=0;}srand(int(time(0)));for(i=1;i<=k;i++){int s,t;L:{s=rand()%line;t=rand()%arrange;}if(!(s>=0&&s<line&&t>=0&&t<arrange&&a[s][t]!='#'))goto L;for(int m=0;m<line;m++)for(int n=0;n<arrange;n++){if(m==s&&n==t&&a[m][n]!='#')a[m][n]='#';}}for(i=0;i<line;i++)for(j=0;j<arrange;j++){if(j-1>=0&&a[i][j-1]=='#')if(j+1<arrange&&a[i][j+1]=='#')b[i][j]++;if(i-1>=0&&a[i-1][j]=='#')b[i][j]++;if(i+1<line&&a[i+1][j]=='#')b[i][j]++;if(i-1>=0&&j+1<arrange&&a[i-1][j+1]=='#')b[i][j]++;if(i-1>=0&&j-1>=0&&a[i-1][j-1]=='#')b[i][j]++;if(i+1<line&&j+1<arrange&&a[i+1][j+1]=='#')b[i][j]++;if(j-1>=0&&i+1<line&&a[i+1][j-1]=='#')b[i][j]++;}int f=0;for(i=0;i<line;i++)for(j=0;j<arrange;j++){if(a[i][j]=='#')d[i][j]=2;else {if(j-1>=0&&a[i][j-1]=='.')f++;if(j+1<arrange&&a[i][j+1]=='.')f++;if(i-1>=0&&a[i-1][j]=='.')f++;if(i+1<line&&a[i+1][j]=='.')f++;if(i-1>=0&&j+1<arrange&&a[i-1][j+1]=='.')f++;if(i-1>=0&&j-1>=0&&a[i-1][j-1]=='.')f++;if(i+1<line&&j+1<arrange&&a[i+1][j+1]=='.')f++;if(j-1>=0&&i+1<line&&a[i+1][j-1]=='.')f++;if(i-1>=0&&i+1<line&&j-1>=0&&j+1<arrange){if(f==8)d[i][j]=1;else d[i][j]=0;}else if(i==0&&j==0||i==0&&j==arrange-1||i==line-1&&j==0||i==line-1&&j==arrange-1) {if(f==3)else d[i][j]=0;}else{if(i==0&&j!=0&&j!=arrange-1||i==line-1&&j!=arrange-1&&j!=0||i!=line-1&&i!=0&&j==0||i!=line-1&&i!=0&&j==arrange-1){if(f==5)d[i][j]=1;else d[i][j]=0;}}f=0;}}int x,y,left=0,right=0,hang,shu,duan=0,jishu=0;z=1;for(i=1;i<=space;i++)cout<<" ";for(i=0;i<=line;i++)if(i<=9)cout<<i<<" ";else cout<<i;cout<<endl;for(i=0;i<line;i++){if(i<9){for(k=1;k<=space;k++)cout<<" ";}if(i>=9){for(k=1;k<=space-1;k++)cout<<" ";}cout<<i+1<<" ";for(j=0;j<arrange;j++)cout<<c[i][j]<<" ";cout<<endl;}while(z){cout<<"请输入你要翻开的位置(如:6 0 或5 6 1 ):";cin>>x>>y>>lei;x--,y--;if(a[x][y]=='#')e[x][y]=1;if(a[x][y]=='.'){if(b[x][y]!=0)e[x][y]=1;if(b[x][y]==0){for(i=0;i<line&&duan==0;i++)for(j=0;j<arrange&&duan==0;j++)if(d[i][j]==1){d[i][j]=3;int dir=3,fu=0,pan=1,ci=0;int m=i,n=j;do{ switch(dir){ case 1 : //向左走{if (m-1>=0&&d[m-1][n]==1) {d[m-1][n]=3;m--;dir=2;} //检测所在位置右边else if (n-1>=0&&d[m][n-1]==1) {d[m][n-1]=3;n--;dir=1;} //检测所在位置前方else if (m+1<line&&d[m+1][n]==1) {d[m+1][n]=3;m++;dir=4;} //检测所在位置左边else if(n+1<arrange&&d[m][n+1]==1){d[m][n+1]=3;n++;dir=3;} //检测所在位置后方else if(m-1>=0&&d[m-1][n]==3) {m--;dir=2;} //检测所在位置右边else if (n-1>=0&&d[m][n-1]==3) {n--;dir=1;} //检测所在位置前方else if (m+1<line&&d[m+1][n]==3) {m++;dir=4;} //检测所在位置左边else {if(n+1<arrange&&d[m][n+1]==3){n++;dir=3;}} //检测所在位置后方}break;case 2 : //向上走{if (n+1<arrange&&d[m][n+1]==1) {d[m][n+1]=3;n++;dir=3;} //检测所在位置右边else if (m-1>=0&&d[m-1][n]==1) {d[m-1][n]=3;m--;dir=2;} //检测所在位置前方else if (n-1>=0&&d[m][n-1]==1) {d[m][n-1]=3;n--;dir=1;} //检测所在位置左边else if(m+1<line&&d[m+1][n]==1){d[m+1][n]=3;m++;dir=4;} //检测所在位置后方else if(n+1<arrange&&d[m][n+1]==3) {n++;dir=3;} //检测所在位置右边else if (m-1>=0&&d[m-1][n]==3) {m--;dir=2;} //检测所在位置前方else if (n-1>=0&&d[m][n-1]==3) {n--;dir=1;} //检测所在位置左边else {if(m+1<line&&d[m+1][n]==3){m++;dir=4;}} //检测所在位置后方}break;case 3 : //向右走{ if (m+1<line&&d[m+1][n]==1) {d[m+1][n]=3;m++;dir=4;} //检测所在位置右边else if (n+1<arrange&&d[m][n+1]==1) {d[m][n+1]=3;n++;dir=3;} //检测所在位置前方else if (m-1>=0&&d[m-1][n]==1) {d[m-1][n]=3;m--;dir=2;} //检测所在位置左边else if(n-1>=0&&d[m][n-1]==1){d[m][n-1]=3;n--;dir=1;} //检测所在位置后方else if(m+1<line&&d[m+1][n]==3) {m++;dir=4;} //检测所在位置右边else if (n+1<arrange&&d[m][n+1]==3) {n++;dir=3;} //检测所在位置前方else if (m-1>=0&&d[m-1][n]==3) {m--;dir=2;} //检测所在位置左边else {if(n-1>=0&&d[m][n-1]==3){n--;dir=1;}} //检测所在位置后方}break;case 4 : //向下走{if (n-1>=0&&d[m][n-1]==1) {d[m][n-1]=3;n--;dir=1;} //检测所在位置右边else if (m+1<line&&d[m+1][n]==1) {d[m+1][n]=3;m++;dir=4;} //检测所在位置前方else if (n+1<arrange&&d[m][n+1]==1) {d[m][n+1]=3;n++;dir=3;} //检测所在位置左边else if(m-1>=0&&d[m-1][n]==1){d[m-1][n]=3;m--;dir=2;} //检测所在位置后方else if(n-1>=0&&d[m][n-1]==3) {n--;dir=1;} //检测所在位置右边else if (m+1<line&&d[m+1][n]==3) {m++;dir=4;} //检测所在位置前方else if (n+1<arrange&&d[m][n+1]==3) {n++;dir=3;} //检测所在位置左边else {if(m-1>=0&&d[m-1][n]==3){m--;dir=2;}} //检测所在位置后方}break;}if(d[m][n]==3)ci++;if(ci>=line*arrange)pan=0;if(m==i&&n==j){fu++;if(fu==4)pan=0;}if(m==x&&n==y)left=i+1,right=j+1,duan=1;}while(pan);if(left==0&&right==0)for(hang=0;hang<line;hang++)for(shu=0;shu<arrange;shu++)if(d[hang][shu]==3)d[hang][shu]=1;}left=0,right=0,duan=0;for(i=0;i<line;i++)for(j=0;j<arrange;j++)if(d[i][j]==3)e[i][j]=1;for(i=0;i<line;i++)for(j=0;j<arrange;j++)if(d[i][j]==3){if(j-1>=0)e[i][j-1]=1;if(j+1<arrange)e[i][j+1]=1;if(i-1>=0)e[i-1][j]=1;if(i+1<line)e[i+1][j]=1;if(i-1>=0&&j+1<arrange)e[i-1][j+1]=1;if(i-1>=0&&j-1>=0)e[i-1][j-1]=1;if(i+1<line&&j+1<arrange)e[i+1][j+1]=1;if(j-1>=0&&i+1<line)e[i+1][j-1]=1;}}}//当b[x][y]==0时system("cls");//清屏for(i=0;i<line;i++)for(j=0;j<arrange;j++)if(d[i][j]==3)d[i][j]=1;if(a[x][y]=='.'&&b[x][y]!=0&&lei!=2) {for(i=1;i<=space;i++)cout<<" ";for(i=0;i<=line;i++)if(i<=9)cout<<i<<" ";else cout<<i;cout<<endl;for(i=0;i<line;i++){if(i<9){for(k=1;k<=space;k++)cout<<" ";cout<<i+1<<" ";}if(i>=9){for(k=1;k<=space-1;k++)cout<<" ";cout<<i+1<<" ";}for(j=0;j<arrange;j++)if(g[i][j]==1){if(a[i][j]=='#')cout<<a[i][j]<<" ";else cout<<b[i][j]<<" ";}else if(i==x&&y==j)cout<<b[i][j]<<" ";else cout<<c[i][j]<<" ";cout<<endl;}if(lei==1){jishu++;if(jishu<=3)cout<<"提示:判断错误"<<jishu<<"次,若判断错误超过三次,你将输掉游戏,注意哦o(︶︿︶)o"<<endl; }}//第一种情况if(a[x][y]=='.'&&b[x][y]==0&&lei!=2){for(i=1;i<=space;i++)cout<<" ";for(i=0;i<=line;i++)if(i<=9)cout<<i<<" ";else cout<<i;cout<<endl;for(i=0;i<line;i++){if(i<9){for(k=1;k<=space;k++)cout<<" ";cout<<i+1<<" ";}if(i>=9){for(k=1;k<=space-1;k++)cout<<" ";cout<<i+1<<" ";}for(j=0;j<arrange;j++)if(g[i][j]==1){if(a[i][j]=='#')cout<<a[i][j]<<" ";else cout<<b[i][j]<<" ";}else if(e[i][j]==1)cout<<b[i][j]<<" ";else cout<<c[i][j]<<" ";cout<<endl;}if(lei==1){jishu++;if(jishu<=3)cout<<"提示:判断错误"<<jishu<<"次,若判断错误超过三次,你将输掉游戏,注意哦o(︶︿︶)o"<<endl; }}//第二种情况if(a[x][y]=='#'&&lei==0)cout<<" ";for(i=0;i<=line;i++)if(i<=9)cout<<i<<" ";else cout<<i;cout<<endl;for(i=0;i<line;i++){if(i<9){for(k=1;k<=space;k++)cout<<" ";cout<<i+1<<" ";}if(i>=9){for(k=1;k<=space-1;k++)cout<<" ";cout<<i+1<<" ";}for(j=0;j<arrange;j++)if(g[i][j]==1){if(a[i][j]=='#')cout<<a[i][j]<<" ";else cout<<b[i][j]<<" ";}else if(e[i][j]==1)cout<<a[i][j]<<" ";else if(a[i][j]=='#')cout<<a[i][j]<<" ";else cout<<c[i][j]<<" ";cout<<endl;}cout<<"oh my god 你输了!所有雷的位置已显示出,请再接再厉哦(*^__^*) 嘻嘻……"<<endl; z=0;}//第三种情况if(a[x][y]=='#'&&lei==1){for(i=1;i<=space;i++)cout<<" ";for(i=0;i<=line;i++)if(i<=9)cout<<i<<" ";else cout<<i;cout<<endl;for(i=0;i<line;i++){if(i<9)cout<<" ";cout<<i+1<<" ";}if(i>=9){for(k=1;k<=space-1;k++)cout<<" ";cout<<i+1<<" ";}for(j=0;j<arrange;j++)if(g[i][j]==1){if(a[i][j]=='#')cout<<a[i][j]<<" ";else cout<<b[i][j]<<" ";}else if(e[i][j]==1)cout<<a[i][j]<<" ";else cout<<c[i][j]<<" ";cout<<endl;}}//第四种情况if(lei==2||lei==3||lei==4)z=0,all=0;for(i=0;i<line;i++)for(j=0;j<arrange;j++)if(e[i][j]==1)g[i][j]=e[i][j];for(i=0;i<line;i++)for(j=0;j<arrange;j++)e[i][j]=0;int sum=1;for(i=0;i<line;i++)for(j=0;j<arrange;j++)sum*=g[i][j];if(sum!=0){cout<<"oh good 你赢了耶!( ^_^ )不错嘛"<<endl; z=0;}int total=1;for(i=0;i<line;i++)for(j=0;j<arrange;j++)if(a[i][j]=='#'){if(g[i][j]==1)total*=1;if(g[i][j]!=1)total*=0;}if(total!=0&&sum==0){cout<<"oh good 你赢了耶!( ^_^ )不错嘛"<<endl;z=0;}if(jishu>3){cout<<"how pitty! 错误判断超过三次,你输了,下次注意哦(*^__^*)"<<endl;z=0;}}//循环并判断是否继续循环}}int main(){L:{cout<<"游戏名称:扫雷"<<'\n'<<"--------------------------------------------------------------------------------"<<'\n' <<"说明:.代表未翻开的地方;#表示雷;翻开地方显示的数字表示:该地方四周的八个相邻的地方含有雷的总数"<<'\n'<<"--------------------------------------------------------------------------------"<<'\n' <<"规则:根据翻开地方显示的数字判断雷所在的地方"<<'\n'<<"--------------------------------------------------------------------------------"<<'\n' <<"操作:根据判断,请输入位置(如:6 0/1/2/3/4)"<<'\n'<<"--------------------------------------------------------------------------------"<<'\n' <<"解释:输入的三个数字中,前两个数字表示位置,如:表示行数,表示列数;第三个表示判断与选择,--无雷,--有雷,--再来一局,--结束游戏,--重启整个游戏系统"<<'\n'<<"--------------------------------------------------------------------------------"<<'\n' <<"例如:5 6 0 表示游戏者认为该处无雷,6 1表示游戏者认为该处有雷,6 2表示再来一局,6 3表示结束游戏,6 4表示重启游戏系统"<<'\n'<<"--------------------------------------------------------------------------------"<<endl; int choice,i;char **a=NULL,**c=NULL;int **b=NULL,**d=NULL,**e=NULL,**g=NULL;cout<<"游戏等级有五:"<<'\n'<<"1--茅塞未开(方格x7, 雷数-->5)"<<'\n'<<"2--七窍通六(方格x10,雷数-->10)"<<'\n'<<"3--闲庭信步(方格x13,雷数-->15)"<<'\n'<<"4--炉火纯青(方格x15,雷数-->30)"<<'\n'<<"5--偶滴神呀(方格x25,雷数-->100)"<<'\n'<<"6--自定义难易程度"<<endl;cout<<"请选择:";cin>>choice;if(choice==1)line=7,arrange=7,thunder1=3,thunder2=5,space=33;if(choice==2)line=10,arrange=10,thunder1=7,thunder2=10,space=30;if(choice==3)line=13,arrange=13,thunder1=10,thunder2=15,space=27;if(choice==4)line=15,arrange=15,thunder1=15,thunder2=30,space=25;if(choice==5)line=25,arrange=25,thunder1=50,thunder2=100,space=15;if(choice==6){cout<<"请输入方格的行(行<=39):";cin>>line;cout<<"请输入方格的列(列<=39):";cin>>arrange;cout<<"希望出现雷的个数的范围(如:5):";cin>>thunder1>>thunder2;space=40-arrange;}if(choice<=0||choice>6||line<=0||arrange<=0||thunder2<thunder1||thunder2>line*arrange) {lei=3;goto M;}saolei(a,c,b,d,e,g,line,arrange,thunder1,thunder2,space);if(lei==2)saolei(a,c,b,d,e,g,line,arrange,thunder1,thunder2,space);M:{if(lei==3)cout<<"*******游戏结束,欢迎下次使用********"<<endl;}if(lei==4){system("cls");goto L;}for(i=0;i<=line-1;i++)delete []a[i],delete []b[i],delete []c[i],delete []d[i],delete []e[i],delete []g[i]; delete []a,delete []b,delete []c,delete []d,delete []e,delete []g;a=NULL,b=NULL,c=NULL,d=NULL,e=NULL,g=NULL;}}。

vb扫雷游戏代码

vb扫雷游戏代码

Public Class formDim chks(8, 8) As CheckBoxDim o As IntegerDim i, j As IntegerDim P, U As IntegerDim arr(9, 0) As ObjectPrivate Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Clicko = 0For i = 0 To 8For j = 0 To 8If chks(i, j) Is Nothing Thenchks(i, j) = New CheckBox()End IfAddHandler chks(i, j).MouseUp, AddressOf Chk_MouseUpchks(i, j).Appearance =Appearance.Buttonchks(i, j).height = 25chks(i, j).width = 25chks(i, j).Top = i * 25 + 50chks(i, j).left = j * 25chks(i, j).text = ""chks(i, j).tag = 0chks(i, j).BackColor = Me.BackColorchks(i, j).checked = Falsechks(i, j).Enabled = Truechks(i, j).Font = New Font("Arial", 14, FontStyle.Bold)Me.Controls.Add(chks(i, j))NextNextDim n As Integer = 0Dim h As Integer = 0Randomize()Do While h < 10P = Math.Floor(Rnd() * 9)U = Math.Floor(Rnd() * 9)If chks(P, U).Tag = 0 Thenarr(n, 0) = chks(P, U)chks(P, U).Tag = 1h = h + 1n += 1End IfLoopTimer1.Enabled = TrueEnd SubPrivate Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)End SubPrivate Sub Chk_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)Dim chk As CheckBox = CType(sender, CheckBox)Dim m As IntegerIf chk.Tag = 1 ThenFor m = 0 To 9arr(m, 0).BackColor = Color.BlueNextMsgBox("over ")EndEnd IfCall autoopen(chk)End SubSub autoopen(ByVal chk As CheckBox)Dim row As Integer = chk.Top / 25Dim col As Integer = chk.Left / 25Dim i, j As IntegerDim sum As Integer = 0For i = row - 1 To row + 1For j = col - 1 To col + 1If (i >= 0) And (i < 9) And (j >= 0) And (j < 9) Thensum += chks(i, j).TagEnd IfNextNextchk.Text = sumchk.Enabled = FalseIf sum = 0 ThenFor i = row - 1 To row + 1For j = row - 1 To row + 1If (i >= 1) And (i <= 8) And (j >= 1) And (j <= 8) ThenIf chks(i, j).Text = "" ThenCallautoopen(chks(i, j))End IfEnd IfNextNextEnd IfEnd SubPrivate Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.LoadEnd SubPrivate Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Ticko = o + 1TextBox1.Text = oEnd SubPrivate Sub Button1_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) HandlesButton1.MouseDoubleClickEnd SubPrivate Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChangedEnd SubEnd Class。

C语言代码实现简单扫雷小游戏

C语言代码实现简单扫雷小游戏

C语⾔代码实现简单扫雷⼩游戏⽤C语⾔写⼀个简单的扫雷,供⼤家参考,具体内容如下1.所需要的知识c语⾔的基本语法,简单的⼆维数组,⼀点简单的递归知识。

2.总体思路扫雷游戏主要由3个部分组成,埋雷⼦,扫雷,判断输赢。

扫雷游戏的主体是两个个字符类型的⼆维数组。

⼀个是mine[][]它的构成是'0'和‘1',其中'0'表⽰⽆雷,'1'表⽰有雷。

⼀个是show[][]它的构成是'*'和'数字'。

星号表⽰未开启的地⽅,数字表⽰周围的雷数。

这⾥要注意的是:mine和show的实际⼤⼩是11x11,但是展⽰的效果是 9x9。

这样做的优点将在Find()中体现。

蓝⾊部分是可见的9x9,实际的类似红⾊ 11x11。

下⾯是我⽤到的⼀些函数。

//game.h#pragma once#ifndef __GAME_H__#define __GAME_H__#include<stdio.h>#include<stdlib.h>#include<process.h>#include<string.h>#include<time.h>#define ROW 9 // 9⾏#define COL 9 // 9列#define ROWS ROW+2 //实际⾏#define COLS COL+2 //实际列#define MineNum 10 //雷⼦数量//菜单信息void menu();//执⾏菜单void test(char mine[ROWS][COLS], int row1, int col1, char show[ROWS][COLS], int row2, int col2);//游戏主体void game(char mine[ROWS][COLS], int row1, int col1, char show[ROWS][COLS], int row2, int col2);//打印雷阵void InitBoard(char arr[ROWS][COLS], int row, int col);//埋雷⼦void SetMine(char mine[ROWS][COLS], int row, int col);//找雷⼦int FindMine(char mine[ROWS][COLS], int row1, int col1, char show[ROWS][COLS], int row2, int col2);//空⽩算法void Find(char mine[ROWS][COLS], int row1, int col1, char show[ROWS][COLS], int row2, int col2,int x, int y,int exam[ROWS][COLS]);#endif//__GAME_H__下⾯是主函数内容#include"game.h"int main(){char mine[ROWS][COLS];char show[ROWS][COLS];srand ((unsigned int)time(NULL)); //⽣成随机数,⽤于随机埋雷int i = 0, j = 0;test(mine, ROWS, COLS, show, ROWS, COLS); //测试函数system("pause");return 0;}3.详细实现菜单函数void menu(){printf("******************\n");printf("******1.play *****\n");printf("******0.exit *****\n");printf("******************\n");}这个函数是⽤来打印信息的,打印⼀个简单的菜单。

扫雷源代码(精)

扫雷源代码(精)

#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; // 游戏胜利结束,正确的扫完了所有的雷}。

python扫雷简易代码

python扫雷简易代码

python扫雷简易代码Python是一种简单易学、功能强大的编程语言,广泛应用于各个领域。

在本文中,我们将介绍如何使用Python编写一个简易的扫雷程序。

1. 游戏规则扫雷是一种经典的益智游戏,玩家需要根据已翻开的方块上的数字判断周围是否有雷,并标记雷的位置。

游戏的目标是翻开所有非雷方块,而不触雷。

2. 扫雷算法为了实现扫雷游戏,我们需要设计一个算法来生成雷区并计算每个方块周围的雷数。

以下是一个简单的扫雷算法:(1)初始化一个二维列表,表示雷区。

列表中的每个元素为一个字典,包含is_mine(是否是雷)、is_open(是否已翻开)和mine_count(周围的雷数)三个属性。

(2)随机生成一定数量的雷,将雷的is_mine属性设置为True。

(3)遍历雷区的每个方块,计算它周围的雷数并将结果存储在mine_count属性中。

3. Python代码实现下面是一个简易的Python扫雷程序代码:```pythonimport randomdef generate_minesweeper_board(rows, cols, mine_count):board = []for r in range(rows):row = []for c in range(cols):cell = {'is_mine': False, 'is_open': False, 'mine_count': 0} row.append(cell)board.append(row)mines = random.sample(range(rows * cols), mine_count)for index in mines:row = index // colscol = index % colsboard[row][col]['is_mine'] = Truefor r in range(rows):for c in range(cols):if not board[r][c]['is_mine']:count = 0for dx in [-1, 0, 1]:for dy in [-1, 0, 1]:if 0 <= r + dx < rows and 0 <= c + dy < cols and board[r + dx][c + dy]['is_mine']:count += 1board[r][c]['mine_count'] = countreturn boardrows = 10cols = 10mine_count = 10board = generate_minesweeper_board(rows, cols, mine_count)for r in range(rows):for c in range(cols):if board[r][c]['is_mine']:print('X', end=' ')else:print(board[r][c]['mine_count'], end=' ')print()```4. 代码解析(1)首先,我们通过调用`generate_minesweeper_board`函数生成一个扫雷的雷区,指定雷区的行数、列数和雷的数量。

c语言编写扫雷代码

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为布雷的位置坐标。

C++实现简单扫雷游戏

C++实现简单扫雷游戏

C++实现简单扫雷游戏扫雷是⼀个经典的电脑⼩游戏,⽤C++来编⼀下,效果⾃⼰试⼀下#include<stdio.h>#include<Windows.h>#define YELLOW FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY#define CYAN FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY#define ORANGE FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY#define PURPLE FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITYusing namespace std;const int STARTX = 30;const int STARTY = 6;const int MAXX = 9;//雷区的宽const int MAXY = 9;//雷区的⾼const int BOMBNUMBER = 10;//地雷数量class Cube{private:bool ifHaveBomb;//该⽅块是否含有炸弹bool ifOpen;//该⽅块有⽆被玩家翻开int nearBombNumber;//该区块周围8格的含有炸弹的⽅块的数量public:void setOpen() {//将Open的值改为trueifOpen = true;}bool getOpen() {//获取ifOpen的值return ifOpen;}void setNearBombNumber(int number) {//给nearBombNumber赋值nearBombNumber = number;}void haveBomb() {//给⽅块放置地雷ifHaveBomb = true;}bool getIfHaveBomb() {//获取ifHaveBomb的值return ifHaveBomb;}int getNearBombNumber() {//获取nearBombNumber的值return nearBombNumber;}void resetCube(bool ifhavebomb = false, bool ifopen = false, int nearbombnumber = 0){//初始化成员数据ifHaveBomb = ifhavebomb;ifOpen = ifopen;nearBombNumber = nearbombnumber;}};Cube cube[MAXX][MAXY];void GoTo(int x, int y);//定位光标void setBomb(int bombNumber);//⽣成bombNumber个炸弹并且放进随机的⽅块中void show();//显⽰地雷阵int checkAndSetNearBombNumber(int x, int y);//检查当前⽅块周围的雷数量void gameStart();//初始化游戏void showXY();//显⽰雷区坐标bool player(bool &life);//玩家输⼊坐标翻开⽅块void message(bool life);//玩家游戏结束后输出的信息void autoOpen(int x,int y);//玩家翻开的⽅块为不含雷且周围⽆雷的⽅块时,⾃动翻开周围⽆雷的⽅块bool ifWin();//判断玩家是否扫雷成功void showBomb();//游戏结束后显⽰地雷位置int main() {system("title 李柏衡");gameStart();show();bool life = true, win = true;while (player(life) && !ifWin()) {}message(life && ifWin());return 0;}void GoTo(int x, int y) {//定位光标COORD coord = { x,y };SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);}void setBomb(int bombNumber = BOMBNUMBER) {//⽣成bombNumber个炸弹并且放进随机的⽅块中srand((unsigned)GetCurrentTime());while (bombNumber--) {int x = MAXX + 1, y = MAXY + 1;while ((x >= MAXX || y >= MAXY) || cube[x][y].getIfHaveBomb() == true) {x = rand() % MAXX;y = rand() % MAXY;}cube[x][y].haveBomb();}}void show() {//显⽰地雷阵system("cls");showXY();SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), CYAN);for (int i = 0;i < MAXY;i++) {GoTo(STARTX, STARTY + i);for (int j = 0;j < MAXX;j++) {if (cube[j][i].getOpen() == true) {if (cube[j][i].getIfHaveBomb() == false) {if (cube[j][i].getNearBombNumber() == 0) { //挖开⽆雷的⽅块显⽰该⽅块周围多少个⽅块含雷,若为0则显⽰空格 printf(" ");} else {printf(" %d", cube[j][i].getNearBombNumber());}} else {printf("×");//有雷的⽅块被挖开后显⽰×}} else {printf("■");//未翻开的⽅块⽤■显⽰}}}}void showXY() {//显⽰坐标轴SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), CYAN);GoTo(STARTX - 3, STARTY + MAXY / 2);printf("Y");GoTo(STARTX + MAXX, STARTY - 2);printf("X");SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), YELLOW);for (int i = 0;i < MAXY;i++) {GoTo(STARTX - 1, STARTY + i);printf("%d ", i);}for (int i = 0;i < 2 * MAXX;i += 2) {GoTo(STARTX + i + 1, STARTY - 1);printf("%d ", i / 2);}}int checkAndSetNearBombNumber(int x, int y) {//检查当前⽅块周围的雷数量int num = 0;if (cube[x][y].getIfHaveBomb() == true) {//若该⽅块有地雷,则不⽤判断它周围有⼏个雷return 0;} else {//⽤两个循环当前⽅块周围8格扫⼀遍for (int i = -1; i <= 1; i++) {for (int j = -1; j <= 1; j++) {int nx = x + i;int ny = y + j;if (!(ny == y && nx == x) && (nx >= 0 && nx <= MAXX - 1) &&(ny >= 0 && ny <= MAXY - 1)) {if (cube[nx][ny].getIfHaveBomb()) {num++;}}}}cube[x][y].setNearBombNumber(num);//设置该⽅块附近的地雷的数量 return 0;}}void gameStart() {//初始化游戏for (int i = 0;i < MAXY;i++) {for (int j = 0;j < MAXX;j++) {cube[j][i].resetCube();}}setBomb();for (int i = 0;i < MAXY;i++) {for (int j = 0;j < MAXX;j++) {checkAndSetNearBombNumber(j, i);}}}bool player(bool &life) {//玩家输⼊坐标翻开⽅块int x, y;GoTo(STARTX - 3, STARTY + MAXY + 1);printf("请输⼊坐标(x,y),x和y⽤空格隔开");GoTo(STARTX + MAXX / 2, STARTY + MAXY + 2);scanf("%d%d", &x, &y);if ((x < 0) || (x > MAXX - 1) || (y < 0) || (y > MAXY - 1)) {//当玩家输⼊的坐标超出范围时show();GoTo(STARTX - 3, STARTY + MAXY + 3);printf("该坐标不存在,请重新输⼊坐标");GoTo(STARTX + MAXX / 2, STARTY + MAXY + 2);} else if (cube[x][y].getIfHaveBomb() == true) {//当玩家翻开的⽅块有地雷时cube[x][y].setOpen();show();life = false;return false;} else if (cube[x][y].getOpen() == false) {//当玩家翻开的⽅块⽆雷时if (cube[x][y].getNearBombNumber() == 0) {autoOpen(x, y);cube[x][y].setOpen();show();} else {cube[x][y].setOpen();show();}} else if (cube[x][y].getOpen() == true) {//当玩家输⼊已翻开⽅块的坐标时show();GoTo(STARTX, STARTY + MAXY + 3);printf("该⽅块已被挖开,请再次输⼊坐标");GoTo(STARTX + MAXX / 2, STARTY + MAXY + 2);}ifWin();return true;}void message(bool result) {if (result == true) {//玩家胜利时输出的信息showBomb();SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), YELLOW);GoTo(STARTX - 1, STARTY + MAXY + 1);printf("祝贺你,你胜利了!");GoTo(STARTX, STARTY + MAXY + 2);} else {//玩家失败时输出的信息showBomb();SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), PURPLE);GoTo(STARTX - 1, STARTY + MAXY + 1);printf("××你踩中地雷了××");GoTo(STARTX, STARTY + MAXY + 2);}}void autoOpen(int x, int y) {//玩家翻开的⽅块为不含雷且周围⽆雷的⽅块时,⾃动翻开周围⽆雷的⽅块for (int i = -1; i <= 1; i++) {for (int j = -1; j <= 1; j++) {int nx = x + i;int ny = y + j;if (!(ny == y && nx == x) && (nx >= 0 && nx <= MAXX - 1) &&(ny >= 0 && ny <= MAXY - 1) && cube[nx][ny].getOpen() == false) {if (cube[nx][ny].getNearBombNumber() == 0) {cube[nx][ny].setOpen();autoOpen(nx, ny);} else {cube[nx][ny].setOpen();}}}}}bool ifWin() {//判断玩家是否扫雷成功达到游戏结束条件int num = 0;for (int i = 0;i < MAXX;i++) {for (int j = 0;j < MAXY;j++) {if (cube[j][i].getOpen() == false) {num++;}}}if (num == BOMBNUMBER) {return true;} else {return false;}}void showBomb() {//游戏结束后显⽰地雷位置for (int i = 0;i < MAXY;i++) {for (int j = 0;j < MAXX;j++) {if (cube[j][i].getIfHaveBomb() == true) {cube[j][i].setOpen();}}}show();}更多精彩游戏⼩代码,请点击阅读以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

c语言扫雷源代码

c语言扫雷源代码

c语言扫雷源代码扫雷游戏是一种非常经典的单人益智游戏,玩家需要根据数字提示找出地雷的位置。

下面给出一个简单的C语言扫雷游戏的源代码示例:```c#include <stdio.h>#include <stdlib.h>#include <time.h>#define SIZE 10 // 扫雷游戏的大小#define MINE_COUNT 10 // 地雷的数量typedef struct {int x;int y;} Position;typedef struct {int isMine; // 是否是地雷int isFlagged; // 是否被标记为地雷int isRevealed; // 是否已被翻开int adjacentMines; // 相邻地雷的数量} Cell;Cell board[SIZE][SIZE];void initializeBoard() {int i, j;// 初始化游戏面板for (i = 0; i < SIZE; i++) {for (j = 0; j < SIZE; j++) {board[i][j].isMine = 0;board[i][j].isFlagged = 0;board[i][j].isRevealed = 0;board[i][j].adjacentMines = 0;}}}void generateMines() {int i, j;int count = 0;srand(time(NULL)); // 以当前时间作为随机数种子 while (count < MINE_COUNT) {i = rand() % SIZE;j = rand() % SIZE;// 如果该格子已经是地雷,则重新生成随机位置 if (!board[i][j].isMine) {board[i][j].isMine = 1;count++;}}}void calculateAdjacentMines() {int i, j, k, l;int dx[] = {-1, -1, -1, 0, 0, 1, 1, 1};int dy[] = {-1, 0, 1, -1, 1, -1, 0, 1};for (i = 0; i < SIZE; i++) {for (j = 0; j < SIZE; j++) {if (!board[i][j].isMine) {for (k = 0; k < 8; k++) {int ni = i + dx[k];int nj = j + dy[k];if (ni >= 0 && ni < SIZE && nj >= 0 && nj < SIZE && board[ni][nj].isMine) {board[i][j].adjacentMines++;}}}}}}void displayBoard() {int i, j;printf(" ");for (i = 0; i < SIZE; i++) {printf("%d ", i);}printf("\n");for (i = 0; i < SIZE; i++) {printf("%d ", i);for (j = 0; j < SIZE; j++) {if (board[i][j].isRevealed) {if (board[i][j].isMine) {printf("M ");} else {printf("%d ", board[i][j].adjacentMines);}} else if (board[i][j].isFlagged) {printf("F ");} else {printf(". ");}}printf("\n");}}void revealAdjacentEmptyCells(Position pos) {int dx[] = {-1, -1, -1, 0, 0, 1, 1, 1};int dy[] = {-1, 0, 1, -1, 1, -1, 0, 1};int i;for (i = 0; i < 8; i++) {int ni = pos.x + dx[i];int nj = pos.y + dy[i];if (ni >= 0 && ni < SIZE && nj >= 0 && nj < SIZE && !board[ni][nj].isRevealed && !board[ni][nj].isMine) { board[ni][nj].isRevealed = 1;if (board[ni][nj].adjacentMines == 0) {Position newPos;newPos.x = ni;newPos.y = nj;revealAdjacentEmptyCells(newPos);}}}}int main() {Position pos;char cmd;int isSuccess = 0;initializeBoard();generateMines();calculateAdjacentMines();displayBoard();while (!isSuccess) {printf("Enter command (R: reveal, F: flag): ");fflush(stdout);scanf(" %c", &cmd);printf("Enter position (x, y): ");fflush(stdout);scanf("%d %d", &(pos.x), &(pos.y));if (cmd == 'R') {board[pos.x][pos.y].isRevealed = 1;if (board[pos.x][pos.y].isMine) {printf("Game Over!\n");isSuccess = 1;} else if (board[pos.x][pos.y].adjacentMines == 0) {revealAdjacentEmptyCells(pos);}} else if (cmd == 'F') {board[pos.x][pos.y].isFlagged = 1;}displayBoard();}return 0;}```上述代码实现了一个简单的C语言扫雷游戏。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
case WM_LBUTTONDBLCLK:
return OnMButtonDown(m);
default:
return 0;
}
}
void UpdateResult()
{
return ;
}
t[i]=0;
for(i=0;i<totalMine;i++)
{
m=rand()%(COL*ROW);
while(t[m]==1)
{
m=rand()%(COL*ROW);
}
t[m]=1;
}
#ifdef DEBUG
/*调试 用来显示雷区情况*/
#define STARTX 50 /*表示雷区在屏幕上的起始x坐标*/
#define STARTY 50 /*表示雷区在屏幕上的起始y坐标*/
#define SIZEX 20 /*表示一个方块的长度*/
#define SIZEY 20 /*表示一个方块的宽度*/
#define UNFLAG 0 /*表示该方块还没有被打开或者标记*/
m=GetMouseMsg();
/*根据信息进行操作*/
res=GetMessage(m);
}
/*结果更新*/
UpdateResult();
if(res!=0)
break;
}
getch();
closegraph();
return 0;
#include"stdio.h"
#include"stdlib.h"
#include"conio.h"
#include"graphics.h"
#include"time.h"
//#define DEBUG
#define ROW 16 /*表示整个雷区的行数*/
#define COL 16 /*表示整个雷区的列数*/
}
return ;
}
/*初始化数据*/
void InitData()
{
int i,j,m,count,k,ii,jj;
int *t;
t=(int *)(&table[0][0]);
srand((unsigned)time(NULL));
for(i=0;i<COL*ROW;i++)
#define FLAGED 1 /*标记该方块有地雷*/
#define QUESTION 2 /*表示该方块可能有地雷*/
#define EXPLOD 3 /*踩到地雷爆炸了*/
#define OPEN 4 /*一个没有地雷的方块被打开*/
int totalMine=30; /*整个雷区所含地雷总数*/
/*
if(flag[ny][nx]==UNFLAG)
Mark(nx,ny);
else if(flag[ny][nx]==FLAGED)
QMark(nx,ny);
else if(flag[ny][nx]=QUESTION)
{
flag[ny][nx]=UNFLAG;
{
flag[j][i]=UNFLAG;
}
}
return ;
}
/*挖某个位置*/
int Dig(int x,int y)
{
char s[3];
if(table[y][x]==1)
{
setfillstyle(RED);
bar(STARTX+x*SIZEX,STARTY+y*SIZEY,STARTX+(x+1)*SIZEX-2,STARTY+(y+1)*SIZEY-2);
int nx,ny;
if(m.x>STARTX&&m.x<STARTX+SIZEX*COL&&m.y>STARTY&&m.y<STARTY+SIZEY*ROW)
{
//计算位置
nx=(int)(m.x-STARTX)/SIZEX;
ny=(int)(m.y-STARTY)/SIZEY;
}
}
#ifdef DEBUG
for(j=0;j<ROW;j++)
{
for(i=0;i<COL;i++)
{
printf("%d ",num[j][i]);
}
printf("\n");
}
#endif
for(j=0;j<ROW;j++)
{
for(i=0;i<COL;i++)
int main()
{
int res;
MOUSEMSG m;
/*初始化图形区域*/
initgraph(640,480);
/*初始化数据*/
InitDraw();
InitData();
w
{
/*检查鼠标信息*/
{
return 0;
}
int GetMessage(MOUSEMSG m)
{
//鼠标循环
switch(m.uMsg)
{
case WM_LBUTTONDOWN:
return OnLButtonDown(m);
case WM_RBUTTONDOWN:
return OnRButtonDown(m);
for(j=0;j<ROW;j++)
{
for(i=0;i<COL;i++)
{
printf("%d ",table[j][i]);
}
printf("\n");
}
#endif
//printf("\n");
for(j=0;j<ROW;j++)
{
for(i=0;i<COL;i++)
setfillstyle(WHITE);
bar(STARTX+nx*BOXSIZE,STARTY+ny*BOXSIZE,STARTX+(nx+1)*BOXSIZE-2,STARTY+(ny+1)*BOXSIZE-2);
}*/
}
return 0;
}
int OnMButtonDown(MOUSEMSG m)
}
/*画初始图*/
void InitDraw()
{
int i,j;
for(j=0;j<ROW;j++)
for(i=0;i<COL;i++)
{
setfillstyle(WHITE);
bar(STARTX+i*SIZEX,STARTY+j*SIZEY,STARTX+i*SIZEX+SIZEX-2,STARTY+j*SIZEY +SIZEY-2);
setcolor(RED);
outtextxy(STARTX+x*SIZEX+6,STARTY+y*SIZEY+2,s);
return 0;
}
return 0;
}
//左键按下
int OnLButtonDown(MOUSEMSG m)
{
int nx,ny;
if(m.x>STARTX&&m.x<STARTX+SIZEX*COL&&m.y>STARTY&&m.y<STARTY+SIZEY*ROW)
{
//计算位置
nx=(int)(m.x-STARTX)/SIZEX;
ny=(int)(m.y-STARTY)/SIZEY;
return Dig(nx,ny);
}
return 0;
}
//右键按下
int OnRButtonDown(MOUSEMSG m)
{
{
count=0;
for(k=0;k<8;k++)
{
ii=i+di[k];
jj=j+dj[k];
if(ii>=0&&jj>=0&&ii<COL&&jj<ROW&&table[jj][ii]==1)
count++;
}
num[j][i]=count;
int di[8]={-1,-1,0,1,1,1,0,-1};
int dj[8]={0,1,1,1,0,-1,-1,-1};
void InitDraw();
void InitData();
int GetMessage(MOUSEMSG m);
void UpdateResult();
int table[ROW][COL]; /*数组table的每个元素值记录了雷区对应方块是否有累:1有雷,0无雷*/
int num[ROW][COL]; /*数组num的每个元素值记录了雷区对应方块周围有多少个地雷*/
相关文档
最新文档