扫雷小游戏源代码
扫雷游戏部分代码
![扫雷游戏部分代码](https://img.taocdn.com/s3/m/00c5cd32b90d6c85ec3ac6dd.png)
//设置状态#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) //如果在右边界,判断左,上,下有没有雷{····}}。
(完整word版)JAVA课程设计--扫雷游戏
![(完整word版)JAVA课程设计--扫雷游戏](https://img.taocdn.com/s3/m/600df4b831126edb6f1a108a.png)
合肥学院计算机科学与技术系课程设计报告2009~2010学年第二学期课程Java语言与应用课程设计名称扫雷游戏学生姓名胡远远学号0604031005专业班级07网络工程一班指导教师许强张贯虹2010年09月1.设计内容及要求1.1 扫雷游戏的基本要求Windows 2000/XP系统提供的扫雷游戏是一个很有趣的游戏。
本章的课程设计使用Java语言编写一个与其类似的扫雷游戏。
具体要求如下:(1)选择级别后将出现相应级别的扫雷区域,这是用户使用鼠标左键单击雷区中任何一个方块便启动计时器。
(2)用户要揭开某个方块,可单击它。
若所揭方块下有雷,用户便输了这一局,若所揭方块下五雷,则显示一个数字,该数字代表方块的周围的8个方块中共有多少颗雷。
(3) 如果用户认为某个方块下埋着雷,单击右键可以在方块上标识一个用户认为是雷的图标,即给出一个扫雷标记。
用户每标记出一个扫雷标记(无论用户的标记是否正确),程序将显示的剩余雷数减少一个。
(4)扫雷胜利后,显示游戏胜利。
(5) 用户可以右击空格,可以选择标记为“旗帜”、“问号”或者返回成空格。
1.2 需实现的主要功能(1)用户点击笑脸实现复位操作。
调用repaint()和validate()函数对界面进行重置以及刷新操作(2)可以显示用户完全扫雷成功所花时间。
文本框TF记录扫雷成功所花的时间(3)在失败和胜利后跳出失败或胜利的文本框JoptionPane 该类用来调出对话框并提示胜利2.需求分析2.1 扫雷棋盘的布局设计系统的整体布局为:CardLayout布局, 采用了文本框、按钮、面板、框架…等组件,菜单主要有run按钮笑脸和哭脸,按钮的功能是重新开始新的游戏。
2.2 雷区的设计MineArea类是javax.swing包中Jpanel容器的子类,实现了ActionListener 和MouseListener接口,所创建的对象:mineArea是MineGame类中最重要的成员之一,作为一个容器添加到MineGame窗口的中心。
Android的扫雷游戏源代码
![Android的扫雷游戏源代码](https://img.taocdn.com/s3/m/2faf766db84ae45c3b358cbe.png)
}
}
私人无效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())
扫雷游戏代码
![扫雷游戏代码](https://img.taocdn.com/s3/m/3caddd0bba1aa8114431d985.png)
}
/*计算方块周围雷数 */
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语言扫雷程序代码](https://img.taocdn.com/s3/m/fcdf014b336c1eb91a375db3.png)
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) {
扫雷游戏Java源代码
![扫雷游戏Java源代码](https://img.taocdn.com/s3/m/c80cdea6910ef12d2af9e7e2.png)
扫雷游戏Java源代码import java.awt.BorderLayout;import java.awt.Container;import java.awt.Font;import java.awt.GridLayout;import java.awt.Insets;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JPanel;import javax.swing.Timer;public class ScanLei1 extends JFrame implements ActionListener{private static final long serialVersionUID = 1L;private Container contentPane;private JButton btn;private JButton[] btns;private JLabel b1;private JLabel b2;private JLabel b3;private Timer timer;private int row=9;private int col=9;private int bon=10;private int[][] a;private int b;private int[] a1;private JPanel p,p1,p2,p3;public ScanLei1(String title){super(title);contentPane=getContentPane();setSize(297,377);this.setBounds(400, 100, 400, 500);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);timer =new Timer(1000,(ActionListener) this);a = new int[row+2][col+2];initGUI();}public void initGUI(){p3=new JPanel();b=bon;JMenuBar menuBar=new JMenuBar();JMenu menu1=new JMenu("游戏");JMenu menu2=new JMenu("帮助");JMenuItem mi1=new JMenuItem("初级");JMenuItem mi2 = new JMenuItem("中级");JMenuItem mi3 =new JMenuItem("高级");mi1.addActionListener(this);menu1.add(mi1);mi2.addActionListener(this);menu1.add(mi2);mi3.addActionListener(this);menu1.add(mi3);menuBar.add(menu1);menuBar.add(menu2);p3.add(menuBar);b1=new JLabel(bon+"");a1=new int[bon];btn =new JButton("开始");btn.addActionListener(this);b2=new JLabel("0");b3=new JLabel("");btns=new JButton[row*col];p=new JPanel();p.setLayout(new BorderLayout());contentPane.add(p);p.add(p3,BorderLayout.NORTH);//combo=new JComboBox(new Object[]{"初级","中级","高级"} );//加监听/*combo.addItemListener(new ItemListener(){}});*/p1=new JPanel();//在那个位置//(( FlowLayout)p1.getLayout()).setAlignment( FlowLayout.RIGHT);p1.add(b1);p1.add(btn);p1.add(b2);p1.add(b3);p.add(p3,BorderLayout.NORTH);p.add(p1,BorderLayout.CENTER);p2=new JPanel();p2.setLayout(new GridLayout(row,col,0,0));for(int i=0;i<row*col;i++){btns[i]=new JButton("");btns[i].setMargin(new Insets(0,0,0,0));btns[i].setFont(new Font(null,Font.BOLD,25));btns[i].addActionListener(this);btns[i].addMouseListener(new NormoreMouseEvent());p2.add(btns[i]);}contentPane.add(p,BorderLayout.NORTH);contentPane.add(p2,BorderLayout.CENTER);}public void go(){setVisible(true);}public static void main(String[] args){new ScanLei1("扫雷").go();}public void out(int[][] a,JButton[] btns,ActionEvent e,int i,int x,int y){int p=1;if(a[x][y]==0){a[x][y]=10;btns[i].setEnabled(false); //33for(int l=y-1;l<=y+1;l++){int m=x-1-1;int n=l-1;p=1;System.out.println(a[1][2]);if(n>-1&&n<col&&m>-1&&m<row){for(int q=0;q<row&&p==1;q++){//col-->row;if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){if(a[x-1][l]!=0&&a[x-1][l]!=10){btns[n+col*q].setText(a[x-1][l]+"");a[x-1][l]=10;btns[n+col*q].setEnabled(false);}else if(a[x-1][l]==0){//a[x-1][l]=10;btns[n+col*q].setEnabled(false);out(a,btns,e,n+col*q,x-1,l);////55////a[x-1][l]=10;btns[n+col*q].setEnabled(false);}p=0;}}}p=1;m=x;if(n>-1&&n<col&&m>-1&&m<col){for(int q=0;q<row&&p==1;q++){if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){if(a[x+1][l]!=0&&a[x+1][l]!=10){btns[n+col*q].setText(a[x+1][l]+"");a[x+1][l]=10;btns[n+col*q].setEnabled(false);}else if(a[x+1][l]==0){out(a,btns,e,n+col*q,x+1,l);///55////a[x+1][l]=10;btns[n+col*q].setEnabled(false);}p=0;}}}}int m=x-1;int n=y-1-1;if(n>-1&&n<col&&m>-1&&m<col){for(int q=0;q<row&&p==1;q++){if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){if(a[x][y-1]!=0&&a[x][y-1]!=10){btns[n+col*q].setText(a[x][y-1]+"");a[x][y-1]=10;btns[n+col*q].setEnabled(false);}else if(a[x][y-1]==0){out(a,btns,e,n+col*q,x,y-1);a[x][y-1]=10;btns[n+col*q].setEnabled(false);}p=0;}}}p=1;m=x-1;n=y+1-1;if(n>-1&&n<col&&m>-1&&m<col){for(int q=0;q<row&&p==1;q++){if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){if(a[x][y+1]!=0&&a[x][y+1]!=10){btns[n+col*q].setText(a[x][y+1]+"");a[x][y+1]=10;btns[n+col*q].setEnabled(false);}else if(a[x][y+1]==0){out(a,btns,e,n+col*q,x,y+1);a[x][y+1]=10;btns[n+col*q].setEnabled(false);}p=0;}}}}public void actionPerformed(ActionEvent e) {if(e.getActionCommand()=="初级"){row=9;col=9;bon=10;a1=new int[bon];b=bon;//setSize(297,377);a = new int[row+2][col+2];this.remove(p2);timer.stop();b1.setText("10");b2.setText("0");b3.setText("");btns=new JButton[row*col];p2=new JPanel();p2.setLayout(new GridLayout(row,col,0,0));for(int i=0;i<row*col;i++){btns[i]=new JButton(" ");btns[i].setMargin(new Insets(0,0,0,0));btns[i].setFont(new Font(null,Font.BOLD,25));btns[i].addActionListener(this);btns[i].addMouseListener(new NormoreMouseEvent());p2.add(btns[i]);}contentPane.add(p2,BorderLayout.CENTER);//setSize(297,377);this.pack();for(int i=0;i<row*col;i++){btns[i].setText(" ");btns[i].setEnabled(true);}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){a[i][j]=0;}}}else if(e.getActionCommand()=="中级"){row=16;col=16;bon=40;//setSize(33*col,33*row+80);a1=new int[bon];a = new int[row+2][col+2];b=bon;this.remove(p2);timer.stop();b1.setText("40");b2.setText("0");b3.setText("");btns=new JButton[row*col];p2=new JPanel();p2.setLayout(new GridLayout(row,col,0,0));for(int i=0;i<row*col;i++){btns[i]=new JButton(" ");btns[i].setMargin(new Insets(0,0,0,0));btns[i].setFont(new Font(null,Font.BOLD,25));btns[i].addActionListener(this);btns[i].addMouseListener(new NormoreMouseEvent());p2.add(btns[i]);}contentPane.add(p2,BorderLayout.CENTER);this.pack();//setSize(33*col,33*row+80);for(int i=0;i<row*col;i++){btns[i].setText("");btns[i].setEnabled(true);}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){a[i][j]=0;}}}else if(e.getActionCommand()=="高级"){row=16;col=32;bon=99;setSize(33*col,33*row+80);a1=new int[bon];a = new int[row+2][col+2];b=bon;this.remove(p2);timer.stop();b1.setText("99");b2.setText("0");b3.setText("");btns=new JButton[row*col];p2=new JPanel();p2.setLayout(new GridLayout(row,col,0,0));for(int i=0;i<row*col;i++){btns[i]=new JButton(" ");btns[i].setMargin(new Insets(0,0,0,0));btns[i].setFont(new Font(null,Font.BOLD,25));btns[i].addActionListener(this);btns[i].addMouseListener(new NormoreMouseEvent());p2.add(btns[i]);}contentPane.add(p2,BorderLayout.CENTER);//setSize(33*col,33*row+80);this.pack();for(int i=0;i<row*col;i++){btns[i].setText("");btns[i].setEnabled(true);}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){a[i][j]=0;}}}if(e.getSource()==btn){timer.start();b=bon;b3.setText("");//System.out.println(bon);//清空for(int i=0;i<row*col;i++){btns[i].setText("");btns[i].setEnabled(true);}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){a[i][j]=0;}}//产生随机数for(int i=0;i<bon;i++){ int p=1;int m=(int)(Math.random()*row*col);while(p==1){int l=1;int j;for( j=0;j<i&&l==1;j++){if(a1[j]==m){m=(int)(Math.random()*row*col);l=0;}}if(j==i){a1[i]=m;p=0;}}}b1.setText(bon+"");b2.setText("0");//布雷for(int i=0;i<bon;i++){int x=(a1[i]/col+1);int y=(a1[i]%col+1);a[x][y]=100;}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){if(i==0||j==0||i==row+1||j==col+1){a[i][j]=0;}}}for(int i=1;i<=row;i++){for(int j=1;j<=col;j++){if(a[i][j]!=100){for(int l=j-1;l<=j+1;l++){if(a[i-1][l]==100){a[i][j]++;}if(a[i+1][l]==100){a[i][j]++;}}if(a[i][j-1]==100){a[i][j]++;}if(a[i][j+1]==100){a[i][j]++;}}}}}if(e.getSource()==timer){String time=b2.getText().trim();int t=Integer.parseInt(time);//System.out.println(t);if(t>=600){timer.stop();}else{t++;b2.setText(t+"");}}for(int i=0;i<col*row;i++){if(btns[i].getText()!="★"){int x=i/col+1;int y=i%col+1;if(e.getSource()==btns[i]&&a[x][y]==100){btns[i].setText("★");btns[i].setEnabled(false);a[x][y]=10;for(int k=0;k<col*row;k++){int m1=k/col+1;int n1=k%col+1;if(a[m1][n1]!=10&&btns[k].getText()=="★"){btns[k].setText("*o*");}}for(int j=0;j<col*row;j++){int m=j/col+1;int n=j%col+1;if(a[m][n]==100){btns[j].setText("★");btns[j].setEnabled(false);b3.setText("你输了!!");}btns[j].setEnabled(false);a[m][n]=10;}timer.stop();}else if(e.getSource()==btns[i]){if(a[x][y]==0){out(a,btns,e,i,x,y);a[x][y]=10;btns[i].setEnabled(false);}if(a[x][y]!=0&&a[x][y]!=10){btns[i].setText(a[x][y]+"");btns[i].setEnabled(false);a[x][y]=10;}}}else if(btns[i].getText()=="★"){}}}class NormoreMouseEvent extends MouseAdapter{public void mouseClicked(MouseEvent e) {System.out.println(b);for(int i=0;i<col*row;i++){int x1=i/col+1;int y1=i%col+1;if(e.getSource()==btns[i]&&btns[i].getText()!="★"&&a[x1][y1]!=10) {if(e.getButton()==MouseEvent.BUTTON3){btns[i].setText("★");b--;if(b==0){int flag=0;for(int j=0;j<col*row;j++){int x=j/col+1;int y=j%col+1;if(a[x][y]==100&&btns[j].getText()=="★"){flag++;}}if(flag==bon){timer.stop();b3.setText("你赢了!");}}b1.setText(b+"");}}elseif(e.getSource()==btns[i]&&btns[i].getText()=="★"&&a[x1][y1]!=-1){if(e.getButton()==MouseEvent.BUTTON3){btns[i].setText("");b++;if(b>bon){b1.setText(bon+"");}else{b1.setText(b+"");}btns[i].setEnabled(true);}}}}}}。
扫雷游戏代码
![扫雷游戏代码](https://img.taocdn.com/s3/m/b4a3d1980066f5335b812137.png)
扫雷游戏代码Document serial number【UU89WT-UU98YT-UU8CB-UUUT-UUT108】/**/#ifndef BLOCK_H_#define BLOCK_H_#include<QLabel>class QWidget;class Block:public QLabel{Q_OBJECTpublic:explicit Block(bool mine_flag,QWidget*parent=0);void set_number(int number);void turn_over();bool is_mine()const;bool is_turn_over()const;signals:void turn_over(bool is_mine);protected:void mousePressEvent(QMouseEvent*event); private:bool mine_flag_;bool mark_flag_;bool turn_over_flag_;int number_;};#endif#include""#include<QLabel>#include<QMouseEvent>#include<QPixmap>#include<QWidget>Block::Block(bool mine_flag,QWidget*parent) :QLabel(parent){mine_flag_=mine_flag;mark_flag_=false;turn_over_flag_=false;number_=-1;setPixmap(QPixmap(":/images/"));}void Block::set_number(int number){number_=number;}void Block::turn_over(){if(!turn_over_flag_){turn_over_flag_=true;if(mine_flag_)setPixmap(QPixmap(":/images/"));elsesetPixmap(QPixmap(":/images/mine_"+QString("%1").arg(num ber_)+".png"));update();}}bool Block::is_mine()const{return mine_flag_;}bool Block::is_turn_over()const{return turn_over_flag_;}/*鼠标事件的实现*/void Block::mousePressEvent(QMouseEvent*event){if(event->button()==Qt::LeftButton){if(!turn_over_flag_&&!mark_flag_){turn_over_flag_=true;if(mine_flag_==true){setPixmap(QPixmap(":/images/"));update();emit turn_over(true);}else{setPixmap(QPixmap(":/images/mine_"+QString("%1").arg(num ber_)+".png"));update();emit turn_over(false);}}}else if(event->button()==Qt::RightButton){if(!turn_over_flag_){if(!mark_flag_){mark_flag_=true;setPixmap(QPixmap(":/images/"));}else{mark_flag_=false;setPixmap(QPixmap(":/images/"));}update();}}QLabel::mousePressEvent(event);}#ifndef BLOCK_AREA_H_#define BLOCK_AREA_H_#include""#include<QWidget>class QEvent;class QGridLayout;class QObject;class BlockArea:public QWidget{Q_OBJECTpublic:BlockArea(int row,int column,int mine_number,QWidget* parent=0);void set_block_area(int row,int column,intmine_number,int init_flag=false);signals:void game_over(bool is_win);protected:bool eventFilter(QObject*watched,QEvent*event); private slots:void slot_turn_over(bool is_mine);private:int calculate_mines(int x,int y)const;rg(easy_record_time_)),1,1);up_layout->addWidget(new QLabel(easy_record_name_),1,2);up_layout->addWidget(new QLabel(tr("Middle")),2,0);up_layout->addWidget(newQLabel(QString("%1").arg(middle_record_time_)),2,1);up_layout->addWidget(newQLabel(middle_record_name_),2,2);up_layout->addWidget(new QLabel(tr("Hard")),3,0);up_layout->addWidget(newQLabel(QString("%1").arg(hard_record_time_)),3,1);up_layout->addWidget(new QLabel(hard_record_name_),3,2);QPushButton*recount_button=newQPushButton(tr("recount"));QPushButton*close_button=new QPushButton(tr("close"));close_button->setDefault(true);connect(recount_button,SIGNAL(clicked()),&dialog,SLOT(ac cept()));connect(close_button,SIGNAL(clicked()),&dialog,SLOT(reje ct()));QHBoxLayout*bottom_layout=new QHBoxLayout;bottom_layout->addStretch();bottom_layout->addWidget(recount_button);bottom_layout->addWidget(close_button);QVBoxLayout*main_layout=new QVBoxLayout(&dialog);main_layout->addLayout(up_layout);main_layout->addLayout(bottom_layout);if()==QDialog::Accepted){easy_record_time_=middle_record_time_=hard_record_time_= g_no_record_time;easy_record_name_=middle_record_name_=hard_record_name_= g_no_record_name;}}void MainWindow::slot_show_game_toolBar(bool show){if(show)game_toolBar->show();elsegame_toolBar->hide();}void MainWindow::slot_show_statusBar(bool show){if(show)statusBar()->show();elsestatusBar()->hide();}/*游戏的设置容易、中等、困难及自定义*/void MainWindow::slot_standard(QAction*standard_action) {if(standard_action==easy_standard_action){current_standard_=0;row_=9;column_=9;mine_number_=10;}else if(standard_action==middle_standard_action){ current_standard_=1;row_=16;column_=16;mine_number_=40;}else if(standard_action==hard_standard_action){current_standard_=2;row_=16;column_=30;mine_number_=99;}else if(standard_action==custom_standard_action){ QDialog dialog;(tr("set standard"));QSpinBox*row_spinBox=new QSpinBox;row_spinBox->setRange(5,50);row_spinBox->setValue(row_);QSpinBox*column_spinBox=new QSpinBox;column_spinBox->setRange(5,50);column_spinBox->setValue(column_);QSpinBox*mine_spinBox=new QSpinBox;mine_spinBox->setValue(mine_number_);QHBoxLayout*up_layout=new QHBoxLayout;up_layout->addWidget(row_spinBox);up_layout->addWidget(column_spinBox);up_layout->addWidget(mine_spinBox);QDialogButtonBox*dialog_buttonBox=new QDialogButtonBox;dialog_buttonBox->addButton(QDialogButtonBox::Ok);dialog_buttonBox->addButton(QDialogButtonBox::Cancel);connect(dialog_buttonBox,SIGNAL(accepted()),&dialog,SLOT (accept()));connect(dialog_buttonBox,SIGNAL(rejected()),&dialog,SLOT (reject()));QHBoxLayout*bottom_layout=new QHBoxLayout;bottom_layout->addStretch();bottom_layout->addWidget(dialog_buttonBox);QVBoxLayout*main_layout=new QVBoxLayout(&dialog);main_layout->addLayout(up_layout);main_layout->addLayout(bottom_layout);if()==QDialog::Accepted)if(row_spinBox->value()*column_spinBox->value()>mine_spinBox->value()){current_standard_=3;row_=row_spinBox->value();column_=column_spinBox->value();mine_number_=mine_spinBox->value();}}slot_new_game();}/*实现帮助菜单中的关于游戏,及功能*/void MainWindow::slot_about_game(){QString introduction("<h2>"+tr("About Mine Sweepr")+"</h2>"+"<p>"+tr("This game is played by revealing squares of the grid,typically by clicking them with a mouse.If a square containing a mine is revealed,the player loses the game.Otherwise,a digit is revealed in the square,indicating the number of adjacent squares(out of the possible eight)that contain this number is zero then the square appears blank,and the surrounding squares are automatically also revealed.By using logic,the player can in many instances use this information to deduce that certain other squares are mine-free, in which case they may be safely revealed,or mine-filled,in which they can be marked as such(which is effected by right-clicking the square and indicated by a flag graphic).")+"</p>"+"<p>"+tr("This program is free software;you can redistribute it and/or under the terms of the GNU General Public License as published by the Software Foundation;either version3of the License,or(at your option)any later version.")+"</p>"+"<p>"+tr("Please see")+"<a href="+tr("for an overview of GPLv3licensing")+"</p>"+"<br>"+tr("Version:")+g_software_version+"</br>"+"<br>"+tr("Author:")+g_software_author+"</br>");QMessageBoxmessageBox(QMessageBox::Information,tr("About Mine Sweeper"),introduction,QMessageBox::Ok);();}/*游戏的判断,及所给出的提示做出判断*/void MainWindow::slot_game_over(bool is_win){();QString name;if(is_win){switch(current_standard_){case0:if(time_label->text().toInt()<easy_record_time_){name=QInputDialog::getText(this,tr("Please enter your name"),tr("You create a record.Please enter your name"));if(!()){easy_record_time_=time_label->text().toInt();easy_record_name_=name;}}elseQMessageBox::information(this,tr("Result"),tr("You win"));break;case1:if(time_label->text().toInt()<middle_record_time_){name=QInputDialog::getText(this,tr("Please enter your name"),tr("You create a record.Please enter your name"));if(!()){middle_record_time_=time_label->text().toInt();middle_record_name_=name;}}elseQMessageBox::information(this,tr("Result"),tr("You win"));break;case2:if(time_label->text().toInt()<hard_record_time_){name=QInputDialog::getText(this,tr("Please enter your name"),tr("You create a record.Please enter your name"));if(!()){hard_record_time_=time_label->text().toInt();hard_record_name_=name;}}elseQMessageBox::information(this,tr("Result"),tr("You win"));break;default:QMessageBox::information(this,tr("Result"),tr("Y ou win"));}}else{QMessageBox::information(this,tr("Result"),tr("You lose"));}}/*定时器的设置*/void MainWindow::slot_timer(){time_label->setText(QString("%1").arg()/1000));}/*关于菜单栏的设置是否显示游戏工具栏和状态栏*/void MainWindow::read_settings(){QSettings settings;("MainWindow");resize("size").toSize());move("pos").toPoint());bool show_game_toolBar=("showGameToolBar").toBool();show_game_toolBar_action->setChecked(show_game_toolBar);slot_show_game_toolBar(show_game_toolBar);bool show_statusBar=("showStatusBar").toBool();show_statusBar_action->setChecked(show_statusBar);slot_show_statusBar(show_statusBar);();("GameSetting");current_standard_=("current_standard").toInt();switch(current_standard_){case0:easy_standard_action->setChecked(true);break;case1:middle_standard_action->setChecked(true);break;case2:hard_standard_action->setChecked(true);break;case3:custom_standard_action->setChecked(true);break;default:;}row_=("row").toInt()==09:("row").toInt();column_=("column").toInt()==09:("column").toInt();mine_number_=("mine_number").toInt()==010:("mine_number" ).toInt();();("Rank");easy_record_time_=("easy_record_time").toInt()==0g_no_re cord_time:("easy_record_time").toInt();middle_record_time_=("middle_record_time").toInt()==0g_n o_record_time:("middle_record_time").toInt();hard_record_time_=("hard_record_time").toInt()==0g_no_re cord_time:("hard_record_time").toInt();easy_record_name_=("easy_record_name").toString()==""g_n o_record_name:("easy_record_name").toString();middle_record_name_=("middle_record_name").toString()==" "g_no_record_name:("middle_record_name").toString();hard_record_name_=("hard_record_name").toString()==""g_n o_record_name:("hard_record_name").toString();();}void MainWindow::write_settings(){QSettings settings;("MainWindow");("size",size());("pos",pos());("showGameToolBar",show_game_toolBar_action->isChecked());("showStatusBar",show_statusBar_action->isChecked());();("GameSetting");("current_standard",current_standard_);("row",row_);("column",column_);("mine_number",mine_number_);();("Rank");("easy_record_time",easy_record_time_);("middle_record_time",middle_record_time_);("hard_record_time",hard_record_time_);("easy_record_name",easy_record_name_);("middle_record_name",middle_record_name_);("hard_record_name",hard_record_name_);();}/*菜单栏里图片的显示*/void MainWindow::create_actions(){new_game_action=new QAction(QIcon(":/images/"),tr("New Game"),this);new_game_action->setShortcut(QKeySequence::New);connect(new_game_action,SIGNAL(triggered()),this,SLOT(sl ot_new_game()));rank_action=newQAction(QIcon(":/images/"),tr("Rank"),this);connect(rank_action,SIGNAL(triggered()),this,SLOT(slot_r ank()));exit_action=newQAction(QIcon(":/images/"),tr("Exit"),this);exit_action->setShortcut(QKeySequence::Quit);connect(exit_action,SIGNAL(triggered()),this,SLOT(close( )));show_game_toolBar_action=new QAction(tr("Show Game Tool Bar"),this);show_game_toolBar_action->setCheckable(true);connect(show_game_toolBar_action,SIGNAL(toggled(bool)),t his,SLOT(slot_show_game_toolBar(bool)));show_statusBar_action=new QAction(tr("Show Status Bar"),this);show_statusBar_action->setCheckable(true);connect(show_statusBar_action,SIGNAL(toggled(bool)),this ,SLOT(slot_show_statusBar(bool)));easy_standard_action=newQAction(QIcon(":/images/"),tr("Easy"),this);easy_standard_action->setCheckable(true);middle_standard_action=newQAction(QIcon(":/images/"),tr("Middle"),this);middle_standard_action->setCheckable(true);hard_standard_action=newQAction(QIcon(":/images/"),tr("Hard"),this);hard_standard_action->setCheckable(true);custom_standard_action=newQAction(QIcon(":/images/"),tr("Custom"),this);custom_standard_action->setCheckable(true);standard_actionGroup=new QActionGroup(this);standard_actionGroup->addAction(easy_standard_action);standard_actionGroup->addAction(middle_standard_action);standard_actionGroup->addAction(hard_standard_action);standard_actionGroup->addAction(custom_standard_action);connect(standard_actionGroup,SIGNAL(triggered(QAction*)) ,this,SLOT(slot_standard(QAction*)));about_game_action=newQAction(QIcon(":/images/"),tr("About Game"),this);connect(about_game_action,SIGNAL(triggered()),this,SLOT( slot_about_game()));about_qt_action=new QAction(QIcon(":/images/"),tr("About Qt"),this);connect(about_qt_action,SIGNAL(triggered()),qApp,SLOT(ab outQt()));}/*菜单栏的创建*/void MainWindow::create_menus(){game_menu=menuBar()->addMenu(tr("Game"));game_menu->addAction(new_game_action);game_menu->addSeparator();game_menu->addAction(rank_action);game_menu->addSeparator();game_menu->addAction(exit_action);setting_menu=menuBar()->addMenu(tr("Setting"));setting_menu->addAction(show_game_toolBar_action);setting_menu->addAction(show_statusBar_action);setting_menu->addSeparator();setting_menu->addAction(easy_standard_action);setting_menu->addAction(middle_standard_action);setting_menu->addAction(hard_standard_action);setting_menu->addAction(custom_standard_action);help_menu=menuBar()->addMenu(tr("Help"));help_menu->addAction(about_game_action);help_menu->addAction(about_qt_action);}void MainWindow::create_game_toolBar(){game_toolBar=addToolBar(tr("Game Tool Bar"));game_toolBar->setFloatable(false);game_toolBar->setMovable(false);game_toolBar->addAction(new_game_action);game_toolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); }void MainWindow::create_statusBar(){time_label=new QLabel;statusBar()->addPermanentWidget(time_label);statusBar()->addPermanentWidget(newQLabel(tr("second")));}#include""#include<QApplication>#include<QTranslator>int main(int argc,char*argv[]){QApplication app(argc,argv);QTranslator translator;(":/");(&translator);MainWindow window;();return();}。
扫雷小游戏代码c++版
![扫雷小游戏代码c++版](https://img.taocdn.com/s3/m/4da99c8d6529647d272852ac.png)
#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;}}。
java课程设计——扫雷
![java课程设计——扫雷](https://img.taocdn.com/s3/m/b7ec090353d380eb6294dd88d0d233d4b14e3fc6.png)
java课程设计——扫雷⼀、团队课程设计博客链接:⼆、个⼈负责模块或任务说明:模块:⽂件操作 Minefield类实现三、⾃⼰的代码提交记录截图四、⾃⼰负责模块或任务详细说明1.Minefield类实现Minefield是我们主要的算法实现模块。
在正式开始扫雷游戏时,看见的是如下界⾯:⼀格⼀格的蓝⾊格⼦表⽰可点击区域。
点击后,分三个情况:1)标记该区域为雷(右击)2)该区域是点击到雷,游戏结束 3)该区域⽆雷,显⽰区域九宫格范围内的雷的个数。
(此处有9种情况)4)游戏提前结束,显⽰所有未被点击的雷。
下图囊括四种情况:选项区域:这⾥涉及到的保存进度,下条中讲解。
对于以上游戏功能,我们是这样实现的。
先根据所选等级,初始化⼀个map数组,数组的⾏数和列数取决于等级。
然后⽤Math.random()数结合循环语句和判断语句⽣成,将类的区域置9。
其余位置元素值属于0~8,分别表⽰以当前位置为中⼼的九宫格中雷的数⽬。
⾄此,map数组⽣成完毕。
由于游戏界⾯中,真正显⽰出来的状态有13种(0~8九个数字九种,标记该位置为雷、该位置是被点击的雷、游戏成功后未被点击的雷、当前可点击区域各⼀种),⽤map数组来控制游戏界⾯的显⽰会有冲突,所以此处引⼊hiddenmap数组,元素数值范围为0~12,分别表⽰上述13种情况。
对于游戏界⾯,其实是⼀个JButton数组,由于界⾯的美观性,⽤hiddenmap数组值为每个按钮分配图⽚,根据hiddenmap数组值分配对应的功能图⽚。
⽣成雷:⽣成map数组其他位置的数字:for (int i = 0; i < getWidth(); i++)for (int j = 0; j < getLength(); j++) {if (map[i][j] != 9) // 只对不为雷的区域进⾏雷数判断{int number = 0;if (i == 0) {if (j == 0) {if (map[i][j + 1] == 9)number++;if (map[i + 1][j] == 9)number++;if (map[i + 1][j + 1] == 9)number++;} else if (j == getLength() - 1) {if (map[i][j - 1] == 9)number++;if (map[i + 1][j] == 9)number++;if (map[i + 1][j - 1] == 9)number++;} else {if (map[i][j - 1] == 9)number++;if (map[i][j + 1] == 9)number++;if (map[i + 1][j - 1] == 9)number++;if (map[i + 1][j] == 9)number++;if (map[i + 1][j + 1] == 9)number++;}}if (i == getWidth() - 1) {if (j == 0) {if (map[i][j + 1] == 9)number++;if (map[i - 1][j] == 9)number++;if (map[i - 1][j + 1] == 9)number++;} else if (j == getLength() - 1) {if (map[i][j - 1] == 9)number++;if (map[i - 1][j] == 9)number++;if (map[i - 1][j - 1] == 9)number++;} else {if (map[i][j - 1] == 9)number++;if (map[i][j + 1] == 9)number++;if (map[i - 1][j - 1] == 9)number++;if (map[i - 1][j] == 9)number++;if (map[i - 1][j + 1] == 9)number++;}}if (i != 0 && i != (getWidth() - 1)) {if (j == 0) {if (map[i - 1][j + 1] == 9)number++;if (map[i][j + 1] == 9)number++;if (map[i + 1][j + 1] == 9)number++;if (map[i - 1][j] == 9)number++;if (map[i + 1][j] == 9)number++;}if (j == getLength() - 1) {if (map[i - 1][j - 1] == 9)number++;if (map[i][j - 1] == 9)number++;if (map[i + 1][j - 1] == 9)number++;if (map[i - 1][j] == 9)number++;if (map[i + 1][j] == 9)number++;}}if ((i != 0) && (j != 0) && (i != getWidth() - 1) && (j != getLength() - 1)) { // 不在边缘的情况// 单位九宫格内的雷数for (int n = i - 1; n <= i + 1; n++)for (int m = j - 1; m <= j + 1; m++)if (map[n][m] == 9)number++;}map[i][j] = number;}}}所有过程中我们的操作都是对我们的hiddenmap做修改,我们的map是我们的真实雷区不做改动,接下来讲讲核⼼的具体实现。
C语言代码实现简单扫雷小游戏
![C语言代码实现简单扫雷小游戏](https://img.taocdn.com/s3/m/e393c5fbe109581b6bd97f19227916888486b9b7.png)
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");}这个函数是⽤来打印信息的,打印⼀个简单的菜单。
扫雷源代码(精)
![扫雷源代码(精)](https://img.taocdn.com/s3/m/dd30e65b336c1eb91a375d59.png)
#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; // 游戏胜利结束,正确的扫完了所有的雷}。
C语言游戏代码(里面揽括扫雷_俄罗斯方块_推箱子_五子棋_贪吃蛇)
![C语言游戏代码(里面揽括扫雷_俄罗斯方块_推箱子_五子棋_贪吃蛇)](https://img.taocdn.com/s3/m/32e948ec551810a6f52486e8.png)
五子棋#include <stdio.h>#include <bios.h>#include <ctype.h>#include <conio.h>#include <dos.h>#define CROSSRU 0xbf /*右上角点*/#define CROSSLU 0xda /*左上角点*/#define CROSSLD 0xc0 /*左下角点*/#define CROSSRD 0xd9 /*右下角点*/#define CROSSL 0xc3 /*左边*/#define CROSSR 0xb4 /*右边*/#define CROSSU 0xc2 /*上边*/#define CROSSD 0xc1 /*下边*/#define CROSS 0xc5 /*十字交叉点*//*定义棋盘左上角点在屏幕上的位置*/#define MAPXOFT 5#define MAPYOFT 2/*定义1号玩家的操作键键码*/#define PLAY1UP 0x1157/*上移--'W'*/#define PLAY1DOWN 0x1f53/*下移--'S'*/#define PLAY1LEFT 0x1e41/*左移--'A'*/#define PLAY1RIGHT 0x2044/*右移--'D'*/#define PLAY1DO 0x3920/*落子--空格键*//*定义2号玩家的操作键键码*/#define PLAY2UP 0x4800/*上移--方向键up*/#define PLAY2DOWN 0x5000/*下移--方向键down*/ #define PLAY2LEFT 0x4b00/*左移--方向键left*/#define PLAY2RIGHT 0x4d00/*右移--方向键right*/ #define PLAY2DO 0x1c0d/*落子--回车键Enter*//*若想在游戏中途退出, 可按Esc 键*/#define ESCAPE 0x011b/*定义棋盘上交叉点的状态, 即该点有无棋子*//*若有棋子, 还应能指出是哪个玩家的棋子*/#define CHESSNULL 0 /*没有棋子*/#define CHESS1 'O'/*一号玩家的棋子*/#define CHESS2 'X'/*二号玩家的棋子*//*定义按键类别*/#define KEYEXIT 0/*退出键*/#define KEYFALLCHESS 1/*落子键*/#define KEYMOVECURSOR 2/*光标移动键*/#define KEYINV ALID 3/*无效键*//*定义符号常量: 真, 假--- 真为1, 假为0 */#define TRUE 1#define FALSE 0/**********************************************************/ /* 定义数据结构*//*棋盘交叉点坐标的数据结构*/struct point{int x,y;};/**********************************************************/ /*自定义函数原型说明*/void Init(void);int GetKey(void);int CheckKey(int press);int ChangeOrder(void);int ChessGo(int Order,struct point Cursor);void DoError(void);void DoOK(void);void DoWin(int Order);void MoveCursor(int Order,int press);void DrawCross(int x,int y);void DrawMap(void);int JudgeWin(int Order,struct point Cursor);int JudgeWinLine(int Order,struct point Cursor,int direction);void ShowOrderMsg(int Order);void EndGame(void);/**********************************************************//**********************************************************/ /* 定义全局变量*/int gPlayOrder; /*指示当前行棋方*/struct point gCursor; /*光标在棋盘上的位置*/char gChessBoard[19][19];/*用于记录棋盘上各点的状态*//**********************************************************//**********************************************************/ /*主函数*/void main(){int press;int bOutWhile=FALSE;/*退出循环标志*/printf("Welcome ");Init();/*初始化图象,数据*/while(1){press=GetKey();/*获取用户的按键值*/switch(CheckKey(press))/*判断按键类别*/{/*是退出键*/case KEYEXIT:clrscr();/*清屏*/bOutWhile = TRUE;break;/*是落子键*/case KEYFALLCHESS:if(ChessGo(gPlayOrder,gCursor)==FALSE)/*走棋*/DoError();/*落子错误*/else{DoOK();/*落子正确*//*如果当前行棋方赢棋*/if(JudgeWin(gPlayOrder,gCursor)==TRUE){DoWin(gPlayOrder);bOutWhile = TRUE;/*退出循环标志置为真*/}/*否则*/else/*交换行棋方*/ChangeOrder();ShowOrderMsg(gPlayOrder);}break;/*是光标移动键*/case KEYMOVECURSOR:MoveCursor(gPlayOrder,press);break;/*是无效键*/case KEYINV ALID:break;}if(bOutWhile==TRUE)break;}/*游戏结束*/EndGame();}/**********************************************************//*界面初始化,数据初始化*/void Init(void){int i,j;char *Msg[]={"Player1 key:"," UP----w"," DOWN--s"," LEFT--a"," RIGHT-d"," DO----space","","Player2 key:"," UP----up"," DOWN--down"," LEFT--left"," RIGHT-right"," DO----ENTER","","exit game:"," ESC",NULL,/* 先手方为1号玩家*/gPlayOrder = CHESS1;/* 棋盘数据清零, 即棋盘上各点开始的时候都没有棋子*/ for(i=0;i<19;i++)for(j=0;j<19;j++)gChessBoard[i][j]=CHESSNULL;/*光标初始位置*/gCursor.x=gCursor.y=0;/*画棋盘*/textmode(C40);DrawMap();/*显示操作键说明*/i=0;textcolor(BROWN);while(Msg[i]!=NULL){gotoxy(25,3+i);cputs(Msg[i]);i++;}/*显示当前行棋方*/ShowOrderMsg(gPlayOrder);/*光标移至棋盘的左上角点处*/gotoxy(gCursor.x+MAPXOFT,gCursor.y+MAPYOFT);}/*画棋盘*/void DrawMap(void){int i,j;clrscr();for(i=0;i<19;i++)for(j=0;j<19;j++)DrawCross(i,j);}/*画棋盘上的交叉点*/void DrawCross(int x,int y){gotoxy(x+MAPXOFT,y+MAPYOFT); /*交叉点上是一号玩家的棋子*/if(gChessBoard[x][y]==CHESS1) {textcolor(LIGHTBLUE);putch(CHESS1);return;}/*交叉点上是二号玩家的棋子*/if(gChessBoard[x][y]==CHESS2) {textcolor(LIGHTBLUE);putch(CHESS2);return;}textcolor(GREEN);/*左上角交叉点*/if(x==0&&y==0){putch(CROSSLU);return;}/*左下角交叉点*/if(x==0&&y==18){putch(CROSSLD);return;}/*右上角交叉点*/if(x==18&&y==0){putch(CROSSRU);return;}/*右下角交叉点*/if(x==18&&y==18){putch(CROSSRD); return;}/*左边界交叉点*/if(x==0){putch(CROSSL); return;}/*右边界交叉点*/if(x==18){putch(CROSSR); return;}/*上边界交叉点*/if(y==0){putch(CROSSU); return;}/*下边界交叉点*/if(y==18){putch(CROSSD); return;}/*棋盘中间的交叉点*/ putch(CROSS);}/*交换行棋方*/int ChangeOrder(void) {if(gPlayOrder==CHESS1) gPlayOrder=CHESS2; elsegPlayOrder=CHESS1;return(gPlayOrder);}/*获取按键值*/int GetKey(void){char lowbyte;int press;while (bioskey(1) == 0);/*如果用户没有按键,空循环*/press=bioskey(0);lowbyte=press&0xff;press=press&0xff00 + toupper(lowbyte); return(press);}/*落子错误处理*/void DoError(void){sound(1200);delay(50);nosound();}/*赢棋处理*/void DoWin(int Order){sound(1500);delay(100);sound(0); delay(50);sound(800); delay(100);sound(0); delay(50);sound(1500);delay(100);sound(0); delay(50);sound(800); delay(100);sound(0); delay(50);nosound();textcolor(RED+BLINK);gotoxy(25,20);if(Order==CHESS1)cputs("PLAYER1 WIN!");elsecputs("PLAYER2 WIN!");gotoxy(25,21);cputs(" \\<^+^>/");getch();}/*走棋*/int ChessGo(int Order,struct point Cursor){/*判断交叉点上有无棋子*/if(gChessBoard[Cursor.x][Cursor.y]==CHESSNULL){/*若没有棋子, 则可以落子*/gotoxy(Cursor.x+MAPXOFT,Cursor.y+MAPYOFT); textcolor(LIGHTBLUE);putch(Order);gotoxy(Cursor.x+MAPXOFT,Cursor.y+MAPYOFT); gChessBoard[Cursor.x][Cursor.y]=Order;return TRUE;}elsereturn FALSE;}/*判断当前行棋方落子后是否赢棋*/int JudgeWin(int Order,struct point Cursor){int i;for(i=0;i<4;i++)/*判断在指定方向上是否有连续5个行棋方的棋子*/if(JudgeWinLine(Order,Cursor,i))return TRUE;return FALSE;}/*判断在指定方向上是否有连续5个行棋方的棋子*/int JudgeWinLine(int Order,struct point Cursor,int direction) {int i;struct point pos,dpos;const int testnum = 5;int count;switch(direction){case 0:/*在水平方向*/pos.x=Cursor.x-(testnum-1);pos.y=Cursor.y;dpos.x=1;dpos.y=0;break;case 1:/*在垂直方向*/pos.x=Cursor.x;pos.y=Cursor.y-(testnum-1);dpos.x=0;dpos.y=1;break;case 2:/*在左下至右上的斜方向*/pos.x=Cursor.x-(testnum-1);pos.y=Cursor.y+(testnum-1);dpos.x=1;dpos.y=-1;break;case 3:/*在左上至右下的斜方向*/pos.x=Cursor.x-(testnum-1);pos.y=Cursor.y-(testnum-1);dpos.x=1;dpos.y=1;break;}count=0;for(i=0;i<testnum*2+1;i++)/*????????i<testnum*2-1*/ {if(pos.x>=0&&pos.x<=18&&pos.y>=0&&pos.y<=18) {if(gChessBoard[pos.x][pos.y]==Order){count++;if(count>=testnum)return TRUE;}elsecount=0;}pos.x+=dpos.x;pos.y+=dpos.y;}return FALSE;}/*移动光标*/void MoveCursor(int Order,int press) {switch(press){case PLAY1UP:if(Order==CHESS1&&gCursor.y>0) gCursor.y--;break;case PLAY1DOWN:if(Order==CHESS1&&gCursor.y<18) gCursor.y++;break;case PLAY1LEFT:if(Order==CHESS1&&gCursor.x>0) gCursor.x--;break;case PLAY1RIGHT:if(Order==CHESS1&&gCursor.x<18) gCursor.x++;break;case PLAY2UP:if(Order==CHESS2&&gCursor.y>0) gCursor.y--;break;case PLAY2DOWN:if(Order==CHESS2&&gCursor.y<18) gCursor.y++;break;case PLAY2LEFT:if(Order==CHESS2&&gCursor.x>0) gCursor.x--;break;case PLAY2RIGHT:if(Order==CHESS2&&gCursor.x<18) gCursor.x++;break;}gotoxy(gCursor.x+MAPXOFT,gCursor.y+MAPYOFT); }/*游戏结束处理*/void EndGame(void){textmode(C80);}/*显示当前行棋方*/void ShowOrderMsg(int Order){gotoxy(6,MAPYOFT+20);textcolor(LIGHTRED);if(Order==CHESS1)cputs("Player1 go!");elsecputs("Player2 go!");gotoxy(gCursor.x+MAPXOFT,gCursor.y+MAPYOFT); }/*落子正确处理*/void DoOK(void){sound(500);delay(70);sound(600);delay(50);sound(1000);delay(100);nosound();}/*检查用户的按键类别*/int CheckKey(int press){if(press==ESCAPE)return KEYEXIT;/*是退出键*/elseif( ( press==PLAY1DO && gPlayOrder==CHESS1) || ( press==PLAY2DO && gPlayOrder==CHESS2))return KEYFALLCHESS;/*是落子键*/elseif( press==PLAY1UP || press==PLAY1DOWN || press==PLAY1LEFT || press==PLAY1RIGHT || press==PLAY2UP || press==PLAY2DOWN ||press==PLAY2LEFT || press==PLAY2RIGHT)return KEYMOVECURSOR;/*是光标移动键*/elsereturn KEYINV ALID;/*按键无效*/}贪吃蛇#define N 200#include <graphics.h>#include <stdlib.h>#include <dos.h>#define LEFT 0x4b00#define RIGHT 0x4d00#define DOWN 0x5000#define UP 0x4800#define ESC 0x011bint i,key;int score=0;/*得分*/int gamespeed=50000;/*游戏速度自己调整*/ struct Food{int x;/*食物的横坐标*/int y;/*食物的纵坐标*/int yes;/*判断是否要出现食物的变量*/ }food;/*食物的结构体*/struct Snake{int x[N];int y[N];int node;/*蛇的节数*/int direction;/*蛇移动方向*/int life;/* 蛇的生命,0活着,1死亡*/}snake;void Init(void);/*图形驱动*/void Close(void);/*图形结束*/void DrawK(void);/*开始画面*/void GameOver(void);/*结束游戏*/void GamePlay(void);/*玩游戏具体过程*/void PrScore(void);/*输出成绩*//*主函数*/void main(void){Init();/*图形驱动*/DrawK();/*开始画面*/GamePlay();/*玩游戏具体过程*/Close();/*图形结束*/}/*图形驱动*/void Init(void){int gd=DETECT,gm;initgraph(&gd,&gm,"c:\\tc");cleardevice();}/*开始画面,左上角坐标为(50,40),右下角坐标为(610,460)的围墙*/ void DrawK(void){/*setbkcolor(LIGHTGREEN);*/setcolor(11);setlinestyle(SOLID_LINE,0,THICK_WIDTH);/*设置线型*/for(i=50;i<=600;i+=10)/*画围墙*/{rectangle(i,40,i+10,49); /*上边*/rectangle(i,451,i+10,460);/*下边*/}for(i=40;i<=450;i+=10){rectangle(50,i,59,i+10); /*左边*/rectangle(601,i,610,i+10);/*右边*/}}/*玩游戏具体过程*/void GamePlay(void){randomize();/*随机数发生器*/food.yes=1;/*1表示需要出现新食物,0表示已经存在食物*/snake.life=0;/*活着*/snake.direction=1;/*方向往右*/snake.x[0]=100;snake.y[0]=100;/*蛇头*/snake.x[1]=110;snake.y[1]=100;snake.node=2;/*节数*/PrScore();/*输出得分*/while(1)/*可以重复玩游戏,压ESC键结束*/{while(!kbhit())/*在没有按键的情况下,蛇自己移动身体*/{if(food.yes==1)/*需要出现新食物*/{food.x=rand()%400+60;food.y=rand()%350+60;while(food.x%10!=0)/*食物随机出现后必须让食物能够在整格内,这样才可以让蛇吃到*/ food.x++;while(food.y%10!=0)food.y++;food.yes=0;/*画面上有食物了*/}if(food.yes==0)/*画面上有食物了就要显示*/{setcolor(GREEN);rectangle(food.x,food.y,food.x+10,food.y-10);}for(i=snake.node-1;i>0;i--)/*蛇的每个环节往前移动,也就是贪吃蛇的关键算法*/{snake.x[i]=snake.x[i-1];snake.y[i]=snake.y[i-1];}/*1,2,3,4表示右,左,上,下四个方向,通过这个判断来移动蛇头*/switch(snake.direction){case 1:snake.x[0]+=10;break;case 2: snake.x[0]-=10;break;case 3: snake.y[0]-=10;break;case 4: snake.y[0]+=10;break;}for(i=3;i<snake.node;i++)/*从蛇的第四节开始判断是否撞到自己了,因为蛇头为两节,第三节不可能拐过来*/{if(snake.x[i]==snake.x[0]&&snake.y[i]==snake.y[0]){GameOver();/*显示失败*/snake.life=1;break;}}if(snake.x[0]<55||snake.x[0]>595||snake.y[0]<55||snake.y[0]>455)/*蛇是否撞到墙壁*/{GameOver();/*本次游戏结束*/snake.life=1; /*蛇死*/}if(snake.life==1)/*以上两种判断以后,如果蛇死就跳出内循环,重新开始*/ break;if(snake.x[0]==food.x&&snake.y[0]==food.y)/*吃到食物以后*/{setcolor(0);/*把画面上的食物东西去掉*/rectangle(food.x,food.y,food.x+10,food.y-10);snake.x[snake.node]=-20;snake.y[snake.node]=-20;/*新的一节先放在看不见的位置,下次循环就取前一节的位置*/snake.node++;/*蛇的身体长一节*/food.yes=1;/*画面上需要出现新的食物*/score+=10;PrScore();/*输出新得分*/}setcolor(4);/*画出蛇*/for(i=0;i<snake.node;i++)rectangle(snake.x[i],snake.y[i],snake.x[i]+10,snake.y[i]-10);delay(gamespeed);setcolor(0);/*用黑色去除蛇的的最后一节*/rectangle(snake.x[snake.node-1],snake.y[snake.node-1],snake.x[snake.node-1]+10,snake.y[snake.node-1]-10);} /*endwhile(!kbhit)*/if(snake.life==1)/*如果蛇死就跳出循环*/break;key=bioskey(0);/*接收按键*/if(key==ESC)/*按ESC键退出*/break;elseif(key==UP&&snake.direction!=4)/*判断是否往相反的方向移动*/snake.direction=3;elseif(key==RIGHT&&snake.direction!=2)snake.direction=1;elseif(key==LEFT&&snake.direction!=1)snake.direction=2;elseif(key==DOWN&&snake.direction!=3)snake.direction=4;}/*endwhile(1)*/}/*游戏结束*/void GameOver(void){cleardevice();PrScore();setcolor(RED);settextstyle(0,0,4);outtextxy(200,200,"GAME OVER");getch();}/*输出成绩*/void PrScore(void){char str[10];setfillstyle(SOLID_FILL,YELLOW);bar(50,15,220,35);setcolor(6);settextstyle(0,0,2);sprintf(str,"score:%d",score);outtextxy(55,20,str);}/*图形结束*/void Close(void){getch();closegraph();}扫雷游戏/*模拟扫雷游戏*/#include <graphics.h>#include <math.h>#include <stdio.h>#include <dos.h>#include <stdlib.h>#include <conio.h>#include <alloc.h>union REGS regs;int size=15;/*用于表示每个方块的大小(正方形的边长)*/int pix,piy=50;/*pix,piy是矩阵的偏移量*/char b[2]="1";/*用于显示方格周围的雷的个数*/int pan[30][16];/*用于记录盘面的情况:0:没有、9:有雷、1~8:周围雷的个数*/int pan1[30][16];/*pan1[][]纪录当前的挖雷情况,0:没有操作、1:打开了、2:标记了*/int tt;/*纪录时间参数*/int Eflags;/*用于标记鼠标按钮的有效性,0:有效,1:无效,2:这是鼠标的任意键等于重新开始*/int Msinit();void Draw(int x,int y,int sizex,int sizey);void Facedraw(int x,int y,int sizel,int k);void Dead(int sizel,int x,int y);void Setmouse(int xmax,int ymax,int x,int y);int Msread(int *xp,int *yp,int *bup,struct time t1,int k);void Draw1(int x,int y);int Open(int x,int y);float Random();void Have(int sum,int x,int y,int xx,int yy);void Help();void Coread();void Ddraw2(int x,int y);/*下面是主函数*/main(){int mode=VGAHI,devices=VGA;/*图形模式初始化的变量*/char ams; /*鼠标操作中的标志变量*/int xms,yms,bms; /*鼠标的状态变量*/int i,j,k,k1=0; /*i,j,k是循环变量*/int x=9,y=9,flags=0; /*x,y矩阵的大小*/int sum=10; /*sum 盘面的雷的总数目,是个x,y的函数*/int x1=0,y1=0; /*用于记录光标当前的位置*/int x11=0,y11=0; /*暂时保存鼠标位置的值*/int sizel=10; /*脸的大小*/int cflags=1; /*这是菜单操作标志变量,没有弹出1,弹出0*/struct time t1={0,0,0,0}; /*时间结构体,头文件已定义*/int co[3]; /*暂时纪录历史纪录*/void far *Map; /*用于保存鼠标图片*/char name[3][20]; /*名字字符串,用于记录名字*/FILE * p; /*文件指针用于文件操作*/Msinit(); /*鼠标初始化*//*registerbgidriver(EGA VGA_driver);*/initgraph(&devices,&mode,"C:\\tc"); /*图形模式初始化*//*为图片指针分配内存*/if((Map=farmalloc(imagesize(0,0,20,20)))==NULL)/*图片的大小是20*20*/{printf("Memory ererr!\n");printf("Press any key to out!\n");exit(1);}/*用于检验文件是否完整*/while((p = fopen("score.dat", "r")) == NULL) /*如果不能打开就新建一个*/{if((p = fopen("score.dat", "w")) == NULL)/*如果不能新建就提示错误并推出*/{printf("The file cannot open!\n");printf("Presss any key to exit!\n");getch();exit(1);}/*写入初始内容*/fprintf(p,"%d %d %d,%s\n%s\n%s\n",999,999,999,"xiajia","xiajia","xiajia");fclose(p);}/*暂时读出历史纪录。
扫雷游戏
![扫雷游戏](https://img.taocdn.com/s3/m/b7ba24f9c8d376eeaeaa3191.png)
题目三扫雷游戏3.1 题目简介本程序是用java语言在My Eclipse运行环境下编写的一个扫雷小游戏。
程序的功能是在运行后生成指定的地雷个数,在鼠标左键点击下寻找地雷,右键点击下标记地雷,点击重新开始的按钮重新开始一盘新游戏,并给出胜利和失败的条件:标出所有的地雷和左键点中地雷。
当左键点击雷区事,游戏开始,计时器自动启动,通过左键单击即可挖开方块。
如果挖出的是地雷,则输掉游戏;如果方块上出现数字,则表示在其周围的八个方块中共有多少颗地雷,要标记您认为可能有地雷的方块,请右键单击。
游戏区包括雷区、地雷计数器和计时器。
3.2 设计的内容、要求和目标●设计内容:扫雷游戏分为初级中级和高级三个级别,扫雷英雄榜上存储了每个级别的最好成绩,即挖出全部的地雷且用时最少者。
单击游戏难度可以选择“初级”、“中级”、“高级”和“随机”四个级别,单击英雄榜可以查询本级别最好的成绩。
●设计要求和目标:(1)选择级别后将出现相应级别的扫雷区域,这时用户使用鼠标左方块键单击雷区中任何一个方块启动计时器。
(2)用户要揭开某个方块,可左键单击该方块,若所揭方块下有雷,用户则输了这一局,若所揭方块下无雷,则显示一个数字,该数字表示方块周围的8个方块中共有多少颗雷。
(3)如果用户认为某个方块下埋着雷,单击右键可以在方块上标记一个雷的图标,即给出一个扫雷标记。
用户每标记出一个扫雷标记,程序将显示的剩余雷数减少一个。
(4)扫雷胜利后,程序弹出保存成绩的对话框。
(5)用户可以自定义级别并且可以任意输入雷数。
(6)游戏具有计时功能,即显示用户完成游戏所用的时间。
(7)游戏完成后弹出若打破原有的记录,则将该次游戏时间记入扫雷英雄榜。
3.3 总体设计本程序共有Block.java、BlockView.java、Help.ava、LayMines.java、MineArea.java、MineGame.java、Record.java和ShowRecord.java八个源文件。
C语言程序设计扫雷游戏
![C语言程序设计扫雷游戏](https://img.taocdn.com/s3/m/321418bb3169a4517723a3de.png)
C语言程序设计报告题目: 扫雷小游戏设计电子通信与物理学院日期: 2018 年 7 月 12 日指导教师评语目录1. 课程设计容 (1)2. 课程设计目的 (1)3. 背景知识 (1)4. 工具/准备工作 (3)5. 设计步骤、方法 (3)5.1 (3)5.2定义全局变量 (4)5.3挖雷部分函数的分析 (5)6. 设计结果及分析 (11)7. 设计结论 (16)8. 参考文献 (17)附录 (17)1. 课程设计容在计算机逐步渗入社会生活各个层面的今天,计算机已经成为人们日常生活的一分,越来越多的人使用计算机办公、娱乐等等。
扫雷游戏是Windows操作系统自带的一款小游戏,在过去的几年里,Windows操作系统历经数次换代更新,变得越来越庞大、复杂,功能也越来越强大,但是这款小游戏依然保持原来的容貌,可见这款小游戏受到越来越多人的喜爱。
我利用C-free编写了与它功能相仿的挖地雷游戏,寓学于乐。
即:设计一个功能与Windows中的挖雷游戏相同的小游戏。
2. 课程设计目的1.培养学生综合运用所学知识独立完成课题的能力。
2.试学生更深入地理解和掌握该课程中的有关基本概念,程序设计思想和方法。
3.提高对工作认真负责、一丝不苟,对同学团结友爱,协作攻关的基本素质。
4.培养勇于探索、严谨推理、实事、有错必改,用实践来检验理论,全方位考虑问题等科学技术人员应具有的素质。
5.培养从资料文献、科学实验中获得知识的能力,提高从别人经验中找到解决问题的新途径的悟性,初步培养工程意识和创新能力。
6.对掌握知识的深度、运用理论去处理问题的能力、实验能力、课程设计能力、书面及口头表达能力进行考核3. 背景知识游戏区包括雷区、地雷计数器(位于左上角,记录剩余地雷数)和计时器(位于右上角,记录游戏时间),确定大小的矩形雷区中随机布置一定数量的地雷(初级为9*9个方块10个雷,中级为16*16个方块40个雷,高级为16*30个方块99个雷,自定义级别可以自己设定雷区大小和雷数,但是雷区大小不能超过24*30),玩家需要尽快找出雷区中的所有不是地雷的方块,而不许踩到地雷。
c语言编写扫雷代码
![c语言编写扫雷代码](https://img.taocdn.com/s3/m/645e35a8541810a6f524ccbff121dd36a32dc4c3.png)
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库来创建窗口、处理事件和渲染图形。
C++程序设计 第五次作业 扫雷游戏
![C++程序设计 第五次作业 扫雷游戏](https://img.taocdn.com/s3/m/7cd129f10975f46527d3e167.png)
抄袭扣分,如果比对代码完全相同,得分/雷同份数
(加到100分为止)
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <iomanip>
#define random(x) (rand()%x)
(pmap+width*h+w)->setmine(1);//设置为地雷
}
}
void Map::putnum()//设置cell中num的值
{
int i,j,w,h;
for(i=0;i<height;i++)
for(j=0;j<width;j++)//遍历每一个格子
{
if((pmap+width*i+j)->getmine()!=1)
cout<<"Please input:";
cin>>a;
if(a=='d')//挖雷
{
do
{
cout<<"Please input location X (0-"<<width-1<<"):";
cin>>x;
cout<<"Please input location Y (0-"<<height-1<<"):";
void coutmap(int b);//打印界面
visual studio 2010 扫雷游戏API的实现方法
![visual studio 2010 扫雷游戏API的实现方法](https://img.taocdn.com/s3/m/de7c690df78a6529647d5388.png)
经典扫雷游戏C++API函数的实现方法扫雷对大家来说应该是非常熟悉和经典的游戏之一了,但是这样一个看似简单的小游戏是如何实现的呢?其实方法有很多种,相信我们大家都学过C++,我就先提供一种利用C++中的API函数实现扫雷的方法。
代码使用说明:游戏实现后的功能,鼠标左键单击掀开未知区域,鼠标右键单击设置标记,鼠标中间滑轮单击实现自动翻开功能。
1首先打开Visual Studio 2010软件;2点击文件->新建->项目3选择Win32中的Win32项目:4确定后点击“下一步”:如下图中勾选,点击完成即可:5点击视图主菜单(View)->解决方案资源管理器:6在右侧的解决方案资源管理器中的头文件文件夹中添加下面的头文件(.h),在源文件文件夹下添加下面的源文件(.cpp文件)以下是实现的各部分代码:首先我们来写程序的入口程序WinMain函数:文档命名为WinMain.cpp#include"proc.h"#include"caculate.h"extern char co[xk][yk];extern char th[xk][yk];int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInst,LPSTR lpszCmdLine,int nCmdShow){creat(th);num(th);cover(th,co);MSG Msg ;if(!InitWindowsClass(hInstance))return FALSE;if(!InitWindows(hInstance,nCmdShow))return FALSE;//-----------------消息循环----------------------while( GetMessage(&Msg, NULL, 0, 0)){TranslateMessage( &Msg) ;DispatchMessage( &Msg) ;}return Msg.wParam;//消息循环结束即程序终止时将信息返回系统}由于Windows是基于消息的传递机制,所以接下来编写过程处理函数:命名为Proc.cpp#include"proc.h"#include"caculate.h"extern int record[xk][yk]={0}; //记录窗口的图形状态0为关闭、1为开启、2为占旗extern char co[xk][yk];extern char th[xk][yk];extern int xs,ys;extern int tn;void print(char co[xk][yk],HWND hWnd,int ini_x,int ini_y,int width,int height,int cir_len);long WINAPI WndProc(HWND hWnd,UINT iMessage,UINT wParam,LONG lParam){intwidth=d_width,height=d_height,ini_x=d_ini_x,ini_y=d_ini_y,cir_len=8,mine_x=ys,mine_y=xs,cyc_ x,cyc_y;int move_x,move_y,record_i,record_j,flag;int test_x,test_y;WORD mouse_x,mouse_y;HDC hDC; //定义指向设备的句柄HBRUSH hBrush,hB; //定义指向画刷的句柄HPEN hPen;//定义指向画笔的句柄PAINTSTRUCT PtStr;//定义指向包含绘图信息的结构体变量WORD x,y;HCURSOR hCursor;TEXTMETRIC tm;wchar_t lpsz1[]=L"重新开局",lpsz2[]=L"重试本局",lpsz[3],lpsz_text[]=L"剩余标记数:";int i,j; //揭开时的坐标switch(iMessage) //处理消息{case WM_MOUSEMOVE:x=LOWORD(lParam);y=HIWORD(lParam);if(x>=ini_x&&x<=ini_x+width*mine_x&&y>=ini_y&&y<=ini_y+height*mine_y){hCursor=LoadCursor(NULL,IDC_CROSS);SetCursor(hCursor);}/*if(x>=20+2*d_ini_x+ys*d_width&&x<=20+2*d_ini_x+ys*d_width+70&&y>=10&&y<=10+hei ght){hDC=GetDC(hWnd);SetMapMode(hDC,MM_ANISOTROPIC); //设置映像模式hPen=(HPEN)GetStockObject(BLACK_PEN);//黑色画笔hB=(HBRUSH)GetStockObject(DKGRAY_BRUSH); //画刷SelectObject(hDC,hB); //选择画刷SelectObject(hDC,hPen); //选择画笔RoundRect(hDC,20+2*d_ini_x+ys*d_width,10,20+2*d_ini_x+ys*d_width+70,10+height,cir_len,cir _len);EndPaint(hWnd,&PtStr); //结束绘图hDC=GetDC(hWnd);SetMapMode(hDC,MM_ANISOTROPIC); //设置映像模式SetTextColor(hDC,RGB(255,233,0));GetTextMetrics(hDC,&tm);TextOut(hDC,20+2*d_ini_x+ys*d_width+2,10+2,lpsz1,4);EndPaint(hWnd,&PtStr); //结束绘图}*/return 0;case WM_PAINT: //处理绘图消息hDC=BeginPaint(hWnd,&PtStr);SetMapMode(hDC,MM_ANISOTROPIC); //设置映像模式hPen=(HPEN)GetStockObject(BLACK_PEN);//黑色画笔hB=(HBRUSH)GetStockObject(DKGRAY_BRUSH); //画刷SelectObject(hDC,hB); //选择画刷SelectObject(hDC,hPen); //选择画笔for(cyc_x=0;cyc_x<mine_y;cyc_x++){for(cyc_y=0;cyc_y<mine_x;cyc_y++){RoundRect(hDC,ini_x+cyc_y*width,ini_y+cyc_x*height,ini_x+cyc_y*width+width,ini_y+cyc_x*hei ght+height,cir_len,cir_len); //绘制圆角矩形}}print(co,hWnd,ini_x,ini_y,width,height,cir_len);//按钮EndPaint(hWnd,&PtStr); //结束绘图hDC=GetDC(hWnd);SetMapMode(hDC,MM_ANISOTROPIC); //设置映像模式hPen=(HPEN)GetStockObject(BLACK_PEN);//黑色画笔hB=(HBRUSH)GetStockObject(WHITE_BRUSH); //画刷SelectObject(hDC,hB); //选择画刷SelectObject(hDC,hPen); //选择画笔RoundRect(hDC,20+2*d_ini_x+ys*d_width,10,20+2*d_ini_x+ys*d_width+70,10+height,cir_len,cir _len);RoundRect(hDC,20+2*d_ini_x+ys*d_width,50,20+2*d_ini_x+ys*d_width+70,50+height,cir_len,cir _len);EndPaint(hWnd,&PtStr); //结束绘图//按钮hDC=GetDC(hWnd);SetMapMode(hDC,MM_ANISOTROPIC); //设置映像模式SetTextColor(hDC,RGB(255,233,0));GetTextMetrics(hDC,&tm);TextOut(hDC,20+2*d_ini_x+ys*d_width+2,10+2,lpsz1,4);TextOut(hDC,20+2*d_ini_x+ys*d_width+2,50+2,lpsz2,4);EndPaint(hWnd,&PtStr); //结束绘图*/return 0;case WM_LBUTTONUP:mouse_x=LOWORD(lParam);mouse_y=HIWORD(lParam);test_x=(mouse_x+ini_x)/25-1;test_y=(mouse_y+ini_y)/25-1;move_x=((mouse_x+ini_x)/25-1)*width+ini_x;move_y=((mouse_y+ini_y)/25-1)*height+ini_y;if(mouse_x>=20+2*d_ini_x+ys*d_width&&mouse_x<=20+2*d_ini_x+ys*d_width+70&&mouse_y >=50&&mouse_y<=50+height){cover(th,co);for(record_i=0;record_i<mine_y;record_i++)for(record_j=0;record_j<mine_x;record_j++)record[record_i][record_j]=0;hDC=GetDC(hWnd);SetMapMode(hDC,MM_ANISOTROPIC); //设置映像模式hPen=(HPEN)GetStockObject(BLACK_PEN);//黑色画笔hB=(HBRUSH)GetStockObject(DKGRAY_BRUSH); //画刷SelectObject(hDC,hB); //选择画刷SelectObject(hDC,hPen); //选择画笔for(cyc_x=0;cyc_x<mine_y;cyc_x++){for(cyc_y=0;cyc_y<mine_x;cyc_y++){RoundRect(hDC,ini_x+cyc_y*width,ini_y+cyc_x*height,ini_x+cyc_y*width+width,ini_y+cyc_x*hei ght+height,cir_len,cir_len); //绘制圆角矩形}}}if(mouse_x>=20+2*d_ini_x+ys*d_width&&mouse_x<=20+2*d_ini_x+ys*d_width+70&&mouse_y >=10&&mouse_y<=10+height){creat(th);num(th);cover(th,co);for(record_i=0;record_i<mine_y;record_i++)for(record_j=0;record_j<mine_x;record_j++)record[record_i][record_j]=0;hDC=GetDC(hWnd);SetMapMode(hDC,MM_ANISOTROPIC); //设置映像模式hPen=(HPEN)GetStockObject(BLACK_PEN);//黑色画笔hB=(HBRUSH)GetStockObject(DKGRAY_BRUSH); //画刷SelectObject(hDC,hB); //选择画刷SelectObject(hDC,hPen); //选择画笔for(cyc_x=0;cyc_x<mine_y;cyc_x++){for(cyc_y=0;cyc_y<mine_x;cyc_y++){RoundRect(hDC,ini_x+cyc_y*width,ini_y+cyc_x*height,ini_x+cyc_y*width+width,ini_y+cyc_x*hei ght+height,cir_len,cir_len); //绘制圆角矩形}}}if(mouse_x>=ini_x&&mouse_x<=ini_x+width*mine_x&&mouse_y>=ini_y&&mouse_y<=ini_y+hei ght*mine_y){if(record[test_y][test_x]==0){//record[test_y][test_x]=1;hDC=GetDC(hWnd);SetMapMode(hDC,MM_ANISOTROPIC); //设置映像模式hPen=(HPEN)GetStockObject(BLACK_PEN);//黑色画笔hB=(HBRUSH)GetStockObject(WHITE_BRUSH); //画刷SelectObject(hDC,hB); //选择画刷SelectObject(hDC,hPen); //选择画笔RoundRect(hDC,move_x,move_y,move_x+width,move_y+height,cir_len,cir_len);EndPaint(hWnd,&PtStr); //结束绘图//揭开//cover(th,co);i=test_y;j=test_x; //获取揭开坐标if(th[i][j]=='*'){copy(th,co);print(co,hWnd,ini_x,ini_y,width,height,cir_len);for(record_i=0;record_i<mine_y;record_i++)for(record_j=0;record_j<mine_x;record_j++)record[record_i][record_j]=1;}else{if(th[i][j]==0){open(th,co,i,j);print(co,hWnd,ini_x,ini_y,width,height,cir_len);}else{co[i][j]=th[i][j];print(co,hWnd,ini_x,ini_y,width,height,cir_len);}}//揭开*/}/*else if(record[test_y][test_x]==2){record[test_y][test_x]=0;hDC=GetDC(hWnd);SetMapMode(hDC,MM_ANISOTROPIC); //设置映像模式左键取消标记代码hPen=(HPEN)GetStockObject(BLACK_PEN);//黑色画笔hB=(HBRUSH)GetStockObject(DKGRAY_BRUSH); //画刷SelectObject(hDC,hB); //选择画刷SelectObject(hDC,hPen); //选择画笔RoundRect(hDC,ini_x+width*test_x,ini_y+height*test_y,ini_x+width*test_x+width,ini_y+height*t est_y+height,cir_len,cir_len);EndPaint(hWnd,&PtStr);}*/}return 0;case WM_RBUTTONDOWN:mouse_x=LOWORD(lParam);mouse_y=HIWORD(lParam);test_x=(mouse_x+ini_x)/25-1;test_y=(mouse_y+ini_y)/25-1;move_x=((mouse_x+ini_x)/25-1)*width+ini_x;move_y=((mouse_y+ini_y)/25-1)*height+ini_y;if(mouse_x>=ini_x&&mouse_x<=ini_x+width*mine_x&&mouse_y>=ini_y&&mouse_y<=ini_y+hei ght*mine_y){if(record[test_y][test_x]==0){hDC=GetDC(hWnd);record[test_y][test_x]=2;SetMapMode(hDC,MM_ANISOTROPIC); //设置映像模式hPen=(HPEN)GetStockObject(BLACK_PEN);//黑色画笔hB=(HBRUSH)GetStockObject(WHITE_BRUSH);SelectObject(hDC,hB); //选择画刷SelectObject(hDC,hPen); //选择画笔Pie(hDC,move_x+2,move_y+2,move_x+25,move_y+25,move_x+2,move_y+2,move_x+2,move_y+ 2);EndPaint(hWnd,&PtStr);}else if(record[test_y][test_x]==2){record[test_y][test_x]=0;hDC=GetDC(hWnd);SetMapMode(hDC,MM_ANISOTROPIC); //设置映像模式hPen=(HPEN)GetStockObject(BLACK_PEN);//黑色画笔hB=(HBRUSH)GetStockObject(DKGRAY_BRUSH); //画刷SelectObject(hDC,hB); //选择画刷SelectObject(hDC,hPen); //选择画笔RoundRect(hDC,ini_x+width*test_x,ini_y+height*test_y,ini_x+width*test_x+width,ini_y+height*t est_y+height,cir_len,cir_len);EndPaint(hWnd,&PtStr);}}flag=0;for(record_i=0;record_i<mine_y;record_i++)for(record_j=0;record_j<mine_x;record_j++){if(record[record_i][record_j]==2) flag++;}flag=tn-flag;lpsz[0]=flag/100+48;lpsz[1]=(flag%100)/10+48;lpsz[2]=flag%10+48;hDC=GetDC(hWnd);SetMapMode(hDC,MM_ANISOTROPIC); //设置映像模式SetTextColor(hDC,RGB(0,0,234));GetTextMetrics(hDC,&tm);TextOut(hDC,20+2*d_ini_x+ys*d_width+2,80+2,lpsz_text,5);TextOut(hDC,20+2*d_ini_x+ys*d_width+2,120+2,lpsz,3);return 0;case WM_MBUTTONDOWN:mouse_x=LOWORD(lParam);mouse_y=HIWORD(lParam);test_x=(mouse_x+ini_x)/25-1;test_y=(mouse_y+ini_y)/25-1;move_x=((mouse_x+ini_x)/25-1)*width+ini_x;move_y=((mouse_y+ini_y)/25-1)*height+ini_y;if(record[test_y][test_x]==1){if(intelligence(record,th,test_x,test_y)){for(i=test_y-1,j=test_x-1;j<=test_x+1;j++){if(i<0||j<0||i>=xs|j>=ys) continue;if(record[i][j]!=1&&record[i][j]!=2){co[i][j]=th[i][j];if(th[i][j]==0)open(th,co,i,j);print(co,hWnd,ini_x,ini_y,width,height,cir_len);}}for(j--,i++;i<=test_y+1;i++){if(i<0||j<0||i>=xs|j>=ys) continue;if(record[i][j]!=1&&record[i][j]!=2){co[i][j]=th[i][j];if(th[i][j]==0)open(th,co,i,j);print(co,hWnd,ini_x,ini_y,width,height,cir_len);}}for(i--,j--;j>=test_x-1;j--){if(i<0||j<0||i>=xs|j>=ys) continue;if(record[i][j]!=1&&record[i][j]!=2){co[i][j]=th[i][j];if(th[i][j]==0)open(th,co,i,j);print(co,hWnd,ini_x,ini_y,width,height,cir_len);}}for(j++,i--;i>=test_y;i--){if(i<0||j<0||i>=xs|j>=ys) continue;if(record[i][j]!=1&&record[i][j]!=2){co[i][j]=th[i][j];if(th[i][j]==0)open(th,co,i,j);print(co,hWnd,ini_x,ini_y,width,height,cir_len);}}}}return 0;case WM_DESTROY: //结束应用程序PostQuitMessage(0); return 0;default://其他消息处理程序return(DefWindowProc(hWnd,iMessage,wParam,lParam)) ;}}void print(char co[xk][yk],HWND hWnd,int ini_x,int ini_y,int width,int height,int cir_len){TEXTMETRIC tm;HBRUSH hBrush,hB; //定义指向画刷的句柄HPEN hPen;//定义指向画笔的句柄HDC hDC; //定义指向设备的句柄PAINTSTRUCT PtStr;//定义指向包含绘图信息的结构体变量wchar_t lpsz[1];int i,j;for(i=0;i<xs;i++){for(j=0;j<ys;j++){lpsz[0]=co[i][j]+48;if(lpsz[0]>=48&&lpsz[0]<=57&&record[i][j]!=1){hDC=GetDC(hWnd);SetMapMode(hDC,MM_ANISOTROPIC); //设置映像模式hPen=(HPEN)GetStockObject(BLACK_PEN);//黑色画笔hB=CreateHatchBrush(NULL,RGB(204,255,0)); //画刷SelectObject(hDC,hB); //选择画刷SelectObject(hDC,hPen); //选择画笔RoundRect(hDC,ini_x+j*width,ini_y+i*height,ini_x+j*width+width,ini_y+i*height+height,cir_len,c ir_len);EndPaint(hWnd,&PtStr); //结束绘图if(lpsz[0]!=48){hDC=GetDC(hWnd);SetMapMode(hDC,MM_ANISOTROPIC); //设置映像模式if(lpsz[0]==49)SetTextColor(hDC,RGB(0,0,234));else if(lpsz[0]==50)SetTextColor(hDC,RGB(0,123,0));elseSetTextColor(hDC,RGB(245,0,0));GetTextMetrics(hDC,&tm);TextOut(hDC,ini_x+j*width+2,ini_y+i*height+2,lpsz,1);}record[i][j]=1;}else if(lpsz[0]==90&&record[i][j]!=1){hDC=GetDC(hWnd);SetMapMode(hDC,MM_ANISOTROPIC); //设置映像模式hPen=(HPEN)GetStockObject(BLACK_PEN);//黑色画笔hB=(HBRUSH)GetStockObject(WHITE_BRUSH); //画刷SelectObject(hDC,hB); //选择画刷SelectObject(hDC,hPen); //选择画笔RoundRect(hDC,ini_x+j*width,ini_y+i*height,ini_x+j*width+width,ini_y+i*height+height,cir_len,c ir_len);EndPaint(hWnd,&PtStr); //结束绘图hDC=GetDC(hWnd);hPen=(HPEN)GetStockObject(BLACK_PEN);//黑色画笔hB=(HBRUSH)GetStockObject(BLACK_BRUSH); //画刷SelectObject(hDC,hB); //选择画刷SelectObject(hDC,hPen); //选择画笔Pie(hDC,ini_x+j*width,ini_y+i*height,ini_x+j*width+width,ini_y+i*height+height,ini_x+j*width,ini _y+i*height,ini_x+j*width,ini_y+i*height);EndPaint(hWnd,&PtStr); //结束绘图record[i][j]=1;}else continue;}}}接下来是游戏软件Windows界面的初始化函数:命名为initwindow.cpp #include"proc.h"#include"caculate.h"#include"resource2.h"extern int xs,ys;BOOL InitWindowsClass(HINSTANCE hInstance){WNDCLASS wndclass ;wchar_t lpszClassName[]=L"窗口";//窗口类名wchar_t lpszTitle[]=L"miner_sweep";//窗口标题名wchar_t lpszMenuName[]=L"IDR_MENU1";//窗口类的定义wndclass.style=0;//窗口类型为缺省类型wndclass.lpfnWndProc=WndProc;//定义窗口处理函数wndclass.cbClsExtra=0;//窗口类无扩展wndclass.cbWndExtra=0;//窗口实例无扩展wndclass.hInstance=hInstance;//当前实例句柄wndclass.hIcon=LoadIcon(NULL,IDI_APPLICATION);//窗口的最小化图标为缺省图标wndclass.hCursor=LoadCursor(NULL,IDC_ARROW) ;//窗口采用箭头光标wndclass.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH);//窗口背景为白色wndclass.lpszMenuName=lpszMenuName;//窗口中无菜单wndclass.lpszClassName=lpszClassName ;//窗口类名为"窗口"//---------------以下进行窗口类的注册-------return RegisterClass( &wndclass);}BOOL InitWindows(HINSTANCE hInstance,int nCmdShow){HWND hwnd ;wchar_t lpszClassName[]=L"窗口";//窗口类名wchar_t lpszTitle[]=L"miner_sweep";//窗口标题名hwnd=CreateWindowW(lpszClassName,//窗口类名lpszTitle,//窗口实例的标题名WS_OVERLAPPEDWINDOW,//窗口的风格100,100,//窗口左上角坐标为缺省值20+2*d_ini_x+ys*d_width+130,40+2*d_ini_y+xs*d_height,//窗口的高和宽为缺省值NULL,//此窗口无父窗口NULL,//此窗口无主菜单hInstance,//创建此窗口的应用程序的当前句柄NULL //不使用该值);if(!hwnd)return FALSE;ShowWindow( hwnd, nCmdShow) ;UpdateWindow(hwnd);return TRUE;}接下来是核心部分是扫雷游戏的算法代码:命名为caculate.cpp#include"caculate.h" //定义覆盖层普通标记;extern char co[xk][yk]={0};extern char th[xk][yk]={0};extern int xs=20,ys=20;extern int tn=50;Z *top,*bottom;void crzh(Z **top,Z **bottom) //创建两个空头节点;{Z *tem;*top=*bottom=(Z*)malloc(sizeof(Z));(*top)->i=1;(*top)->j=1;tem=(Z*)malloc(sizeof(Z));(*top)->next=tem;tem->piror=*top;*top=tem;(*top)->next=NULL;}void pop(Z **top) //建立出栈函数;{*top=(*top)->piror;free((*top)->next);(*top)->next=NULL;}void push(Z **top,int i,int j) //建立压栈函数;{Z *temp;temp=(Z*)malloc(sizeof(Z));temp->i=i;temp->j=j;(*top)->next=temp;temp->piror=*top;(*top)=temp;(*top)->next=NULL;}void creat(char th[xk][yk]) //创建地图;{int x,y,i,j;for(i=0;i<xs;i++)for(j=0;j<ys;j++)th[i][j]=0;for(i=1;i<=tn;){x=(int)((rand()+90)*(xs)/(32767+90)); // 把xs-1改为了xsy=(int)((rand()+90)*(ys)/(32767+90));if(th[x][y]!=0) continue;th[x][y]='*';i++;}}void num(char th[xk][yk]) //标记数字;{int i,j,flag,ti,tj;for(i=0;i<xs;i++)for(j=0;j<ys;j++){if(th[i][j]=='*') continue;flag=0;ti=i;tj=j;for(--tj;ti<=i+1;ti++) {if((ti>=0)&&(tj>=0)&&(ti<xs)&&(tj<ys)&&(th[ti][tj]=='*')) flag++;else continue;}for(--ti,++tj;tj<=j+1;tj++) {if((ti>=0)&&(tj>=0)&&(ti<xs)&&(tj<ys)&&(th[ti][tj]=='*')) flag++;else continue;}for(--tj,--ti;ti>=i-1;ti--) {if((ti>=0)&&(tj>=0)&&(ti<xs)&&(tj<ys)&&(th[ti][tj]=='*')) flag++;else continue;}for(++ti,--tj;tj>=j-1;tj--) {if((ti>=0)&&(tj>=0)&&(ti<xs)&&(tj<ys)&&(th[ti][tj]=='*')) flag++;else continue;}th[i][j]=flag;}}void display(char th[xk][yk]) //显示创建的底盘结果;{int i,j;for(i=0;i<xs;i++){for(j=0;j<ys;j++)if(th[i][j]=='*') printf("%3c",th[i][j]);else printf("%3d",th[i][j]);putchar('\n');}}void cover(char th[xk][yk],char co[xk][yk]) //添加覆盖层;{int i,j;for(i=0;i<xs;i++)for(j=0;j<ys;j++)co[i][j]=buf;}void copy(char th[xk][yk],char co[xk][yk]){int i,j;for(i=0;i<xs;i++)for(j=0;j<ys;j++)if(th[i][j]=='*') co[i][j]=th[i][j];}void result(char co[xk][yk]) //显示游戏结果;{int i,j;for(i=0;i<xs;i++){for(j=0;j<ys;j++){if(co[i][j]=='*'||co[i][j]==buf) printf("%3c",co[i][j]);else printf("%3d",co[i][j]);}putchar('\n');}}void open(char th[xk][yk],char co[xk][yk],int i,int j) //定义打开区域函数;{int ti,tj;crzh(&top,&bottom); //创建栈的首节点;do{pop(&top);cout<<'*'<<endl;co[i][j]=th[i][j];ti=i;tj=j;for(--tj;ti<=i+1;ti++){if((ti>=0)&&(tj>=0)&&(ti<xs)&&(tj<ys)){if(th[ti][tj]==0){if(co[ti][tj]!=0) push(&top,ti,tj);cout<<'*'<<endl;}co[ti][tj]=th[ti][tj];}else continue;}for(--ti,++tj;tj<=j+1;tj++){if((ti>=0)&&(tj>=0)&&(ti<xs)&&(tj<ys)){if(th[ti][tj]==0){if(co[ti][tj]!=0) push(&top,ti,tj);}co[ti][tj]=th[ti][tj];}else continue;}for(--tj,--ti;ti>=i-1;ti--){if((ti>=0)&&(tj>=0)&&(ti<xs)&&(tj<ys)){if(th[ti][tj]==0){if(co[ti][tj]!=0) push(&top,ti,tj);}co[ti][tj]=th[ti][tj];}else continue;}for(++ti,--tj;tj>=j-1;tj--){if((ti>=0)&&(tj>=0)&&(ti<xs)&&(tj<ys)){if(th[ti][tj]==0){if(co[ti][tj]!=0) push(&top,ti,tj);}co[ti][tj]=th[ti][tj];}else continue;}i=top->i;j=top->j;}while(top!=bottom); //因为有空节点;}int intelligence(int record[xk][yk],char th[xk][yk],int move_x,int move_y) {int i,j,count=0;for(i=move_y-1,j=move_x-1;j<=move_x+1;j++){if(i<0||j<0||i>=xs|j>=ys) continue;if(record[i][j]==2&&th[i][j]=='*')count++;}for(j--,i++;i<=move_y+1;i++){if(i<0||j<0||i>=xs|j>=ys) continue;if(record[i][j]==2&&th[i][j]=='*')count++;}for(i--,j--;j>=move_x-1;j--){if(i<0||j<0||i>=xs|j>=ys) continue;if(record[i][j]==2&&th[i][j]=='*')count++;}for(j++,i--;i>=move_y;i--){if(i<0||j<0||i>=xs|j>=ys) continue;if(record[i][j]==2&&th[i][j]=='*')count++;}if(count==th[move_y][move_x])return 1;elsereturn 0;}最后是运行程序需要使用的头文件为别为:(1)caculate.h#include<windows.h>#include<stdlib.h>#include<string.h>#include<stdio.h>#include<iostream>#include<conio.h>using namespace std;#define xk 100#define yk 100//#define xs 20 //横向尺寸;//#define ys 30 //纵向尺寸;//#define tn 100 //雷数;#define buf 12typedef struct zhan{int i,j;struct zhan *piror,*next;}Z;//定义覆盖层普通标记;void crzh(Z **top,Z **bottom); //创建两个空头节点;void pop(Z **top); //建立出栈函数;void push(Z **top,int i,int j); //建立压栈函数;void creat(char th[xk][yk]); //创建地图;void num(char th[xk][yk]); //标记数字;void display(char th[xk][yk]); //显示创建的底盘结果;void cover(char th[xk][yk],char co[xk][yk]); //添加覆盖层;void copy(char th[xk][yk],char co[xk][yk]);void result(char co[xk][yk]); //显示游戏结果;void open(char th[xk][yk],char co[xk][yk],int i,int j); //定义打开区域函数;int intelligence(int record[xk][yk],char th[xk][yk],int move_x,int move_y);(2)windo.h#include<windows.h>//包含应用程序中所需的数据类型和数据结构的定义#include<stdlib.h>#include<string.h>#include<stdio.h>#include<iostream>#include<conio.h>using namespace std;#define d_width 25 //雷块尺寸#define d_height 25#define d_ini_x 10 //雷区起始坐标#define d_ini_y 10BOOL InitWindowsClass(HINSTANCE hInstance);BOOL InitWindows(HINSTANCE hInstance,int nCmdShow);(3)proc.h#include"windo.h"LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM); //窗口函数说明完成以上操作,运行即可:以下为运行效果截图由于本人知识有限,仅提供以上代码供大家学习、参考,希望大家批评指正。
C++实现简单扫雷游戏
![C++实现简单扫雷游戏](https://img.taocdn.com/s3/m/4a892cf9e109581b6bd97f19227916888486b9b3.png)
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();}更多精彩游戏⼩代码,请点击阅读以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
扫雷小游戏实验报告(3篇)
![扫雷小游戏实验报告(3篇)](https://img.taocdn.com/s3/m/a436e9a388eb172ded630b1c59eef8c75fbf95d1.png)
第1篇一、实验目的本次实验旨在通过使用C语言编写扫雷小游戏,巩固和加深对C语言编程基础知识的理解,提高编程实践能力。
通过实验,使学生能够熟练运用数组、函数等编程技巧,实现一个具有良好交互性和趣味性的小游戏。
二、实验环境1. 操作系统:Windows 102. 编译器:Visual Studio 20193. 编程语言:C语言三、实验内容1. 游戏设计扫雷小游戏是一款经典的逻辑推理游戏,玩家需要在限定时间内找出棋盘上的所有非雷区域。
游戏规则如下:(1)棋盘大小:9x9(2)地雷数量:10个(3)玩家通过输入坐标排查雷区,若排查到非雷区则显示周围雷的数量,若排查到雷则游戏结束。
(4)玩家的目标是找出所有非雷区,成功排雷后游戏结束。
2. 数据结构设计为了存储雷的位置信息和排查信息,我们需要使用以下数据结构:(1)二维数组:用于存储雷的位置信息,大小为9x9,其中值为-1表示雷,值为0表示非雷。
(2)二维字符数组:用于存储排查结果,大小为9x9,其中字符'0'表示非雷,字符''表示雷。
3. 函数设计(1)初始化函数:用于初始化棋盘、地雷位置和排查结果。
(2)打印棋盘函数:用于显示当前棋盘状态。
(3)布置雷函数:用于随机布置地雷。
(4)排查函数:用于判断玩家输入的坐标是否为雷,并更新排查结果。
(5)游戏主逻辑函数:用于实现游戏的主要逻辑,包括用户交互、游戏结束判断等。
4. 编码实现以下是部分代码实现:```cinclude <stdio.h>include <stdlib.h>include <time.h>define ROW 9define COL 9define MINE_NUM 10// 函数声明void init(char mine[ROW][COL], char show[ROW][COL]);void print(char show[ROW][COL]);void setMines(char mine[ROW][COL]);void check(char mine[ROW][COL], char show[ROW][COL], int x, int y);int isGameOver(char show[ROW][COL]);int main() {char mine[ROW][COL], show[ROW][COL];int x, y;int gameOver = 0;init(mine, show);setMines(mine);while (!gameOver) {print(show);printf("请输入坐标(x y):");scanf("%d %d", &x, &y);if (x < 0 || x >= ROW || y < 0 || y >= COL) { printf("坐标输入错误,请重新输入。