C语言扫雷源代码
C语言扫雷游戏源代码
/*模拟扫雷游戏*/#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(EGAVGA_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);}/*暂时读出历史纪录。
C语言编写的扫雷游戏源代码
C语言编写的扫雷嬉戏源代码/* 源程序*/#include <graphics.h>#include <stdlib.h>#include <dos.h>#define LE 0xff01#define LEFTCLICK 0xff10#define LEFTDRAG 0xff19#define MOUSEMOVE 0xff08struct{int num;/*格子当前处于什么状态,1有雷,0已经显示过数字或者空白格子*/ int roundnum;/*统计格子四周有多少雷*/int flag;/*右键按下显示红旗的标记,0没有红旗标记,1有红旗标记*/}Mine[10][10];int gameAGAIN=0;/*是否重来的变量*/int gamePLAY=0;/*是否是第一次玩嬉戏的标记*/int mineNUM;/*统计处理过的格子数*/char randmineNUM[3];/*显示数字的字符串*/int Keystate;int MouseExist;int MouseButton;int MouseX;int MouseY;void Init(void);/*图形驱动*/void MouseOn(void);/*鼠标光标显示*/void MouseOff(void);/*鼠标光标隐藏*/void MouseSetXY(int,int);/*设置当前位置*/int Le(void);/*左键按下*/int RightPress(void);/*鼠标右键按下*/void MouseGetXY(void);/*得到当前位置*/void Control(void);/*嬉戏开场,重新,关闭*/void GameBegain(void);/*嬉戏开场画面*/void DrawSmile(void);/*画笑脸*/void DrawRedflag(int,int);/*显示红旗*/void DrawEmpty(int,int,int,int);/*两种空格子的显示*/void GameOver(void);/*嬉戏完毕*/void GameWin(void);/*显示成功*/int MineStatistics(int,int);/*统计每个格子四周的雷数*/int ShowWhite(int,int);/*显示无雷区的空白局部*/void GamePlay(void);/*嬉戏过程*/void Close(void);/*图形关闭*/void main(void)Init();Control();Close();}void Init(void)/*图形开场*/{int gd=DETECT,gm;initgraph(&gd,&gm,"c:\\tc");}void Close(void)/*图形关闭*/{closegraph();}void MouseOn(void)/*鼠标光标显示*/{_AX=0x01;geninterrupt(0x33);}void MouseOff(void)/*鼠标光标隐藏*/{_AX=0x02;geninterrupt(0x33);}void MouseSetXY(int x,int y)/*设置当前位置*/ {_CX=x;_DX=y;_AX=0x04;geninterrupt(0x33);}int Le(void)/*鼠标左键按下*/{_AX=0x03;geninterrupt(0x33);return(_BX&1);}int RightPress(void)/*鼠标右键按下*/{_AX=0x03;geninterrupt(0x33);return(_BX&2);}void MouseGetXY(void)/*得到当前位置*/_AX=0x03;geninterrupt(0x33);MouseX=_CX;MouseY=_DX;}void Control(void)/*嬉戏开场,重新,关闭*/{int gameFLAG=1;/*嬉戏失败后推断是否重新开场的标记*/while(1){if(gameFLAG)/*嬉戏失败后没推断出重新开场或者退出嬉戏的话就接着推断*/ {GameBegain(); /*嬉戏初始画面*/GamePlay();/*详细嬉戏*/if(gameAGAIN==1)/*嬉戏中重新开场*/{gameAGAIN=0;continue;}}MouseOn();gameFLAG=0;if(Le())/*推断是否重新开场*/{MouseGetXY();if(MouseX>280&&MouseX<300&&MouseY>65&&MouseY<85){gameFLAG=1;continue;}}if(kbhit())/*推断是否按键退出*/break;}MouseOff();}void DrawSmile(void)/*画笑脸*/{setfillstyle(SOLID_FILL,YELLOW);fillellipse(290,75,10,10);setcolor(YELLOW);setfillstyle(SOLID_FILL,BLACK);/*眼睛*/fillellipse(285,75,2,2);setcolor(BLACK);/*嘴巴*/bar(287,80,293,81);}void DrawRedflag(int i,int j)/*显示红旗*/{setcolor(7);setfillstyle(SOLID_FILL,RED);bar(198+j*20,95+i*20,198+j*20+5,95+i*20+5);setcolor(BLACK);line(198+j*20,95+i*20,198+j*20,95+i*20+10);}void DrawEmpty(int i,int j,int mode,int color)/*两种空格子的显示*/ {setcolor(color);setfillstyle(SOLID_FILL,color);if(mode==0)/*没有单击过的大格子*/bar(200+j*20-8,100+i*20-8,200+j*20+8,100+i*20+8);elseif(mode==1)/*单击过后显示空白的小格子*/bar(200+j*20-7,100+i*20-7,200+j*20+7,100+i*20+7);}void GameBegain(void)/*嬉戏开场画面*/{int i,j;cleardevice();if(gamePLAY!=1){MouseSetXY(290,70); /*鼠标一开场的位置,并作为它的初始坐标*/ MouseX=290;MouseY=70;}gamePLAY=1;/*下次按重新开场的话鼠标不重新初始化*/mineNUM=0;setfillstyle(SOLID_FILL,7);bar(190,60,390,290);for(i=0;i<10;i++)/*画格子*/for(j=0;j<10;j++)DrawEmpty(i,j,0,8);setcolor(7);DrawSmile();/*画脸*/randomize();for(i=0;i<10;i++)/*100个格子随机赋值有没有地雷*/for(j=0;j<10;j++)Mine[i][j].num=random(8);/*假如随机数的结果是1表示这个格子有地雷*/if(Mine[i][j].num==1)mineNUM++;/*现有雷数加1*/elseMine[i][j].num=2;Mine[i][j].flag=0;/*表示没红旗标记*/}sprintf(randmineNUM,"%d",mineNUM); /*显示这次总共有多少雷数*/setcolor(1);settextstyle(0,0,2);outtextxy(210,70,randmineNUM);mineNUM=100-mineNUM;/*变量取空白格数量*/MouseOn();}void GameOver(void)/*嬉戏完毕画面*/{int i,j;setcolor(0);for(i=0;i<10;i++)for(j=0;j<10;j++)if(Mine[i][j].num==1)/*显示全部的地雷*/{DrawEmpty(i,j,0,RED);setfillstyle(SOLID_FILL,BLACK);fillellipse(200+j*20,100+i*20,7,7);}}void GameWin(void)/*显示成功*/{setcolor(11);settextstyle(0,0,2);outtextxy(230,30,"YOU WIN!");}int MineStatistics(int i,int j)/*统计每个格子四周的雷数*/{int nNUM=0;if(i==0&&j==0)/*左上角格子的统计*/{if(Mine[0][1].num==1)nNUM++;if(Mine[1][0].num==1)nNUM++;if(Mine[1][1].num==1)}elseif(i==0&&j==9)/*右上角格子的统计*/{if(Mine[0][8].num==1)nNUM++;if(Mine[1][9].num==1)nNUM++;if(Mine[1][8].num==1)nNUM++;}elseif(i==9&&j==0)/*左下角格子的统计*/{if(Mine[8][0].num==1)nNUM++;if(Mine[9][1].num==1)nNUM++;if(Mine[8][1].num==1)nNUM++;}elseif(i==9&&j==9)/*右下角格子的统计*/{if(Mine[9][8].num==1)nNUM++;if(Mine[8][9].num==1)nNUM++;if(Mine[8][8].num==1)nNUM++;}else if(j==0)/*左边第一列格子的统计*/{if(Mine[i][j+1].num==1)nNUM++;if(Mine[i+1][j].num==1)nNUM++;if(Mine[i-1][j].num==1)nNUM++;if(Mine[i-1][j+1].num==1)nNUM++;if(Mine[i+1][j+1].num==1)nNUM++;else if(j==9)/*右边第一列格子的统计*/ {if(Mine[i][j-1].num==1)nNUM++;if(Mine[i+1][j].num==1)nNUM++;if(Mine[i-1][j].num==1)nNUM++;if(Mine[i-1][j-1].num==1)nNUM++;if(Mine[i+1][j-1].num==1)nNUM++;}else if(i==0)/*第一行格子的统计*/{if(Mine[i+1][j].num==1)nNUM++;if(Mine[i][j-1].num==1)nNUM++;if(Mine[i][j+1].num==1)nNUM++;if(Mine[i+1][j-1].num==1)nNUM++;if(Mine[i+1][j+1].num==1)nNUM++;}else if(i==9)/*最终一行格子的统计*/ {if(Mine[i-1][j].num==1)nNUM++;if(Mine[i][j-1].num==1)nNUM++;if(Mine[i][j+1].num==1)nNUM++;if(Mine[i-1][j-1].num==1)nNUM++;if(Mine[i-1][j+1].num==1)nNUM++;}else/*一般格子的统计*/{if(Mine[i-1][j].num==1)nNUM++;nNUM++;if(Mine[i][j+1].num==1)nNUM++;if(Mine[i+1][j+1].num==1)nNUM++;if(Mine[i+1][j].num==1)nNUM++;if(Mine[i+1][j-1].num==1)nNUM++;if(Mine[i][j-1].num==1)nNUM++;if(Mine[i-1][j-1].num==1)nNUM++;}return(nNUM);/*把格子四周一共有多少雷数的统计结果返回*/}int ShowWhite(int i,int j)/*显示无雷区的空白局部*/{if(Mine[i][j].flag==1||Mine[i][j].num==0)/*假如有红旗或该格处理过就不对该格进展任何推断*/return;mineNUM--;/*显示过数字或者空格的格子就表示多处理了一个格子,当全部格子都处理过了表示成功*/if(Mine[i][j].roundnum==0&&Mine[i][j].num!=1)/*显示空格*/{DrawEmpty(i,j,1,7);Mine[i][j].num=0;}elseif(Mine[i][j].roundnum!=0)/*输出雷数*/{DrawEmpty(i,j,0,8);sprintf(randmineNUM,"%d",Mine[i][j].roundnum);setcolor(RED);outtextxy(195+j*20,95+i*20,randmineNUM);Mine[i][j].num=0;/*已经输出雷数的格子用0表示已经用过这个格子*/return ;}/*8个方向递归显示全部的空白格子*/if(i!=0&&Mine[i-1][j].num!=1)ShowWhite(i-1,j);if(i!=0&&j!=9&&Mine[i-1][j+1].num!=1)ShowWhite(i-1,j+1);ShowWhite(i,j+1);if(j!=9&&i!=9&&Mine[i+1][j+1].num!=1)ShowWhite(i+1,j+1);if(i!=9&&Mine[i+1][j].num!=1)ShowWhite(i+1,j);if(i!=9&&j!=0&&Mine[i+1][j-1].num!=1)ShowWhite(i+1,j-1);if(j!=0&&Mine[i][j-1].num!=1)ShowWhite(i,j-1);if(i!=0&&j!=0&&Mine[i-1][j-1].num!=1)ShowWhite(i-1,j-1);}void GamePlay(void)/*嬉戏过程*/{int i,j,Num;/*Num用来接收统计函数返回一个格子四周有多少地雷*/for(i=0;i<10;i++)for(j=0;j<10;j++)Mine[i][j].roundnum=MineStatistics(i,j);/*统计每个格子四周有多少地雷*/while(!kbhit()){if(Le())/*鼠标左键盘按下*/{MouseGetXY();if(MouseX>280&&MouseX<300&&MouseY>65&&MouseY<85)/*重新来*/{MouseOff();gameAGAIN=1;break;}if(MouseX>190&&MouseX<390&&MouseY>90&&MouseY<290)/*当前鼠标位置在格子范围内*/{j=(MouseX-190)/20;/*x坐标*/i=(MouseY-90)/20;/*y坐标*/if(Mine[i][j].flag==1)/*假如格子有红旗那么左键无效*/continue;if(Mine[i][j].num!=0)/*假如格子没有处理过*/{if(Mine[i][j].num==1)/*鼠标按下的格子是地雷*/{MouseOff();GameOver();/*嬉戏失败*/}else/*鼠标按下的格子不是地雷*/{MouseOff();Num=MineStatistics(i,j);if(Num==0)/*四周没地雷就用递归算法来显示空白格子*/ShowWhite(i,j);else/*按下格子四周有地雷*/{sprintf(randmineNUM,"%d",Num);/*输出当前格子四周的雷数*/setcolor(RED);outtextxy(195+j*20,95+i*20,randmineNUM);mineNUM--;}MouseOn();Mine[i][j].num=0;/*点过的格子四周雷数的数字变为0表示这个格子已经用过*/if(mineNUM<1)/*成功了*/{GameWin();break;}}}}}if(RightPress())/*鼠标右键键盘按下*/{MouseGetXY();if(MouseX>190&&MouseX<390&&MouseY>90&&MouseY<290)/*当前鼠标位置在格子范围内*/{j=(MouseX-190)/20;/*x坐标*/i=(MouseY-90)/20;/*y坐标*/MouseOff();if(Mine[i][j].flag==0&&Mine[i][j].num!=0)/*原来没红旗现在显示红旗*/{DrawRedflag(i,j);Mine[i][j].flag=1;}elseif(Mine[i][j].flag==1)/*有红旗标记再按右键就红旗消逝*/DrawEmpty(i,j,0,8);Mine[i][j].flag=0;}}MouseOn();sleep(1);}}}。
原创C语言扫雷程序大作业代码
int a;
a=srdng(x,y);
if(a!=0)
{
tru[x-1][y-1]=a;
tbl[x+1][y+1]=a;
}
else
{
tru[x-1][y-1]='O';
tbl[x+1][y+1]='O';
jdg_4(x-1,y-1);
jdg_4(x,y-1);
jdg_4(x+1,y-1);
}
return 0;
scanf("%d",&z);
if (z==3)//--------------------------------待定
{
tbl[x+1][y+1]='?';
dspl();
}
else
if(z==2)//-----------------------------标记
{
tbl[x+1][y+1]='P';
{
if((x>=1)&&(x<=10)&&(y>=1)&&(y<=10)&&(tru[x-1][y-1]='_'))
anls_1(x,y);
return 0;
}
int anls_2(int x,int y)//-------------------------------------上方境况分析(空白点的迭代)
{1,'|','_','_','_','_','_','_','_','_','_','_'},
c语言扫雷程序代码
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) {
扫雷c语言程序设计
扫雷c语言程序设计以下是一个简单的扫雷游戏的C语言程序设计示例:c复制代码#include <stdio.h>#include <stdlib.h>#include <time.h>#define ROWS 9#define COLS 9#define MINE 10#define UNKNOWNS 0#define EMPTY 0#define MARKED 255int board[ROWS][COLS];int numMines;int numFlags;int numUnknowns;int revealed[ROWS][COLS];void initBoard() {srand(time(NULL));numMines = ROWS * COLS - 1;for (int i = 0; i < ROWS; i++) {for (int j = 0; j < COLS; j++) {board[i][j] = (rand() % (MINE + 1)) + 1; if (board[i][j] == MINE) {numMines--;} else if (rand() % 2 == 0) {board[i][j] = UNKNOWNS;numUnknowns++;} else {board[i][j] = EMPTY;}}}void reveal(int row, int col) {if (row >= 0 && row < ROWS && col >= 0 && col < COLS && board[row][col] != MARKED) { if (board[row][col] == MINE) {printf("Game over!\n");exit(0);} else if (board[row][col] == UNKNOWNS) {numUnknowns--;for (int i = 0; i < ROWS; i++) {for (int j = 0; j < COLS; j++) {if (revealed[i][j] == 0 && isSafe(i, j)) {reveal(i, j);}}} else if (board[row][col] == EMPTY) { revealed[row][col] = 1;} else {printf("You hit a mine!\n");exit(0);}}}int isSafe(int row, int col) {int count = 0;for (int i = 0; i < ROWS; i++) {for (int j = 0; j < COLS; j++) {if ((i == row && j == col) || board[i][j] ==MARKED) continue;if ((i - row) * (i - row) + (j - col) * (j - col) <= numFlags * numFlags) {count++;} else if (board[i][j] != EMPTY) {return 0; // not safe, there is a mine here.}}}return count == numFlags + 1; // safe if all adjacent cells are either mines or flags.}。
C编写的扫雷源程序
C编写的扫雷源程序集团企业公司编码:(LL3698-KKI1269-TM2483-LUI12689-ITT289-//h e a d e r f i l e #include<iostream>#include<cstdlib>#include<ctime>#include<windows.h>#include<conio.h>//defines#defineKEY_UP0xE048#defineKEY_DOWN0xE050#defineKEY_LEFT0xE04B#defineKEY_RIGHT0xE04D#defineKEY_ESC0x001B#defineKEY_1'1'#defineKEY_2'2'#defineKEY_3'3'#defineGAME_MAX_WIDTH100#defineGAME_MAX_HEIGHT100//StringsResource#defineSTR_GAMETITLE"ArrowKey:MoveCursorKey1:Open\Key2:MarkKey3:OpenNeighbors"#defineSTR_GAMEWIN"Congratulations!YouWin!Thankyouforplaying!\n "#defineSTR_GAMEOVER"GameOver,thankyouforplaying!\n"#defineSTR_GAMEEND"Presentedbyyzfy.PressESCtoexit\n"//-------------------------------------------------------------//BaseclassclassCConsoleWnd{public:staticintTextOut(constchar*);staticintGotoXY(int,int);staticintCharOut(int,int,constint);staticintTextOut(int,int,constchar*);staticintGetKey();public:};//{{//classCConsoleWnd////intCConsoleWnd::GetKey()//WaitforstandardinputandreturntheKeyCode//intCConsoleWnd::GetKey(){intnkey=getch(),nk=0;if(nkey>=128||nkey==0)nk=getch();returnnk>0nkey*256+nk:nkey;}////intCConsoleWnd::GotoXY(intx,inty)//Movecursorto(x,y)//OnlyConsoleApplication//intCConsoleWnd::GotoXY(intx,inty){COORDcd;cd.X=x;cd.Y=y;returnSetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cd);}////intCConsoleWnd::TextOut(constchar*pstr)//Outputastringatcurrentposition//intCConsoleWnd::TextOut(constchar*pstr){for(;*pstr;++pstr)putchar(*pstr);return0;}////intCConsoleWnd::CharOut(intx,inty,constintpstr) //Outputacharat(x,y)//intCConsoleWnd::CharOut(intx,inty,constintpstr) {GotoXY(x,y);returnputchar(pstr);}////intCConsoleWnd::TextOut(constchar*pstr)//Outputastringat(x,y)//intCConsoleWnd::TextOut(intx,inty,constchar*pstr) {GotoXY(x,y);returnTextOut(pstr);}//}}//-------------------------------------------------------------//ApplicationclassclassCSLGame:publicCConsoleWnd{private:private:intcurX,curY;intpoolWidth,poolHeight;intbm_gamepool[GAME_MAX_HEIGHT+2][GAME_MAX_WIDTH+2];public:CSLGame():curX(0),curY(0){poolWidth=poolHeight=0;}intInitPool(int,int,int);intMoveCursor(){returnCConsoleWnd::GotoXY(curX,curY);} intDrawPool(int);intWaitMessage();intGetShowNum(int,int);intTryOpen(int,int);private:intDFSShowNum(int,int);private:conststaticintGMARK_BOOM;conststaticintGMARK_EMPTY;conststaticintGMARK_MARK;};constintCSLGame::GMARK_BOOM=0x10; constintCSLGame::GMARK_EMPTY=0x100; constintCSLGame::GMARK_MARK=0x200;//{{//classCSLGame:publicCConsoleWnd////intCSLGame::InitPool(intWidth,intHeight,intnBoom) //Initializethegamepool.//IfWidth*Height<=nBoom,ornBoom<=0,//orWidthandHeightexceedlimit,thenreturn1//otherwisereturn0//intCSLGame::InitPool(intWidth,intHeight,intnBoom) {poolWidth=Width;poolHeight=Height;if(nBoom<=0||nBoom>=Width*Height||Width<=0||Width>GAME_MAX_WIDTH||Height<=0||Height>GAME_MAX_HEIGHT){return1;}//zeromemoryfor(inty=0;y<=Height+1;++y){for(intx=0;x<=Width+1;++x){bm_gamepool[y][x]=0;}}//initseedsrand(time(NULL));//initBoomswhile(nBoom){intx=rand()%Width+1,y=rand()%Height+1; if(bm_gamepool[y][x]==0){bm_gamepool[y][x]=GMARK_BOOM;--nBoom;}}//initcursorpositioncurX=curY=1;MoveCursor();return0;}////intCSLGame::DrawPool(intbDrawBoom=0) //DrawgamepooltoConsolewindow//intCSLGame::DrawPool(intbDrawBoom=0) {for(inty=1;y<=poolHeight;++y){CConsoleWnd::GotoXY(1,y);for(intx=1;x<=poolWidth;++x){if(bm_gamepool[y][x]==0){putchar('.');}elseif(bm_gamepool[y][x]==GMARK_EMPTY) {putchar('');}elseif(bm_gamepool[y][x]>0&&bm_gamepool[y][x]<=8){putchar('0'+bm_gamepool[y][x]);}elseif(bDrawBoom==0&&(bm_gamepool[y][x]&GMARK_MARK)) {putchar('#');}elseif(bm_gamepool[y][x]&GMARK_BOOM){if(bDrawBoom)putchar('*');elseputchar('.');}}}return0;}////intCSLGame::GetShowNum(intx,inty)//returnShowNumat(x,y)//intCSLGame::GetShowNum(intx,inty){intnCount=0;for(intY=-1;Y<=1;++Y)for(intX=-1;X<=1;++X){if(bm_gamepool[y+Y][x+X]&GMARK_BOOM)++nCount; }returnnCount;}////intCSLGame::TryOpen(intx,inty)//Tryopen(x,y)andshowthenumber//Ifthereisaboom,thenreturnEOF//intCSLGame::TryOpen(intx,inty){intnRT=0;if(bm_gamepool[y][x]&GMARK_BOOM){nRT=EOF;}else{intnCount=GetShowNum(x,y);if(nCount==0){DFSShowNum(x,y);}elsebm_gamepool[y][x]=nCount;}returnnRT;}////intCSLGame::DFSShowNum(intx,inty) //Privatefunction,nocomment//intCSLGame::DFSShowNum(intx,inty) {if((0<x&&x<=poolWidth)&&(0<y&&y<=poolHeight)&&(bm_gamepool[y][x]==0)){intnCount=GetShowNum(x,y);if(nCount==0){bm_gamepool[y][x]=GMARK_EMPTY;for(intY=-1;Y<=1;++Y)for(intX=-1;X<=1;++X){DFSShowNum(x+X,y+Y);}}elsebm_gamepool[y][x]=nCount;}return0;}////intCSLGame::WaitMessage()//Gameloop,waitandprocessaninputmessage //return:0:notend;1:Win;otherwise:Lose //intCSLGame::WaitMessage(){intnKey=CConsoleWnd::GetKey(); intnRT=0,nArrow=0;switch(nKey){caseKEY_UP:{if(curY>1)--curY;nArrow=1;}break;caseKEY_DOWN:{if(curY<poolHeight)++curY; nArrow=1;}break;caseKEY_LEFT:{if(curX>1)--curX;nArrow=1;}break;caseKEY_RIGHT:{if(curX<poolWidth)++curX;nArrow=1;}break;caseKEY_1:{nRT=TryOpen(curX,curY);}break;caseKEY_2:{if((bm_gamepool[curY][curX]&~(GMARK_MARK|GMARK_BOOM))==0){bm_gamepool[curY][curX]^=GMARK_MARK; }}break;caseKEY_3:{if(bm_gamepool[curY][curX]&0xF){intnb=bm_gamepool[curY][curX]&0xF; for(inty=-1;y<=1;++y)for(intx=-1;x<=1;++x){if(bm_gamepool[curY+y][curX+x]&GMARK_MARK) --nb;}if(nb==0){for(inty=-1;y<=1;++y)for(intx=-1;x<=1;++x){if((bm_gamepool[curY+y][curX+x]&(0xF|GMARK_MARK))==0){nRT|=TryOpen(curX+x,curY+y);}}}}}break;caseKEY_ESC:{nRT=EOF;}break;}if(nKey==KEY_1||nKey==KEY_3) {inty=1;for(;y<=poolHeight;++y){intx=1;for(;x<=poolWidth;++x){if(bm_gamepool[y][x]==0)break; }if(x<=poolWidth)break;}if(!(y<=poolHeight)){nRT=1;}}if(nArrow==0){DrawPool();}MoveCursor();returnnRT;}//}}//-------------------------------------------------------------//{{////mainfunction//intmain(void){intx=50,y=20,b=100,n;//definewidth&height&n_booms CSLGameslGame;//InitGame{CConsoleWnd::GotoXY(0,0);CConsoleWnd::TextOut(STR_GAMETITLE);slGame.InitPool(x,y,b);slGame.DrawPool();slGame.MoveCursor();}while((n=slGame.WaitMessage())==0)//GameMessageLoop;//EndoftheGame{slGame.DrawPool(1); CConsoleWnd::TextOut("\n");if(n==1){CConsoleWnd::TextOut(STR_GAMEWIN);}else{CConsoleWnd::TextOut(STR_GAMEOVER); }CConsoleWnd::TextOut(STR_GAMEEND);}while(CConsoleWnd::GetKey()!=KEY_ESC) ;return0;}//}}。
扫雷游戏代码
扫雷游戏代码standalone; self-contained; independent; self-governed;autocephalous; indie; absolute; unattached; substantive/**/#ifndef BLOCK_H_#define BLOCK_H_#include<QLabel>class QWidget;class Block:public QLabel{Q_OBJECTpublic:explicit Block(bool mine_flag,QWidget*parent=0);void set_number(int number);void turn_over();bool is_mine()const;bool is_turn_over()const;signals:void turn_over(bool is_mine);protected:void mousePressEvent(QMouseEvent*event); private:bool mine_flag_;bool mark_flag_;bool turn_over_flag_;int number_;};#endif#include""#include<QLabel>#include<QMouseEvent>#include<QPixmap>#include<QWidget>Block::Block(bool mine_flag,QWidget*parent) :QLabel(parent){mine_flag_=mine_flag;mark_flag_=false;turn_over_flag_=false;number_=-1;setPixmap(QPixmap(":/images/"));}void Block::set_number(int number){number_=number;}void Block::turn_over(){if(!turn_over_flag_){turn_over_flag_=true;if(mine_flag_)setPixmap(QPixmap(":/images/"));elsesetPixmap(QPixmap(":/images/mine_"+QString("%1").arg(num ber_)+".png"));update();}}bool Block::is_mine()const{return mine_flag_;}bool Block::is_turn_over()const{return turn_over_flag_;}/*鼠标事件的实现*/void Block::mousePressEvent(QMouseEvent*event){if(event->button()==Qt::LeftButton){if(!turn_over_flag_&&!mark_flag_){turn_over_flag_=true;if(mine_flag_==true){setPixmap(QPixmap(":/images/"));update();emit turn_over(true);}else{setPixmap(QPixmap(":/images/mine_"+QString("%1").arg(num ber_)+".png"));update();emit turn_over(false);}}}else if(event->button()==Qt::RightButton){if(!turn_over_flag_){if(!mark_flag_){mark_flag_=true;setPixmap(QPixmap(":/images/"));}else{mark_flag_=false;setPixmap(QPixmap(":/images/"));}update();}}QLabel::mousePressEvent(event);}#ifndef BLOCK_AREA_H_#define BLOCK_AREA_H_#include""#include<QWidget>class QEvent;class QGridLayout;class QObject;class BlockArea:public QWidget{Q_OBJECTpublic:BlockArea(int row,int column,int mine_number,QWidget* parent=0);void set_block_area(int row,int column,intmine_number,int init_flag=false);signals:void game_over(bool is_win);protected:bool eventFilter(QObject*watched,QEvent*event); private slots:void slot_turn_over(bool is_mine);private:int calculate_mines(int x,int y)const;rg(easy_record_time_)),1,1);up_layout->addWidget(new QLabel(easy_record_name_),1,2);up_layout->addWidget(new QLabel(tr("Middle")),2,0);up_layout->addWidget(newQLabel(QString("%1").arg(middle_record_time_)),2,1);up_layout->addWidget(newQLabel(middle_record_name_),2,2);up_layout->addWidget(new QLabel(tr("Hard")),3,0);up_layout->addWidget(newQLabel(QString("%1").arg(hard_record_time_)),3,1);up_layout->addWidget(new QLabel(hard_record_name_),3,2);QPushButton*recount_button=newQPushButton(tr("recount"));QPushButton*close_button=new QPushButton(tr("close"));close_button->setDefault(true);connect(recount_button,SIGNAL(clicked()),&dialog,SLOT(ac cept()));connect(close_button,SIGNAL(clicked()),&dialog,SLOT(reje ct()));QHBoxLayout*bottom_layout=new QHBoxLayout;bottom_layout->addStretch();bottom_layout->addWidget(recount_button);bottom_layout->addWidget(close_button);QVBoxLayout*main_layout=new QVBoxLayout(&dialog);main_layout->addLayout(up_layout);main_layout->addLayout(bottom_layout);if()==QDialog::Accepted){easy_record_time_=middle_record_time_=hard_record_time_= g_no_record_time;easy_record_name_=middle_record_name_=hard_record_name_= g_no_record_name;}}void MainWindow::slot_show_game_toolBar(bool show){if(show)game_toolBar->show();elsegame_toolBar->hide();}void MainWindow::slot_show_statusBar(bool show){if(show)statusBar()->show();elsestatusBar()->hide();}/*游戏的设置容易、中等、困难及自定义*/void MainWindow::slot_standard(QAction*standard_action) {if(standard_action==easy_standard_action){current_standard_=0;row_=9;column_=9;mine_number_=10;}else if(standard_action==middle_standard_action){ current_standard_=1;row_=16;column_=16;mine_number_=40;}else if(standard_action==hard_standard_action){current_standard_=2;row_=16;column_=30;mine_number_=99;}else if(standard_action==custom_standard_action){ QDialog dialog;(tr("set standard"));QSpinBox*row_spinBox=new QSpinBox;row_spinBox->setRange(5,50);row_spinBox->setValue(row_);QSpinBox*column_spinBox=new QSpinBox;column_spinBox->setRange(5,50);column_spinBox->setValue(column_);QSpinBox*mine_spinBox=new QSpinBox;mine_spinBox->setValue(mine_number_);QHBoxLayout*up_layout=new QHBoxLayout;up_layout->addWidget(row_spinBox);up_layout->addWidget(column_spinBox);up_layout->addWidget(mine_spinBox);QDialogButtonBox*dialog_buttonBox=new QDialogButtonBox;dialog_buttonBox->addButton(QDialogButtonBox::Ok);dialog_buttonBox->addButton(QDialogButtonBox::Cancel);connect(dialog_buttonBox,SIGNAL(accepted()),&dialog,SLOT (accept()));connect(dialog_buttonBox,SIGNAL(rejected()),&dialog,SLOT (reject()));QHBoxLayout*bottom_layout=new QHBoxLayout;bottom_layout->addStretch();bottom_layout->addWidget(dialog_buttonBox);QVBoxLayout*main_layout=new QVBoxLayout(&dialog);main_layout->addLayout(up_layout);main_layout->addLayout(bottom_layout);if()==QDialog::Accepted)if(row_spinBox->value()*column_spinBox->value()>mine_spinBox->value()){current_standard_=3;row_=row_spinBox->value();column_=column_spinBox->value();mine_number_=mine_spinBox->value();}}slot_new_game();}/*实现帮助菜单中的关于游戏,及功能*/void MainWindow::slot_about_game(){QString introduction("<h2>"+tr("About Mine Sweepr")+"</h2>"+"<p>"+tr("This game is played by revealing squares of the grid,typically by clicking them with a mouse.If a square containing a mine is revealed,the player loses the game.Otherwise,a digit is revealed in the square,indicating the number of adjacent squares(out of the possible eight)that contain this number is zero then the square appears blank,and the surrounding squares are automatically also revealed.By using logic,the player can in many instances use this information to deduce that certain other squares are mine-free, in which case they may be safely revealed,or mine-filled,in which they can be marked as such(which is effected by right-clicking the square and indicated by a flag graphic).")+"</p>"+"<p>"+tr("This program is free software;you can redistribute it and/or under the terms of the GNU General Public License as published by the Software Foundation;either version3of the License,or(at your option)any later version.")+"</p>"+"<p>"+tr("Please see")+"<a href="+tr("for an overview of GPLv3licensing")+"</p>"+"<br>"+tr("Version:")+g_software_version+"</br>"+"<br>"+tr("Author:")+g_software_author+"</br>");QMessageBoxmessageBox(QMessageBox::Information,tr("About Mine Sweeper"),introduction,QMessageBox::Ok);();}/*游戏的判断,及所给出的提示做出判断*/void MainWindow::slot_game_over(bool is_win){();QString name;if(is_win){switch(current_standard_){case0:if(time_label->text().toInt()<easy_record_time_){name=QInputDialog::getText(this,tr("Please enter your name"),tr("You create a record.Please enter your name"));if(!()){easy_record_time_=time_label->text().toInt();easy_record_name_=name;}}elseQMessageBox::information(this,tr("Result"),tr("You win"));break;case1:if(time_label->text().toInt()<middle_record_time_){name=QInputDialog::getText(this,tr("Please enter your name"),tr("You create a record.Please enter your name"));if(!()){middle_record_time_=time_label->text().toInt();middle_record_name_=name;}}elseQMessageBox::information(this,tr("Result"),tr("You win"));break;case2:if(time_label->text().toInt()<hard_record_time_){name=QInputDialog::getText(this,tr("Please enter your name"),tr("You create a record.Please enter your name"));if(!()){hard_record_time_=time_label->text().toInt();hard_record_name_=name;}}elseQMessageBox::information(this,tr("Result"),tr("You win"));break;default:QMessageBox::information(this,tr("Result"),tr("Y ou win"));}}else{QMessageBox::information(this,tr("Result"),tr("You lose"));}}/*定时器的设置*/void MainWindow::slot_timer(){time_label->setText(QString("%1").arg()/1000));}/*关于菜单栏的设置是否显示游戏工具栏和状态栏*/void MainWindow::read_settings(){QSettings settings;("MainWindow");resize("size").toSize());move("pos").toPoint());bool show_game_toolBar=("showGameToolBar").toBool();show_game_toolBar_action->setChecked(show_game_toolBar);slot_show_game_toolBar(show_game_toolBar);bool show_statusBar=("showStatusBar").toBool();show_statusBar_action->setChecked(show_statusBar);slot_show_statusBar(show_statusBar);();("GameSetting");current_standard_=("current_standard").toInt();switch(current_standard_){case0:easy_standard_action->setChecked(true);break;case1:middle_standard_action->setChecked(true);break;case2:hard_standard_action->setChecked(true);break;case3:custom_standard_action->setChecked(true);break;default:;}row_=("row").toInt()==09:("row").toInt();column_=("column").toInt()==09:("column").toInt();mine_number_=("mine_number").toInt()==010:("mine_number" ).toInt();();("Rank");easy_record_time_=("easy_record_time").toInt()==0g_no_re cord_time:("easy_record_time").toInt();middle_record_time_=("middle_record_time").toInt()==0g_n o_record_time:("middle_record_time").toInt();hard_record_time_=("hard_record_time").toInt()==0g_no_re cord_time:("hard_record_time").toInt();easy_record_name_=("easy_record_name").toString()==""g_n o_record_name:("easy_record_name").toString();middle_record_name_=("middle_record_name").toString()==" "g_no_record_name:("middle_record_name").toString();hard_record_name_=("hard_record_name").toString()==""g_n o_record_name:("hard_record_name").toString();();}void MainWindow::write_settings(){QSettings settings;("MainWindow");("size",size());("pos",pos());("showGameToolBar",show_game_toolBar_action->isChecked());("showStatusBar",show_statusBar_action->isChecked());();("GameSetting");("current_standard",current_standard_);("row",row_);("column",column_);("mine_number",mine_number_);();("Rank");("easy_record_time",easy_record_time_);("middle_record_time",middle_record_time_);("hard_record_time",hard_record_time_);("easy_record_name",easy_record_name_);("middle_record_name",middle_record_name_);("hard_record_name",hard_record_name_);();}/*菜单栏里图片的显示*/void MainWindow::create_actions(){new_game_action=new QAction(QIcon(":/images/"),tr("New Game"),this);new_game_action->setShortcut(QKeySequence::New);connect(new_game_action,SIGNAL(triggered()),this,SLOT(sl ot_new_game()));rank_action=newQAction(QIcon(":/images/"),tr("Rank"),this);connect(rank_action,SIGNAL(triggered()),this,SLOT(slot_r ank()));exit_action=newQAction(QIcon(":/images/"),tr("Exit"),this);exit_action->setShortcut(QKeySequence::Quit);connect(exit_action,SIGNAL(triggered()),this,SLOT(close( )));show_game_toolBar_action=new QAction(tr("Show Game Tool Bar"),this);show_game_toolBar_action->setCheckable(true);connect(show_game_toolBar_action,SIGNAL(toggled(bool)),t his,SLOT(slot_show_game_toolBar(bool)));show_statusBar_action=new QAction(tr("Show Status Bar"),this);show_statusBar_action->setCheckable(true);connect(show_statusBar_action,SIGNAL(toggled(bool)),this ,SLOT(slot_show_statusBar(bool)));easy_standard_action=newQAction(QIcon(":/images/"),tr("Easy"),this);easy_standard_action->setCheckable(true);middle_standard_action=newQAction(QIcon(":/images/"),tr("Middle"),this);middle_standard_action->setCheckable(true);hard_standard_action=newQAction(QIcon(":/images/"),tr("Hard"),this);hard_standard_action->setCheckable(true);custom_standard_action=newQAction(QIcon(":/images/"),tr("Custom"),this);custom_standard_action->setCheckable(true);standard_actionGroup=new QActionGroup(this);standard_actionGroup->addAction(easy_standard_action);standard_actionGroup->addAction(middle_standard_action);standard_actionGroup->addAction(hard_standard_action);standard_actionGroup->addAction(custom_standard_action);connect(standard_actionGroup,SIGNAL(triggered(QAction*)) ,this,SLOT(slot_standard(QAction*)));about_game_action=newQAction(QIcon(":/images/"),tr("About Game"),this);connect(about_game_action,SIGNAL(triggered()),this,SLOT( slot_about_game()));about_qt_action=new QAction(QIcon(":/images/"),tr("About Qt"),this);connect(about_qt_action,SIGNAL(triggered()),qApp,SLOT(ab outQt()));}/*菜单栏的创建*/void MainWindow::create_menus(){game_menu=menuBar()->addMenu(tr("Game"));game_menu->addAction(new_game_action);game_menu->addSeparator();game_menu->addAction(rank_action);game_menu->addSeparator();game_menu->addAction(exit_action);setting_menu=menuBar()->addMenu(tr("Setting"));setting_menu->addAction(show_game_toolBar_action);setting_menu->addAction(show_statusBar_action);setting_menu->addSeparator();setting_menu->addAction(easy_standard_action);setting_menu->addAction(middle_standard_action);setting_menu->addAction(hard_standard_action);setting_menu->addAction(custom_standard_action);help_menu=menuBar()->addMenu(tr("Help"));help_menu->addAction(about_game_action);help_menu->addAction(about_qt_action);}void MainWindow::create_game_toolBar(){game_toolBar=addToolBar(tr("Game Tool Bar"));game_toolBar->setFloatable(false);game_toolBar->setMovable(false);game_toolBar->addAction(new_game_action);game_toolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); }void MainWindow::create_statusBar(){time_label=new QLabel;statusBar()->addPermanentWidget(time_label);statusBar()->addPermanentWidget(newQLabel(tr("second")));}#include""#include<QApplication>#include<QTranslator>int main(int argc,char*argv[]){QApplication app(argc,argv);QTranslator translator;(":/");(&translator);MainWindow window;();return();}。
扫雷算法c语言
扫雷算法c语言扫雷算法的C语言实现可以有很多种,以下是一个简单的示例:```cinclude <>include <>define SIZE 10typedef struct {int mines;int numbers;int cells;} Game;void initializeGame(Game game) {game->mines = SIZE SIZE - SIZE;game->numbers = 0;game->cells = (int )malloc(SIZE SIZE sizeof(int));for (int i = 0; i < SIZE SIZE; i++) {game->cells[i] = -1;}for (int i = 0; i < SIZE; i++) {for (int j = 0; j < SIZE; j++) {if (rand() % 2 == 0) { // Place a minegame->cells[i SIZE + j] = 0;game->mines--;} else { // Place a number or a blank spacegame->cells[i SIZE + j] = rand() % 3 + 1;game->numbers++;}}}}void printGame(Game game) {for (int i = 0; i < SIZE; i++) {for (int j = 0; j < SIZE; j++) {if (game->cells[i SIZE + j] == -1) { // Blank space printf(" ");} else if (game->cells[i SIZE + j] == 0) { // Mineprintf("");} else { // Number or question markprintf("%d", game->cells[i SIZE + j]);}}printf("\n");}}void solveGame(Game game) {for (int i = 0; i < SIZE; i++) {for (int j = 0; j < SIZE; j++) {if (game->cells[i SIZE + j] == -1) { // Blank space, check surrounding cells to see if they are mines or numbersif (i > 0 && game->cells[(i - 1) SIZE + j] != 0 && game->cells[(i - 1) SIZE + j] != game->cells[i SIZE + j]) { // Check above cellgame->cells[i SIZE + j] = game->cells[(i - 1) SIZE + j]; // Set this cell to the same value as the above cell (mine or number)} else if (i < SIZE - 1 && game->cells[(i + 1) SIZE + j] != 0 && game->cells[(i + 1) SIZE + j] != game->cells[i SIZE + j]) { // Check below cellgame->cells[i SIZE + j] = game->cells[(i + 1) SIZE + j]; // Set this cell to the same value as the below cell (mine or number) } else if (j > 0 && game->cells[i SIZE + (j - 1)] != 0 && game->cells[i SIZE + (j - 1)] != game->cells[i SIZE + j]) { // Check left cellgame->cells[i SIZE + j] = game->cells[i SIZE + (j - 1)]; // Set this cell to the same value as the left cell (mine or number)} else if (j < SIZE - 1 && game->cells[i SIZE + (j + 1)] != 0 && game->cells[i SIZE + (j + 1)] != game->cells[i SIZE + j]) { // Check right cellgame->cells[i SIZE + j] = game->cells[i SIZE + (j + 1)]; // Set this cell to the same value as the right cell (mine or number)} else if (game->numbers > 0) { // If there are still numbers in the game, place a number here if it's a blank space, and reduce the number of numbers by one. Otherwise, place a mine and reduce the number of mines by one.game->cells[i SIZE + j] = rand() % 3 + 1; // Place a number here if it's a blank space, and reduce the number。
c语言扫雷源代码
}
void printField() { for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { if (revealed[i][j] == 1) { if (mineField[i][j] == -1) { printf("* ");
} else { printf("%d ", mineField[i][j]);
} } else {
printf(". "); } } printf("\n"); } }
int countMines(int row, int col) { if (row < 0 || row >= SIZE || col < 0 || col >= SIZE || mineField[row][col] !=
initializeField(); placeMines();
int gameOver = 0; while (!gameOver) {
printField();
int row, col; printf("Enter row and column (0-%d): ", SIZE - 1); scanf("%d %d", &row, &col);
void initializeField() { for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { mineField[i][j] = 0; revealed[i][j] = 0; } }
C语言实现扫雷游戏源代码
C语⾔实现扫雷游戏源代码本⽂实例为⼤家分享了C语⾔实现扫雷游戏的具体代码,供⼤家参考,具体内容如下此次扫雷中我们以9乘以9的表格为例,后期可⾃动调动主要思路:建⽴两个11乘以11的表格,分别为布雷和排雷后的表格,其中我们以字符1表⽰此处有雷,字符0表⽰此处⽆雷,在布雷时我们⽤时间函数布置随机的10个雷(具体多少个雷可⾃⾏选择),在另⼀个表格中显⽰出所选位置周围雷的个数建⽴11*11的表格是因为便于统计四条边上位置周围含雷的个数⽤vs建⽴头⽂件game.n和两个源⽂件game.c和test.c(先分开讲解,在⽂章最后有三个⽂件的整体显⽰)在头⽂件中的声明有#include<stdio.h>#include<time.h>#include<stdlib.h>#define ROW 9#define COL 9#define ROWS ROW+2#define COLS COL+2#define EASY 10time.h和stdlib.h ⽂件是time.h的库函数ROW表⽰⾏,COL表⽰列,ROWS表⽰11列,COLS表⽰11⾏,EASY表⽰(简单程度)雷有10个⾸先在test.c⽂件中建⽴主函数int main(){int input = 0;srand((unsigned int)time(NULL));do{menu();printf("请选择:>");scanf("%d", &input);switch (input){case 1:game();//实现游戏的过程break;case 0:printf("退出游戏\n");break;default:printf("选择错误,请重新选择\n");break;}} while (input);return 0;}其中 srand((unsigned int)time(NULL)) 是为了能够在使⽤rand函数时每次产⽣不同的随机数其中包含两个函数,分别为菜单函数menu()和实现游戏的函数game()菜单函数为void menu(){printf("************************\n");printf("***** 1.play *********\n");printf("***** 0.exit *********\n");printf("************************\n");}主函数中整形input为输⼊的数字,1进⾏游戏,0退出游戏进⾏的游戏函数为void game(){//创建棋盘对应的数组char mine[ROWS][COLS];//布置好的雷的信息char show[ROWS][COLS];//排查出雷的信息//初始化棋盘initboard(mine, ROWS, COLS, '0');initboard(show, ROWS, COLS, '*');//打印棋盘//displayboard(mine, ROW, COL);displayboard(show, ROW, COL);//布置雷setmine(mine, ROW, COL, EASY);//displayboard(mine, ROW, COL);//排雷finemine(mine, show, ROW, COL);}1、创建棋盘在游戏函数中我们⾸先创建两个11乘以11的棋盘,布置雷的棋盘为mine[ROWS][COLS],在玩家⾯前显⽰的棋盘为show[ROWS][COLS]2、初始化棋盘在布置雷的棋盘中全部填写字符0,在玩家显⽰的棋盘⾯前全部填写为字符*,头⽂件中声明//初始化棋盘void initboard(char board[ROWS][COLS], int rows, int cols,char set);game.c中具体写出函数void initboard(char board[ROWS][COLS], int rows, int cols, char set){int i = 0, j = 0;for (i = 0; i < rows; i++){for (j = 0; j < cols; j++){board[i][j] = set;}}}3、打印棋盘头⽂件声明//打印棋盘void displayboard(char board[ROWS][COLS], int row, int col);game.c中具体写出函数//打印棋盘void displayboard(char board[ROWS][COLS], int row, int col){int i = 0, j = 0;printf("-----------扫雷游戏-------------\n");for (i = 0; i <= col; i++)printf("%d ", i);printf("\n");for (i = 1; i <= row; i++){printf("%d ", i);for (j = 1; j <= col; j++){printf("%c ", board[i][j]);}printf("\n");}printf("-----------扫雷游戏-------------\n");}4、布置雷将mine函数布置出雷头⽂件//布置雷void setmine(char mine[ROWS][COLS], int row, int col, int count);count为计数器,计算布置雷的个数,初始值为EASY,在头⽂件中设置为10game.c中的函数//布置雷void setmine(char mine[ROWS][COLS], int row, int col, int count){while (count){int x = rand() % row + 1; //模9为0到8int y = rand() % col + 1;if (mine[x][y] == '0'){mine[x][y] = '1';count--;}}}rand函数产⽣随机数,模上row(9)后的数为0到8,加上1为1到9的数,棋盘本为11*11,但我们填充雷在1~9⾏,1到9列5、排雷并且在玩家⾯前显⽰出棋盘头⽂件//排雷void finemine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col);game.c中的函数//统计x,y坐标周围雷的个数int getmine(char mine[ROWS][COLS], int x, int y){return mine[x - 1][y-1] + mine[x-1][y] + mine[x - 1][y + 1] + mine[x][y - 1] + mine[x][y + 1]+ mine[x + 1][y - 1] + mine[x + 1][y] + mine[x + 1][y + 1] - 8 * '0';}//排雷+打印排雷后的棋盘void finemine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col){int win = 0;while (win<ROW*COL-EASY){printf("请输⼊要排查雷的坐标:>");int x, y;scanf("%d%d", &x, &y);//坐标合法性//坐标是不是雷,不是雷,统计周围雷的个数if (x >= 1 && x <= row&&y >= 1 &&y <= col){if (mine[x][y]=='1'){printf("很遗憾,你被炸死了\n");displayboard(mine, row, col);break;}else{//坐标不是雷,统计雷的个数int count = getmine(mine, x, y);show[x][y] = count+'0';//数字加上字符0为字符数字,转化为字符数字,因为打印的为字符displayboard(show, row, col); //打印排雷后的棋盘win++;}}else{printf("坐标⾮法,重新输⼊!\n");}}if (win == ROW*COL - EASY){printf("恭喜你,排雷成功\n");displayboard(mine, row, col);}}win为已排查出⾮雷的个数判断⾮雷位置周围8个位置有雷的个数只需要将周围8个位置中的字符相加再减去8个0的ascll值,因为8个位置中有雷的位置即为字符1,将8个位置的字符相加转化为实际的数字,即为雷的个数,当排除出的⾮雷的个数为ROWSCOLS-EASY(99-10)时,即扫雷成功game.h中完整⽂件为#include<stdio.h>#include<time.h>#include<stdlib.h>#define ROW 9#define COL 9#define ROWS ROW+2#define COLS COL+2#define EASY 10//初始化棋盘void initboard(char board[ROWS][COLS], int rows, int cols,char set);//打印棋盘void displayboard(char board[ROWS][COLS], int row, int col);//布置雷void setmine(char mine[ROWS][COLS], int row, int col, int count);//排雷void finemine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col);game.c中完整⽂件为#define _CRT_SECURE_NO_WARNINGS#include"game.h"//初始化棋盘void initboard(char board[ROWS][COLS], int rows, int cols, char set){int i = 0, j = 0;for (i = 0; i < rows; i++){for (j = 0; j < cols; j++){board[i][j] = set;}}}//打印棋盘void displayboard(char board[ROWS][COLS], int row, int col){int i = 0, j = 0;printf("-----------扫雷游戏-------------\n");for (i = 0; i <= col; i++)printf("%d ", i);printf("\n");for (i = 1; i <= row; i++){printf("%d ", i);for (j = 1; j <= col; j++){printf("%c ", board[i][j]);}printf("\n");}printf("-----------扫雷游戏-------------\n");}//布置雷void setmine(char mine[ROWS][COLS], int row, int col, int count){while (count){int x = rand() % row + 1; //模9为0到8int y = rand() % col + 1;if (mine[x][y] == '0'){mine[x][y] = '1';count--;}}}//统计x,y坐标周围雷的个数int getmine(char mine[ROWS][COLS], int x, int y){return mine[x - 1][y-1] + mine[x-1][y] + mine[x - 1][y + 1] + mine[x][y - 1] + mine[x][y + 1] + mine[x + 1][y - 1] + mine[x + 1][y] + mine[x + 1][y + 1] - 8 * '0';}//排雷+打印排雷后的棋盘void finemine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col){int win = 0;while (win<ROW*COL-EASY){printf("请输⼊要排查雷的坐标:>");int x, y;scanf("%d%d", &x, &y);//坐标合法性//坐标是不是雷,不是雷,统计周围雷的个数if (x >= 1 && x <= row&&y >= 1 &&y <= col){if (mine[x][y]=='1'){printf("很遗憾,你被炸死了\n");displayboard(mine, row, col);break;}else{//坐标不是雷,统计雷的个数int count = getmine(mine, x, y);show[x][y] = count+'0';//数字加上字符0为字符数字,转化为字符数字,因为打印的为字符 displayboard(show, row, col); //打印排雷后的棋盘win++;}}else{printf("坐标⾮法,重新输⼊!\n");}}if (win == ROW*COL - EASY){printf("恭喜你,排雷成功\n");displayboard(mine, row, col);}}test.c完整⽂件为#define _CRT_SECURE_NO_WARNINGS#include "game.h"void menu(){printf("************************\n");printf("***** 1.play *********\n");printf("***** 0.exit *********\n");printf("************************\n");}void game(){//创建棋盘对应的数组char mine[ROWS][COLS];//布置好的雷的信息char show[ROWS][COLS];//排查出雷的信息//初始化棋盘initboard(mine, ROWS, COLS, '0');initboard(show, ROWS, COLS, '*');//打印棋盘//displayboard(mine, ROW, COL);displayboard(show, ROW, COL);//布置雷setmine(mine, ROW, COL, EASY);//displayboard(mine, ROW, COL);//排雷finemine(mine, show, ROW, COL);}int main(){int input = 0;srand((unsigned int)time(NULL));do{menu();printf("请选择:>");scanf("%d", &input);switch (input){case 1:game();//实现游戏的过程break;case 0:printf("退出游戏\n");break;default:printf("选择错误,请重新选择\n");break;}} while (input);return 0;}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
扫雷小游戏代码c版
intlei;intline,arrange,thunder1,thunder2,space;voidsaolei(char**&a,char**&c,int**&b,int**&d,int**&e,int**&g,int&line,int&a rrange,int&thunder1,int&thunder2,int&space){intall=1;while(all){inti,j;a=newchar*[line],c=newchar*[line],b=newint*[line],d=newint*[line],e=newint*[ line],g=newint*[line];for(i=0;i<=line-1;i++)a[i]=newchar[arrange],c[i]=newchar[arrange],b[i]=newint[arrange],d[i]=newint[arrange],e[i]=newint[arrange],g[i]=newint[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;intk;srand(int(time(0)));intz=1;while(z){k=rand()%(thunder2+1);if(k>=thunder1)z=0;}srand(int(time(0)));for(i=1;i<=k;i++){ints,t;L:{s=rand()%line;t=rand()%arrange;}if(!(s>=0&&s<line&&t>=0&&t<arrange&&a[s][t]!='#')) gotoL;for(intm=0;m<line;m++)for(intn=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]=='#')b[i][j]++;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]++;}intf=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;elsed[i][j]=0;}elseif(i==0&&j==0||i==0&&j==arrange-1||i==line-1&&j==0||i==line-1&&j==arrange-1){if(f==3)d[i][j]=1;elsed[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;elsed[i][j]=0;}}f=0;}}intx,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<<" ";elsecout<<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;intdir=3,fu=0,pan=1,ci=0;intm=i,n=j;do{switch(dir){case1 ://向左走{if(m-1>=0&&d[m-1][n]==1) {d[m-1][n]=3;m--;dir=2;}//检测所在位置右边elseif(n-1>=0&&d[m][n-1]==1) {d[m][n-1]=3;n--;dir=1;}//检测所在位置前方elseif(m+1<line&&d[m+1][n]==1) {d[m+1][n]=3;m++;dir=4;}//检测所在位置左边elseif(n+1<arrange&&d[m][n+1]==1){d[m][n+1]=3;n++;dir=3;}//检测所在位置后方elseif(m-1>=0&&d[m-1][n]==3) {m--;dir=2;}//检测所在位置右边elseif(n-1>=0&&d[m][n-1]==3) {n--;dir=1;}//检测所在位置前方elseif(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;case2 ://向上走elseif(m-1>=0&&d[m-1][n]==1) {d[m-1][n]=3;m--;dir=2;}//检测所在位置前方elseif(n-1>=0&&d[m][n-1]==1) {d[m][n-1]=3;n--;dir=1;}//检测所在位置左边elseif(m+1<line&&d[m+1][n]==1){d[m+1][n]=3;m++;dir=4;}//检测所在位置后方elseif(n+1<arrange&&d[m][n+1]==3) {n++;dir=3;}//检测所在位置右边elseif(m-1>=0&&d[m-1][n]==3) {m--;dir=2;}//检测所在位置前方elseif(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;case3 ://向右走{if(m+1<line&&d[m+1][n]==1) {d[m+1][n]=3;m++;dir=4;}//检测所在位置右边elseif(n+1<arrange&&d[m][n+1]==1) {d[m][n+1]=3;n++;dir=3;}//检测所在位置前方elseif(m-1>=0&&d[m-1][n]==1) {d[m-1][n]=3;m--;dir=2;}//检测所在位置左边elseif(n-1>=0&&d[m][n-1]==1){d[m][n-1]=3;n--;dir=1;}//检测所在位置后方elseif(m+1<line&&d[m+1][n]==3) {m++;dir=4;}//检测所在位置右边elseif(n+1<arrange&&d[m][n+1]==3) {n++;dir=3;}//检测所在位置前方elseif(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;case4 ://向下走{if(n-1>=0&&d[m][n-1]==1) {d[m][n-1]=3;n--;dir=1;}//检测所在位置右边方elseif(n+1<arrange&&d[m][n+1]==1) {d[m][n+1]=3;n++;dir=3;}//检测所在位置左边elseif(m-1>=0&&d[m-1][n]==1){d[m-1][n]=3;m--;dir=2;}//检测所在位置后方elseif(n-1>=0&&d[m][n-1]==3) {n--;dir=1;}//检测所在位置右边elseif(m+1<line&&d[m+1][n]==3) {m++;dir=4;}//检测所在位置前方elseif(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++)}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;for(shu=0;shu<arrange;shu++) if(d[hang][shu]==3)d[hang][shu]=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<<" ";elsecout<<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]<<" "; elsecout<<b[i][j]<<" "; }elseif(i==x&&y==j)cout<<b[i][j]<<" ";elsecout<<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<<" ";elsecout<<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]<<" ";elsecout<<b[i][j]<<" ";}elseif(e[i][j]==1)cout<<b[i][j]<<" ";elsecout<<c[i][j]<<" ";cout<<endl;}if(lei==1){jishu++;if(jishu<=3)cout<<"提示:判断错误"<<jishu<<"次,若判断错误超过三次,你将输掉游戏,注意哦o(︶︿︶)o"<<endl;}}//第二种情况if(a[x][y]=='#'&&lei==0) {for(i=1;i<=space;i++) cout<<" ";for(i=0;i<=line;i++)if(i<=9)cout<<i<<" ";elsecout<<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]<<" ";elsecout<<b[i][j]<<" ";}elseif(e[i][j]==1)cout<<a[i][j]<<" ";elseif(a[i][j]=='#')cout<<a[i][j]<<" ";elsecout<<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<<" ";elsecout<<i;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]<<" "; elsecout<<b[i][j]<<" "; }elseif(e[i][j]==1)cout<<a[i][j]<<" "; elsecout<<c[i][j]<<" ";}}//第四种情况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;intsum=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;}inttotal=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;}}//循环并判断是否继续循环}}intmain(){L:{cout<<"游戏名称:扫雷"<<'\n'<<"--------------------------------------------------------------------------------"<<'\n'<<"说明:.代表未翻开的地方;#表示雷;翻开地方显示的数字表示:该地方四周的八个相邻的地方含有雷的总数"<<'\n'<<"--------------------------------------------------------------------------------"<<'\n'<<"规则:根据翻开地方显示的数字判断雷所在的地方"<<'\n'<<"--------------------------------------------------------------------------------"<<'\n'<<"操作:根据判断,请输入位置(如:<<'\n'<<"--------------------------------------------------------------------------------"<<'\n'<<"解释:输入的三个数字中,前两个数字表示位置,如:表示行数,表示列数;第三个表示判断与选择,--无雷,--有雷,--再来一局,--结束游戏,--重启整个游戏系统"<<'\n'<<"--------------------------------------------------------------------------------"<<'\n'<<"例如:5 6 0表示游戏者认为该处无雷,6 1表示游戏者认为该处有雷,6 2表示再来一局,6 3表示结束游戏,6 4表示重启游戏系统"<<'\n'<<"--------------------------------------------------------------------------------"<<endl;intchoice,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;gotoM;}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");gotoL;}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;}}。
扫雷源代码(精)
#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语言扫雷游戏代码及详细注释扫雷游戏代码及详细注释扫雷游戏做为c语言初学者的编程练习还是很不错的,那么本篇文章详细注释了扫雷代码中的各行代码的含义以及作用,对初学者来说还是很有帮助的。
一、game.h头文件代码1.#ifndef __GAME_H__2.#define __GAME_H__3.4.#define COLS 11 //列数5.#define ROWS 11 //行数6.#define COL (COLS-2)7.#define ROW (ROWS-2)8.#define MAX 10 //雷的个数9.10.#include<stdio.h>11.#include<stdlib.h>12.#include<time.h>13.#include<string.h>//memset头文件14.15.void init_board(char mine[ROWS][COLS], int row, int col);//声明初始化棋盘函数,在game.c实现16.void set_mine(char mine[ROWS][COLS]); //声明布雷函数17.void display(char mine[ROWS][COLS], int row, int col);//声明打印棋盘函数18.int get_mine_count(char mine[ROWS][COLS], int x, int y);//声明统计坐标周围雷的数目函数19.20.#endif//__GAME_H__二、game.c代码1.#define _CRT_SECURE_NO_WARNINGS 12.3.#include'game.h'4.5.void init_board(char mine[ROWS][COLS], char set, int row, int col)//初始化棋盘函数为set6.{7.memset(mine, set, row*col*sizeof(mine[0][0])); //memset 本身就有初始化功能括号内容依次为:8.} //数组名,初始化目标,总共初始化字节9.10.void set_mine(char mine[ROWS][COLS])//随机布雷函数11.{12.int count = MAX;//设置计数器,记录要布入雷的个数13.while(count>0)14.{15.int x = rand()%9+1;//产生1到9的随机数字16.int y = rand()%9+1;17.if((mine[x][y]) == '0') //判断同一位置是否重复布雷18.{19.mine[x][y] = '1';20.count--; //每成功布雷一颗,计数器就减一21.}22.}23.}24.25.void display(char mine[ROWS][COLS], int row, int col)//打印棋盘函数26.{27.int i = 0;28.int j = 0;29.printf(' ');//两个空格,为了使对齐,一个留给列号,一个留给棋盘30.for(i=1; i<=row-2; i++)//打印列号31.{32.printf('%d ', i);33.}34.printf('\n');35.for(i = 1; i<=row-2; i++)//输出的是棋盘信息36.{37.printf('%d ', i);38.for(j=1; j<=col-2; j++)39.{40.printf('%c ', mine[i][j]);//41.}42.printf('\n');43.}44.}45.46.int get_mine_count(char mine[ROWS][COLS], int x, int y)//统计坐标周围雷数目的函数47.{48.return mine[x-1][y-1]49.+mine[x][y-1]+mine[x+1][y-1]50.+mine[x+1][y]+mine[x+1][y+1]51.+mine[x][y+1]+mine[x-1][y+1]52.+mine[x-1][y]-8*'0'; //由于数组中存放的是字符'0',周围是8个数字,所以-8*'0'才能返回雷数的int值53.}三、test.c代码1.#define _CRT_SECURE_NO_WARNINGS 12.#include'game.h'3.4.void menu()5.{6.printf('*********************************\n');7.printf('*********1.play 0.exit***********\n');8.printf('*********************************\n');9.}10.11.enum Option //枚举,增加代码可读性12.{13.EXIT, //默认为014.PLAY //为115.};16.17.void game()18.{19.char mine[ROWS][COLS] = {0};//非雷的位置可初始化为零20.char show[ROWS][COLS] = {0};//创建一个和mine一样大的数组来存放,坐标周围雷的数目21.int x = 0;22.int y = 0;23.int win = 0;24.init_board(mine, '0', ROWS, COLS);//初始化数组,各位置放零25.init_board(show, '*', ROWS, COLS);//初始化数组,各位置放*26.27.set_mine(mine);//布雷28.display(show, ROWS, COLS);//打印棋盘29.while(win<(ROW*COL-MAX)) //非雷的个数30.{31.printf('请输入排查坐标:>');32.scanf('%d%d', &x, &y);33.if(((x>=1)&&(x<=ROWS-2))&&((y>=1)&&(y<=COLS-2)))//判断输入坐标是否在棋盘内34.{35.if(mine[x][y] == '1')36.{37.printf('很不幸,踩到地雷\n');38.break;39.}40.else //每进入一次意味着排完一颗雷41.{42.43.int count = get_mine_count(mine, x, y);//通过此函数统计指定坐标周围有几个雷44.show[x][y] = count+'0';//为了打印*,所以把display函数打印的类型改为%c打印出来的是字符。
扫雷c语言代码
扫雷c语言代码该程序是一个经典的扫雷游戏,使用C语言编写。
该游戏的规则是将地图上的所有地雷挖出来而不触发任何地雷。
以下是该程序的代码:#include <stdio.h>#include <stdlib.h>#include <time.h>// 定义常量#define MAX_ROW 9#define MAX_COL 9#define MINES 10char mineField[MAX_ROW][MAX_COL]; // 地图char gameField[MAX_ROW][MAX_COL]; // 游戏中的视图// 初始化地图void initMineField() {int i, j, count;srand(time(NULL));// 随机放置地雷for (i=0; i<MAX_ROW; i++) {for (j=0; j<MAX_COL; j++) {mineField[i][j] = '0';}}count = 0;while (count < MINES) {i = rand() % MAX_ROW;j = rand() % MAX_COL;if (mineField[i][j] == '0') {mineField[i][j] = '*';count++;}}// 计算周围的地雷数for (i=0; i<MAX_ROW; i++) {for (j=0; j<MAX_COL; j++) {if (mineField[i][j] == '*') {continue;}if (i > 0 && j > 0 && mineField[i-1][j-1] == '*') {mineField[i][j]++;}if (i > 0 && mineField[i-1][j] == '*') {mineField[i][j]++;}if (i > 0 && j < MAX_COL-1 && mineField[i-1][j+1] == '*') {mineField[i][j]++;}if (j > 0 && mineField[i][j-1] == '*') {mineField[i][j]++;}if (j < MAX_COL-1 && mineField[i][j+1] == '*') { mineField[i][j]++;}if (i < MAX_ROW-1 && j > 0 && mineField[i+1][j-1] == '*') {mineField[i][j]++;}if (i < MAX_ROW-1 && mineField[i+1][j] == '*') { mineField[i][j]++;}if (i < MAX_ROW-1 && j < MAX_COL-1 &&mineField[i+1][j+1] == '*') {mineField[i][j]++;}}}}// 显示游戏视图void displayGameField() {int i, j;// 清屏system("cls");printf(" ");for (j=0; j<MAX_COL; j++) {printf(" %d", j+1);}printf(" \n");printf(" +");for (j=0; j<MAX_COL; j++) {printf("--");}printf("-+\n");for (i=0; i<MAX_ROW; i++) {printf("%c|", i+'A');for (j=0; j<MAX_COL; j++) {printf(" %c", gameField[i][j]);}printf(" |\n");}printf(" +");for (j=0; j<MAX_COL; j++) {printf("--");}printf("-+\n");}// 打开格子void open(int row, int col) {if (row < 0 || row >= MAX_ROW || col < 0 || col >= MAX_COL) {// 超出范围return;}if (gameField[row][col] != '-') {// 已经打开return;}gameField[row][col] = mineField[row][col];if (mineField[row][col] == '*') {// 触雷displayGameField();printf("Game over!\n");exit(0);}if (mineField[row][col] != '0') {// 周围有地雷return;}// 递归打开周围的格子open(row-1, col-1);open(row-1, col);open(row-1, col+1);open(row, col-1);open(row, col+1);open(row+1, col-1);open(row+1, col);open(row+1, col+1);}// 主函数int main() {int i, j, row, col, remain = MAX_ROW * MAX_COL - MINES; char command;initMineField();for (i=0; i<MAX_ROW; i++) {for (j=0; j<MAX_COL; j++) {gameField[i][j] = '-';}}displayGameField();while (remain > 0) {printf("Please enter your command (open/o, flag/f, unflag/u):");scanf("%c %d %d", &command, &row, &col);getchar(); // 读取回车符row--;col--;switch (command) {case 'o':open(row, col);remain--;break;case 'f':gameField[row][col] = 'F'; break;case 'u':gameField[row][col] = '-'; break;}displayGameField();}printf("You win!\n");return 0;}。
c语言编写扫雷代码
c语言编写扫雷代码示例编写扫雷游戏的代码涉及到图形界面、事件处理等,因此需要使用相应的库来简化这些操作。
下面是一个使用C语言和Simple DirectMedia Layer (SDL)库编写的简单扫雷游戏的代码示例。
请注意,这只是一个基本的示例,实际的扫雷游戏可能需要更多功能和复杂性。
首先,确保你已经安装了SDL库。
接下来,你可以使用以下代码作为一个简单的扫雷游戏的起点。
```c#include <SDL.h>#include <stdio.h>#include <stdlib.h>#include <time.h>// 游戏常量#define SCREEN_WIDTH 640#define SCREEN_HEIGHT 480#define CELL_SIZE 20#define ROWS 15#define COLS 20#define MINES 40// 游戏状态typedef struct {int revealed; // 是否被揭示int mine; // 是否是地雷int adjacent; // 相邻地雷数量} Cell;// 游戏数据Cell board[ROWS][COLS];// SDL 相关变量SDL_Window* window = NULL;SDL_Renderer* renderer = NULL;// 初始化游戏板void initializeBoard() {// 初始化每个单元格for (int i = 0; i < ROWS; ++i) {for (int j = 0; j < COLS; ++j) {board[i][j].revealed = 0;board[i][j].mine = 0;board[i][j].adjacent = 0;}}// 随机生成地雷位置srand(time(NULL));for (int k = 0; k < MINES; ++k) {int i = rand() % ROWS;int j = rand() % COLS;if (!board[i][j].mine) {board[i][j].mine = 1;// 增加相邻地雷数量for (int ni = i - 1; ni <= i + 1; ++ni) {for (int nj = j - 1; nj <= j + 1; ++nj) {if (ni >= 0 && ni < ROWS && nj >= 0 && nj < COLS && !(ni == i && nj == j)) {board[ni][nj].adjacent++;}}}} else {// 如果已经有地雷,重新生成k--;}}}// 渲染游戏板void renderBoard() {// 清空屏幕SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);SDL_RenderClear(renderer);// 绘制每个单元格for (int i = 0; i < ROWS; ++i) {for (int j = 0; j < COLS; ++j) {if (board[i][j].revealed) {// 已揭示的单元格if (board[i][j].mine) {SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255); // 地雷} else {SDL_SetRenderDrawColor(renderer, 192, 192, 192, 255); // 其他}} else {// 未揭示的单元格SDL_SetRenderDrawColor(renderer, 128, 128, 128, 255);}// 绘制单元格SDL_Rect cellRect = {j * CELL_SIZE, i * CELL_SIZE, CELL_SIZE, CELL_SIZE};SDL_RenderFillRect(renderer, &cellRect);// 绘制地雷数量(已揭示的单元格)if (board[i][j].revealed && !board[i][j].mine && board[i][j].adjacent > 0) {char text[2];snprintf(text, sizeof(text), "%d", board[i][j].adjacent);SDL_Color textColor = {0, 0, 0, 255};SDL_Surface* surface = TTF_RenderText_Solid(font, text, textColor);SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);SDL_Rect textRect = {j * CELL_SIZE + CELL_SIZE / 3, i * CELL_SIZE + CELL_SIZE / 3, CELL_SIZE / 2, CELL_SIZE / 2};SDL_RenderCopy(renderer, texture, NULL, &textRect);SDL_DestroyTexture(texture);SDL_FreeSurface(surface);}}}// 刷新屏幕SDL_RenderPresent(renderer);}// 处理鼠标点击事件void handleMouseClick(int x, int y) {int i = y / CELL_SIZE;int j = x / CELL_SIZE;if (!board[i][j].revealed) {board[i][j].revealed = 1;if (board[i][j].mine) {// 点击到地雷,游戏结束printf("Game Over!\n");SDL_Quit();exit(1);} else {// 递归揭示相邻单元格if (board[i][j].adjacent == 0) {for (int ni = i - 1; ni <= i + 1; ++ni) {for (int nj = j - 1; nj <= j + 1; ++nj) {if (ni >= 0 && ni < ROWS && nj >= 0 && nj < COLS && !(ni == i && nj == j)) {handleMouseClick(nj * CELL_SIZE, ni * CELL_SIZE);}}}}}}}int main() {// 初始化SDLSDL_Init(SDL_INIT_VIDEO);// 创建窗口和渲染器window = SDL_CreateWindow("Minesweeper", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);// 初始化游戏板initializeBoard();// 游戏循环int quit = 0;SDL_Event e;while (!quit) {// 处理事件while (SDL_PollEvent(&e) != 0) {if (e.type == SDL_QUIT) {quit = 1;} else if (e.type == SDL_MOUSEBUTTONDOWN) {if (e.button.button == SDL_BUTTON_LEFT) {handleMouseClick(e.button.x, e.button.y);}}}//渲染游戏板renderBoard();}// 清理资源SDL_DestroyWindow(window);SDL_DestroyRenderer(renderer);SDL_Quit();return 0;}```这是一个简单的扫雷游戏的C语言代码,使用SDL库来创建窗口、处理事件和渲染图形。
c语言扫雷程序代码
c语言扫雷程序代码以下是一份基于C语言编写的扫雷程序代码,供参考:#include <stdio.h>#include <stdlib.h>#include <time.h>#define ROW 10 // 扫雷区域行数#define COL 10 // 扫雷区域列数#define MINE_NUM 10 // 地雷数量int mine_map[ROW][COL] = {0}; // 扫雷地图数组 int show_map[ROW][COL] = {0}; // 显示地图数组 // 随机生成地雷void create_mine() {int i, j, k;for (k = 0; k < MINE_NUM; k++) {i = rand() % ROW;j = rand() % COL;if (mine_map[i][j] == 9) { // 该位置已有地雷 k--;continue;}mine_map[i][j] = 9; // 设定该位置为地雷 }}// 统计周围的地雷数量int count_mine(int x, int y) {int count = 0, i, j;for (i = x - 1; i <= x + 1; i++) {for (j = y - 1; j <= y + 1; j++) {if (i < 0 || i >= ROW || j < 0 || j >= COL) { // 超出地图边界continue;}if (mine_map[i][j] == 9) { // 周围有地雷count++;}}}return count;}// 初始化显示地图void init_show_map() {int i, j;for (i = 0; i < ROW; i++) {for (j = 0; j < COL; j++) {show_map[i][j] = 10; // 10代表未翻开 }}}// 显示地图void show() {int i, j;printf(' ');for (i = 0; i < COL; i++) {printf('%d ', i);}printf('');for (i = 0; i < ROW; i++) {printf('%d ', i);for (j = 0; j < COL; j++) {if (show_map[i][j] == 10) {printf('* ');} else if (show_map[i][j] == 9) {printf('P ');} else if (show_map[i][j] == 0) {printf(' ');} else {printf('%d ', show_map[i][j]);}}printf('');}}// 翻开指定位置void open(int x, int y) {if (mine_map[x][y] == 9) { // 踩到地雷 printf('Game Over!');show_map[x][y] = 9;show();exit(0);}if (show_map[x][y] == 10) { // 未翻开int count = count_mine(x, y);show_map[x][y] = count;if (count == 0) { // 周围没有地雷 int i, j;for (i = x - 1; i <= x + 1; i++) {for (j = y - 1; j <= y + 1; j++) {if (i < 0 || i >= ROW || j < 0 || j >= COL) { // 超出地图边界continue;}open(i, j);}}}}}int main() {int i, j, x, y;srand(time(NULL));create_mine();init_show_map();show();while (1) {printf('Please input x and y: ');scanf('%d%d', &x, &y);open(x, y);show(); }return 0; }。
c语言扫雷代码
c语言扫雷代码以下是一份简单的C语言扫雷代码,用于实现经典扫雷游戏的基本功能:#include <stdio.h>#include <stdlib.h>#include <time.h>#define ROWS 10#define COLS 10#define MINES 10int main(void){int field[ROWS][COLS] = {0}; // 初始化游戏区域int mines[MINES][2] = {0}; // 初始化地雷坐标数组int i, j, k, x, y, count, gameover = 0;srand(time(NULL)); // 初始化随机数生成器// 随机布置地雷for (k = 0; k < MINES; k++) {do {x = rand() % ROWS;y = rand() % COLS;} while (field[x][y] == -1);mines[k][0] = x;mines[k][1] = y;field[x][y] = -1;}// 计算每个非地雷格子周围地雷数for (i = 0; i < ROWS; i++) {for (j = 0; j < COLS; j++) {if (field[i][j] != -1) {count = 0;if (i > 0 && j > 0 && field[i-1][j-1] == -1) count++;if (i > 0 && field[i-1][j] == -1) count++;if (i > 0 && j < COLS-1 && field[i-1][j+1] == -1) count++; if (j > 0 && field[i][j-1] == -1) count++;if (j < COLS-1 && field[i][j+1] == -1) count++;if (i < ROWS-1 && j > 0 && field[i+1][j-1] == -1) count++; if (i < ROWS-1 && field[i+1][j] == -1) count++;if (i < ROWS-1 && j < COLS-1 && field[i+1][j+1] == -1) count++;field[i][j] = count;}}}// 游戏开始,循环猜测地雷位置并扫开周围格子while (!gameover) {// 打印游戏区域printf(' ');for (j = 0; j < COLS; j++) {printf('%d ', j);}printf('');for (i = 0; i < ROWS; i++) {printf('%d ', i);for (j = 0; j < COLS; j++) {if (field[i][j] < 0) {printf('* ');} else {printf('%d ', field[i][j]);}}printf('');}// 用户输入坐标猜测地雷位置printf('Enter row and column: ');scanf('%d %d', &x, &y);// 判断用户猜测是否正确for (k = 0; k < MINES; k++) {if (x == mines[k][0] && y == mines[k][1]) {printf('BOOM! You lose.');gameover = 1;break;}}// 扫开周围格子if (!gameover) {if (field[x][y] == 0) {if (x > 0 && field[x-1][y] >= 0) field[x-1][y] = -2;if (x > 0 && y > 0 && field[x-1][y-1] >= 0) field[x-1][y-1] = -2;if (x > 0 && y < COLS-1 && field[x-1][y+1] >= 0)field[x-1][y+1] = -2;if (y > 0 && field[x][y-1] >= 0) field[x][y-1] = -2;if (y < COLS-1 && field[x][y+1] >= 0) field[x][y+1] = -2; if (x < ROWS-1 && field[x+1][y] >= 0) field[x+1][y] = -2; if (x < ROWS-1 && y > 0 && field[x+1][y-1] >= 0)if (x < ROWS-1 && y < COLS-1 && field[x+1][y+1] >= 0) field[x+1][y+1] = -2;for (i = 0; i < ROWS; i++) {for (j = 0; j < COLS; j++) {if (field[i][j] == -2) {field[i][j] = -1;count = 0;if (i > 0 && j > 0 && field[i-1][j-1] == -1) count++;if (i > 0 && field[i-1][j] == -1) count++;if (i > 0 && j < COLS-1 && field[i-1][j+1] == -1) count++; if (j > 0 && field[i][j-1] == -1) count++;if (j < COLS-1 && field[i][j+1] == -1) count++;if (i < ROWS-1 && j > 0 && field[i+1][j-1] == -1) count++; if (i < ROWS-1 && field[i+1][j] == -1) count++;if (i < ROWS-1 && j < COLS-1 && field[i+1][j+1] == -1) count++;field[i][j] = count;}}}} else {count = 0;if (x > 0 && j > 0 && field[x-1][y-1] == -1) count++;if (x > 0 && field[x-1][y] == -1) count++;if (x > 0 && y < COLS-1 && field[x-1][y+1] == -1) count++; if (y > 0 && field[x][y-1] == -1) count++;if (y < COLS-1 && field[x][y+1] == -1) count++;if (x < ROWS-1 && y > 0 && field[x+1][y-1] == -1) count++; if (x < ROWS-1 && field[x+1][y] == -1) count++;if (x < ROWS-1 && y < COLS-1 && field[x+1][y+1] == -1) count++;field[x][y] = count;}}// 判断游戏是否胜利count = 0;for (i = 0; i < ROWS; i++) {for (j = 0; j < COLS; j++) {if (field[i][j] >= 0) count++;}}if (count == ROWS * COLS - MINES) {printf('Congratulations! You win. ');gameover = 1;}}return 0;}。
c语言扫雷程序代码
c语言扫雷程序代码很高兴能够回答这个问题,关于c语言扫雷程序代码,以下是一个简单的实现示例。
#include<stdio.h>#include<stdlib.h>#include<time.h>#define ROW 9#define COL 9#define COUNT 10void menu()//游戏主菜单{printf("*****************\n");printf("*****扫雷游戏*****\n");printf("*****************\n");printf("*** 1.开始游戏 ***\n");printf("*** 0.退出游戏 ***\n");printf("*****************\n");}void init_board(char board[ROW + 2][COL + 2], int row, int col, char ch)//初始化扫雷棋盘{int i = 0;int j = 0;for (i = 1; i <= row; i++){for (j = 1; j <= col; j++){board[i][j] = ch;}}}void show_board_with_numbers(char mine_board[ROW +2][COL + 2], char show_board[ROW + 2][COL + 2], int row, int col)//棋盘及数字{printf(" ");for (int i = 1; i <= row; i++){printf("%d ", i);}printf("\n");printf(" ");for (int i = 1; i <= row; i++){printf("- ");}printf("\n");for (int i = 1; i <= row; i++){printf("%2d|", i);for (int j = 1; j <= col; j++){if (show_board[i][j] == 'o'){printf("%c ", mine_board[i][j]);}else{printf("%c ", show_board[i][j]); }}putchar('\n');}}int get_all_count(char mine_board[ROW + 1][COL + 1], int x, int y)//计算当前位置周围地雷数量{int count = 0;for (int i = x - 1; i <= x + 1; i++){for (int j = y - 1; j <= y + 1; j++){if (i >= 1 && i <= ROW && j >= 1 && j <= COL && mine_board[i][j] == '*'){count++;}}}return count;}void find_mine(int x, int y, char mine_board[ROW + 2][COL + 2],char show_board[ROW + 2][COL + 2])//查找地雷并标记{if (mine_board[x][y] == '*'){return;}else{int count = get_all_count(mine_board, x, y);show_board[x][y] = count + '0';if (count == 0){for (int i = x - 1; i <= x + 1; i++){for (int j = y - 1; j <= y + 1; j++){if (i >= 1 && i <= ROW && j >= 1 && j <= COL && show_board[i][j] == 'o'){find_mine(i, j, mine_board, show_board);}}}}}}void set_mine(char mine_board[ROW + 2][COL + 2], int count)//随机放置地雷{int x = 0;int y = 0;int i = 0;int j = 0;for (i = 0; i <= ROW; i++){mine_board[i][0] = '1';mine_board[i][COL + 1] = '1';}for (j = 0; j <= COL; j++) {mine_board[0][j] = '1';mine_board[ROW + 1][j] = '1';}srand((unsigned)time(NULL));for (i = 0; i < count; i++){x = rand() % ROW + 1;y = rand() % COL + 1;if (mine_board[x][y] == '*'){i--;}else{mine_board[x][y] = '*';}}}void game()//游戏主程序{char mine_board[ROW + 2][COL + 2]; char show_board[ROW + 2][COL + 2]; int x = 0;int y = 0;int win = 0;init_board(mine_board, ROW, COL, '0'); init_board(show_board, ROW, COL, 'o');set_mine(mine_board, COUNT);show_board_with_numbers(mine_board, show_board, ROW, COL);while (1){printf("请输入你要排查的方格坐标(x,y):");scanf("%d,%d", &x, &y);if (x >= 1 && x <= ROW && y >= 1 && y <= COL){if (mine_board[x][y] == '*'){printf("不好意思,你踩到地雷了!\n");break;}else{find_mine(x, y, mine_board, show_board);printf("当前棋盘状态如下:\n");show_board_with_numbers(mine_board, show_board, ROW, COL);win = win + ROW * COL - COUNT;for (int i = 1; i <= ROW; i++){for (int j = 1; j <= COL; j++){if (show_board[i][j] != 'o'){win--;}}}if (win == 0){printf("你赢了!\n");break;}}}else{printf("输入坐标有误,请重新输入!\n"); }}}int main()//主程序{int choice = 0;do{menu();printf("请输入你的选择:");scanf("%d", &choice);switch (choice){case 1:game();break;case 0:printf("退出游戏!\n");break;default:printf("输入有误,请重新输入!\n"); break;}} while (choice);return 0;}以上就是一个简单的c语言扫雷程序的实现,希望对你有所帮助。
c语言扫雷源代码
c语言扫雷源代码扫雷游戏是一种非常经典的单人益智游戏,玩家需要根据数字提示找出地雷的位置。
下面给出一个简单的C语言扫雷游戏的源代码示例:```c#include <stdio.h>#include <stdlib.h>#include <time.h>#define SIZE 10 // 扫雷游戏的大小#define MINE_COUNT 10 // 地雷的数量typedef struct {int x;int y;} Position;typedef struct {int isMine; // 是否是地雷int isFlagged; // 是否被标记为地雷int isRevealed; // 是否已被翻开int adjacentMines; // 相邻地雷的数量} Cell;Cell board[SIZE][SIZE];void initializeBoard() {int i, j;// 初始化游戏面板for (i = 0; i < SIZE; i++) {for (j = 0; j < SIZE; j++) {board[i][j].isMine = 0;board[i][j].isFlagged = 0;board[i][j].isRevealed = 0;board[i][j].adjacentMines = 0;}}}void generateMines() {int i, j;int count = 0;srand(time(NULL)); // 以当前时间作为随机数种子 while (count < MINE_COUNT) {i = rand() % SIZE;j = rand() % SIZE;// 如果该格子已经是地雷,则重新生成随机位置 if (!board[i][j].isMine) {board[i][j].isMine = 1;count++;}}}void calculateAdjacentMines() {int i, j, k, l;int dx[] = {-1, -1, -1, 0, 0, 1, 1, 1};int dy[] = {-1, 0, 1, -1, 1, -1, 0, 1};for (i = 0; i < SIZE; i++) {for (j = 0; j < SIZE; j++) {if (!board[i][j].isMine) {for (k = 0; k < 8; k++) {int ni = i + dx[k];int nj = j + dy[k];if (ni >= 0 && ni < SIZE && nj >= 0 && nj < SIZE && board[ni][nj].isMine) {board[i][j].adjacentMines++;}}}}}}void displayBoard() {int i, j;printf(" ");for (i = 0; i < SIZE; i++) {printf("%d ", i);}printf("\n");for (i = 0; i < SIZE; i++) {printf("%d ", i);for (j = 0; j < SIZE; j++) {if (board[i][j].isRevealed) {if (board[i][j].isMine) {printf("M ");} else {printf("%d ", board[i][j].adjacentMines);}} else if (board[i][j].isFlagged) {printf("F ");} else {printf(". ");}}printf("\n");}}void revealAdjacentEmptyCells(Position pos) {int dx[] = {-1, -1, -1, 0, 0, 1, 1, 1};int dy[] = {-1, 0, 1, -1, 1, -1, 0, 1};int i;for (i = 0; i < 8; i++) {int ni = pos.x + dx[i];int nj = pos.y + dy[i];if (ni >= 0 && ni < SIZE && nj >= 0 && nj < SIZE && !board[ni][nj].isRevealed && !board[ni][nj].isMine) { board[ni][nj].isRevealed = 1;if (board[ni][nj].adjacentMines == 0) {Position newPos;newPos.x = ni;newPos.y = nj;revealAdjacentEmptyCells(newPos);}}}}int main() {Position pos;char cmd;int isSuccess = 0;initializeBoard();generateMines();calculateAdjacentMines();displayBoard();while (!isSuccess) {printf("Enter command (R: reveal, F: flag): ");fflush(stdout);scanf(" %c", &cmd);printf("Enter position (x, y): ");fflush(stdout);scanf("%d %d", &(pos.x), &(pos.y));if (cmd == 'R') {board[pos.x][pos.y].isRevealed = 1;if (board[pos.x][pos.y].isMine) {printf("Game Over!\n");isSuccess = 1;} else if (board[pos.x][pos.y].adjacentMines == 0) {revealAdjacentEmptyCells(pos);}} else if (cmd == 'F') {board[pos.x][pos.y].isFlagged = 1;}displayBoard();}return 0;}```上述代码实现了一个简单的C语言扫雷游戏。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
C语言扫雷源代码.txt如果背叛是一种勇气,那么接受背叛则需要更大的勇气。
爱情是块砖,婚姻是座山。
砖不在多,有一块就灵;山不在高,守一生就行。
#include <graphics.h> #include <stdlib.h>#include <dos.h>#include <conio.h>/*鼠标信息宏定义*/#define WAITING 0xff00#define LEFTPRESS 0xff01#define LEFTCLICK 0xff10#define LEFTDRAG 0xff19#define RIGHTPRESS 0xff02#define RIGHTCLICK 0xff20#define RIGHTDRAG 0xff2a#define MIDDLEPRESS 0xff04#define MIDDLECLICK 0xff40#define MIDDLEDRAG 0xff4c#define MOUSEMOVE 0xff08struct{int num;/*格子当前处于什么状态,1有雷,0已经显示过数字或者空白格子*/int roundnum;/*统计格子周围有多少雷*/int flag;/*右键按下显示红旗的标志,0没有红旗标志,1有红旗标志*/}Mine[10][10];int gameAGAIN=0;/*是否重来的变量*/int gamePLAY=0;/*是否是第一次玩游戏的标志*/int mineNUM;/*统计处理过的格子数*/char randmineNUM[3];/*显示数字的字符串*/int Keystate;int MouseExist;int MouseButton;int MouseX;int MouseY;int up[16][16],down[16][16],mouse_draw[16][16],pixel_save[16][16];void MouseMath()/*计算鼠标的样子*/{int i,j,jj,k;long UpNum[16]={0x3fff,0x1fff,0x0fff,0x07ff,0x03ff,0x01ff,0x00ff,0x007f,0x003f,0x00ff,0x01ff,0x10ff,0x30ff,0xf87f,0xf87f,0xfc3f };long DownNum[16]={0x0000,0x7c00,0x6000,0x7000, 0x7800,0x7c00,0x7e00,0x7f00, 0x7f80,0x7e00,0x7c00,0x4600, 0x0600,0x0300,0x0300,0x0180 };for(i=0;i<16;i++){j=jj=15;while(UpNum[i]!=0){up[i][j]=UpNum[i]%2;j--;UpNum[i]/=2;}while(DownNum[i]!=0){down[i][jj--]=DownNum[i]%2;DownNum[i]/=2;}for(k=j;k>=0;k--)up[i][k]=0;for(k=jj;k>=0;k--)down[i][k]=0;for(k=0;k<16;k++)/*四种组合方式*/{if(up[i][k]==0&&down[i][k]==0)mouse_draw[i][k]=1;else if(up[i][k]==0&&down[i][k]==1) mouse_draw[i][k]=2;else if(up[i][k]==1&&down[i][k]==0) mouse_draw[i][k]=3;elsemouse_draw[i][k]=4;}}mouse_draw[1][2]=4;/*特殊点*/}void Init(void);/*图形驱动*/void MouseOn(int,int);/*鼠标光标显示*/void MouseOff(void);/*鼠标光标隐藏*/void MouseSetXY(int,int);/*设置当前位置*/int LeftPress(void);/*左键按下*/int RightPress(void);/*鼠标右键按下*/int MiddlePress();void MouseGetXY(void);/*得到当前位置*/int MouseStatus();void Control(void);/*游戏开始,重新,关闭*/void GameBegain(void);/*游戏开始画面*/void DrawSmile(void);/*画笑脸*/void DrawRedflag(int,int);/*显示红旗*/void DrawEmpty(int,int,int,int);/*两种空格子的显示*/ void GameOver(void);/*游戏结束*/void GameWin(void);/*显示胜利*/int MineStatistics(int,int);/*统计每个格子周围的雷数*/ int ShowWhite(int,int);/*显示无雷区的空白部分*/void GamePlay(void);/*游戏过程*/void Close(void);/*图形关闭*/void main(void){Init();MouseMath();//MouseOn(MouseX,MouseY);Control();Close();}void Init(void)/*图形开始*/{int gd=DETECT,gm;registerbgidriver(EGAVGA_driver);initgraph(&gd,&gm,"");}void Close(void)/*图形关闭*/{closegraph();}/*鼠标光标显示*/void MouseOn(int x,int y){int i,j;int color;for(i=0;i<16;i++)/*画鼠标*/{for(j=0;j<16;j++){pixel_save[i][j]=getpixel(x+j,y+i);/*保存原来的颜色*/ if(mouse_draw[i][j]==1)putpixel(x+j,y+i,0);else if(mouse_draw[i][j]==2)putpixel(x+j,y+i,15);}}}/*隐藏鼠标*/void MouseOff(){int i,j,x,y,color;x=MouseX;y=MouseY;for(i=0;i<16;i++)/*原位置异或消去*/for(j=0;j<16;j++){if(mouse_draw[i][j]==3||mouse_draw[i][j]==4)continue;color=getpixel(x+j,y+i);putpixel(x+j,y+i,color^color);putpixel(x+j,y+i,pixel_save[i][j]);}}void MouseSetXY(int x,int y)/*设置当前位置*/{_CX=x;_DX=y;_AX=0x04;geninterrupt(0x33);}int LeftPress(void)/*鼠标左键按下*/{_AX=0x03;geninterrupt(0x33);return(_BX&1);}int RightPress(void)/*鼠标右键按下*/{_AX=0x03;geninterrupt(0x33);return(_BX&2);}/*是否按下中键返回值同上 */int MiddlePress(){_AX=0x03;geninterrupt(0x33);return(_BX&4);}void MouseGetXY(void)/*得到当前位置*/{_AX=0x03;geninterrupt(0x33);MouseX=_CX;MouseY=_DX;}/*鼠标按键情况,返回0表示只移动,返回1表示左右键同时按下,2表示只按了左键,3表示只按了右键*/int MouseStatus(){int x,y;int status;int press=0;int i,j,color;status=0;/*默认鼠标没有移动*/x=MouseX;y=MouseY;while(x==MouseX&&y==MouseY&&status==0&&press==0){if(LeftPress()&&RightPress())press=1;else if(LeftPress())press=2;else if(RightPress())press=3;MouseGetXY();if(MouseX!=x||MouseY!=y)status=1;}if(status)/*移动情况才重新显示鼠标*/{for(i=0;i<16;i++)/*原位置异或消去*/for(j=0;j<16;j++){if(mouse_draw[i][j]==3||mouse_draw[i][j]==4)continue;color=getpixel(x+j,y+i);putpixel(x+j,y+i,color^color);putpixel(x+j,y+i,pixel_save[i][j]);}MouseOn(MouseX,MouseY);/*新位置显示*/}if(press!=0)/*有按键的情况*/return press;return 0;/*只移动的情况*/}void Control(void)/*游戏开始,重新,关闭*/{int gameFLAG=1;/*游戏失败后判断是否重新开始的标志*/while(1){MouseStatus();if(gameFLAG)/*游戏失败后没判断出重新开始或者退出游戏的话就继续判断*/ {GameBegain(); /*游戏初始画面*/GamePlay();/*具体游戏*/if(gameAGAIN==1)/*游戏中重新开始*/{gameAGAIN=0;continue;}}gameFLAG=0;if(LeftPress())/*判断是否重新开始*/{if(MouseX>280&&MouseX<300&&MouseY>65&&MouseY<85){gameFLAG=1;continue;}}if(kbhit())/*判断是否按键退出*/break;}}void DrawSmile(void)/*画笑脸*/{MouseOff();setfillstyle(SOLID_FILL,YELLOW);fillellipse(290,75,10,10);setcolor(YELLOW);setfillstyle(SOLID_FILL,BLACK);/*眼睛*/fillellipse(285,75,2,2);fillellipse(295,75,2,2);setcolor(BLACK);/*嘴巴*/bar(287,80,293,81);MouseGetXY();MouseOn(MouseX,MouseY);}void DrawRedflag(int i,int j)/*显示红旗*/{MouseOff();setcolor(7);setfillstyle(SOLID_FILL,RED);bar(198+j*20,95+i*20,198+j*20+5,95+i*20+5);setcolor(BLACK);line(198+j*20,95+i*20,198+j*20,95+i*20+10);MouseGetXY();MouseOn(MouseX,MouseY);}void DrawEmpty(int i,int j,int mode,int color)/*两种空格子的显示*/ {MouseOff();setcolor(color);setfillstyle(SOLID_FILL,color);if(mode==0)/*没有单击过的大格子*/bar(200+j*20-8,100+i*20-8,200+j*20+8,100+i*20+8);elseif(mode==1)/*单击过后显示空白的小格子*/bar(200+j*20-7,100+i*20-7,200+j*20+7,100+i*20+7);MouseGetXY();MouseOn(MouseX,MouseY);}void GameBegain(void)/*游戏开始画面*/{int i,j;cleardevice();if(gamePLAY!=1){MouseSetXY(290,70); /*鼠标一开始的位置,并作为它的初始坐标*/MouseX=290;MouseY=70;}gamePLAY=1;/*下次按重新开始的话鼠标不重新初始化*/mineNUM=0;setfillstyle(SOLID_FILL,7);bar(190,60,390,290);for(i=0;i<10;i++)/*画格子*/for(j=0;j<10;j++)DrawEmpty(i,j,0,8);setcolor(7);DrawSmile();/*画脸*/randomize();for(i=0;i<10;i++)/*100个格子随机赋值有没有地雷*/for(j=0;j<10;j++){Mine[i][j].num=random(8);/*如果随机数的结果是1表示这个格子有地雷*/ if(Mine[i][j].num==1)mineNUM++;/*现有雷数加1*/elseMine[i][j].num=2;Mine[i][j].flag=0;/*表示没红旗标志*/}sprintf(randmineNUM,"%d",mineNUM); /*显示这次总共有多少雷数*/setcolor(1);settextstyle(0,0,2);outtextxy(210,70,randmineNUM);mineNUM=100-mineNUM;/*变量取空白格数量*/}void GameOver(void)/*游戏结束画面*/{int i,j;setcolor(0);for(i=0;i<10;i++)for(j=0;j<10;j++)if(Mine[i][j].num==1)/*显示所有的地雷*/{DrawEmpty(i,j,0,RED);setfillstyle(SOLID_FILL,BLACK);MouseOff();fillellipse(200+j*20,100+i*20,7,7);MouseGetXY();MouseOn(MouseX,MouseY);}}void GameWin(void)/*显示胜利*/{setcolor(11);settextstyle(0,0,2);outtextxy(230,30,"YOU WIN!");}int MineStatistics(int i,int j)/*统计每个格子周围的雷数*/ {int nNUM=0;if(i==0&&j==0)/*左上角格子的统计*/{if(Mine[0][1].num==1)nNUM++;if(Mine[1][0].num==1)nNUM++;if(Mine[1][1].num==1)nNUM++;}elseif(i==0&&j==9)/*右上角格子的统计*/{if(Mine[0][8].num==1)nNUM++;if(Mine[1][9].num==1)nNUM++;if(Mine[1][8].num==1)nNUM++;}elseif(i==9&&j==0)/*左下角格子的统计*/{if(Mine[8][0].num==1)nNUM++;if(Mine[9][1].num==1)nNUM++;if(Mine[8][1].num==1)nNUM++;}elseif(i==9&&j==9)/*右下角格子的统计*/{if(Mine[9][8].num==1)nNUM++;if(Mine[8][9].num==1)nNUM++;if(Mine[8][8].num==1)nNUM++;}else if(j==0)/*左边第一列格子的统计*/ {if(Mine[i][j+1].num==1)nNUM++;if(Mine[i+1][j].num==1)nNUM++;if(Mine[i-1][j].num==1)nNUM++;if(Mine[i-1][j+1].num==1)nNUM++;if(Mine[i+1][j+1].num==1)nNUM++;}else if(j==9)/*右边第一列格子的统计*/ {if(Mine[i][j-1].num==1)nNUM++;if(Mine[i+1][j].num==1)nNUM++;if(Mine[i-1][j].num==1)nNUM++;if(Mine[i-1][j-1].num==1)nNUM++;if(Mine[i+1][j-1].num==1)nNUM++;}else if(i==0)/*第一行格子的统计*/{if(Mine[i+1][j].num==1)nNUM++;if(Mine[i][j-1].num==1)nNUM++;if(Mine[i][j+1].num==1)nNUM++;if(Mine[i+1][j-1].num==1)nNUM++;if(Mine[i+1][j+1].num==1)nNUM++;}else if(i==9)/*最后一行格子的统计*/{if(Mine[i-1][j].num==1)nNUM++;if(Mine[i][j-1].num==1)nNUM++;if(Mine[i][j+1].num==1)nNUM++;if(Mine[i-1][j-1].num==1)nNUM++;if(Mine[i-1][j+1].num==1)nNUM++;}else/*普通格子的统计*/{if(Mine[i-1][j].num==1)nNUM++;if(Mine[i-1][j+1].num==1)nNUM++;if(Mine[i][j+1].num==1)nNUM++;if(Mine[i+1][j+1].num==1)nNUM++;if(Mine[i+1][j].num==1)nNUM++;if(Mine[i+1][j-1].num==1)nNUM++;if(Mine[i][j-1].num==1)nNUM++;if(Mine[i-1][j-1].num==1)nNUM++;}return(nNUM);/*把格子周围一共有多少雷数的统计结果返回*/ }int ShowWhite(int i,int j)/*显示无雷区的空白部分*/{if(Mine[i][j].flag==1||Mine[i][j].num==0)/*如果有红旗或该格处理过就不对该格进行任何判断*/return;mineNUM--;/*显示过数字或者空格的格子就表示多处理了一个格子,当所有格子都处理过了表示胜利*/if(Mine[i][j].roundnum==0&&Mine[i][j].num!=1)/*显示空格*/{DrawEmpty(i,j,1,7);Mine[i][j].num=0;}elseif(Mine[i][j].roundnum!=0)/*输出雷数*/{DrawEmpty(i,j,0,8);sprintf(randmineNUM,"%d",Mine[i][j].roundnum);setcolor(RED);MouseOff();outtextxy(195+j*20,95+i*20,randmineNUM);MouseGetXY();MouseOn(MouseX,MouseY);Mine[i][j].num=0;/*已经输出雷数的格子用0表示已经用过这个格子*/return ;}/*8个方向递归显示所有的空白格子*/if(i!=0&&Mine[i-1][j].num!=1)ShowWhite(i-1,j);if(i!=0&&j!=9&&Mine[i-1][j+1].num!=1)ShowWhite(i-1,j+1);if(j!=9&&Mine[i][j+1].num!=1)ShowWhite(i,j+1);if(j!=9&&i!=9&&Mine[i+1][j+1].num!=1)ShowWhite(i+1,j+1);if(i!=9&&Mine[i+1][j].num!=1)ShowWhite(i+1,j);if(i!=9&&j!=0&&Mine[i+1][j-1].num!=1)ShowWhite(i+1,j-1);if(j!=0&&Mine[i][j-1].num!=1)ShowWhite(i,j-1);if(i!=0&&j!=0&&Mine[i-1][j-1].num!=1)ShowWhite(i-1,j-1);}void GamePlay(void)/*游戏过程*/{int i,j,Num;/*Num用来接收统计函数返回一个格子周围有多少地雷*/for(i=0;i<10;i++)for(j=0;j<10;j++)Mine[i][j].roundnum=MineStatistics(i,j);/*统计每个格子周围有多少地雷*/while(!kbhit()){ MouseStatus();if(LeftPress())/*鼠标左键盘按下*/{if(MouseX>280&&MouseX<300&&MouseY>65&&MouseY<85)/*重新来*/{gameAGAIN=1;break;}if(MouseX>190&&MouseX<390&&MouseY>90&&MouseY<290)/*当前鼠标位置在格子范围内*/{j=(MouseX-190)/20;/*x坐标*/i=(MouseY-90)/20;/*y坐标*/if(Mine[i][j].flag==1)/*如果格子有红旗则左键无效*/continue;if(Mine[i][j].num!=0)/*如果格子没有处理过*/{if(Mine[i][j].num==1)/*鼠标按下的格子是地雷*/{GameOver();/*游戏失败*/break;}else/*鼠标按下的格子不是地雷*/{Num=MineStatistics(i,j);if(Num==0)/*周围没地雷就用递归算法来显示空白格子*/ShowWhite(i,j);else/*按下格子周围有地雷*/{MouseOff();sprintf(randmineNUM,"%d",Num);/*输出当前格子周围的雷数*/setcolor(RED);outtextxy(195+j*20,95+i*20,randmineNUM);mineNUM--;MouseGetXY();MouseOn(MouseX,MouseY);}Mine[i][j].num=0;/*点过的格子周围雷数的数字变为0表示这个格子已经用过*/if(mineNUM<1)/*胜利了*/{GameWin();break;}}}}}if(RightPress())/*鼠标右键键盘按下*/{if(MouseX>190&&MouseX<390&&MouseY>90&&MouseY<290)/*当前鼠标位置在格子范围内*/{j=(MouseX-190)/20;/*x坐标*/i=(MouseY-90)/20;/*y坐标*/if(Mine[i][j].flag==0&&Mine[i][j].num!=0)/*本来没红旗现在显示红旗*/{DrawRedflag(i,j);Mine[i][j].flag=1;}elseif(Mine[i][j].flag==1)/*有红旗标志再按右键就红旗消失*/{DrawEmpty(i,j,0,8);Mine[i][j].flag=0;}}delay(1000000);delay(1000000);delay(1000000);delay(1000000);delay(1000000);}} }。