简版扫雷代码

合集下载

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

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

C语⾔实现简单扫雷⼩游戏本⽂实例为⼤家分享了C语⾔实现扫雷⼩游戏的具体代码,供⼤家参考,具体内容如下#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <windows.h>#include <time.h>/*⽤ C 语⾔写⼀个简单的扫雷游戏*/// 1.写⼀个游戏菜单 Menu()// 2.开始游戏// 1.初始化⼆维数组 Init_Interface()// 2.打印游戏界⾯ Print_Interface()// 3.玩家掀起指定位置 Play() --> 指定输⼊坐标(判断合法性)// 1.判断该位置是否是雷// 2.判断是否掀掉所有空地// 3.如果掀开的是空地,则判断该空地周围是否有雷// 1.如果周围有雷,则统计周围雷的个数// 2.如果周围没有雷,则掀开周围除了雷的所有空地,并且统计所掀开空地周围雷的个数// 4.更新地图// 5.继续 3 的循环//定义全局变量://定义扫雷地图的长和宽#define MAX_ROW 9#define MAX_COL 9//定义默认的雷数#define DEFAULT_MINE 9//定义两个⼆维数组,分别存放初始地图和雷阵char show_map[MAX_ROW + 2][MAX_COL + 2];char mine_map[MAX_ROW + 2][MAX_COL + 2];//写⼀个游戏菜单int Menu() {printf("=========\n");printf("1.开始游戏\n");printf("0.结束游戏\n");printf("=========\n");printf("请选择游戏菜单选项:");int choice = 0;while (1) {scanf("%d", &choice);if (choice != 0 && choice != 1) {printf("您的输⼊有误, 请重新输⼊\n");continue;}break;}return choice;}//开始游戏//初始化数组void Init_Interface() {for (int row = 0; row < MAX_ROW + 2; row++) {for (int col = 0; col < MAX_COL + 2; col++) {show_map[row][col] = '*';}}for (int row = 0; row < MAX_ROW + 2; row++) {for (int col = 0; col < MAX_COL + 2; col++) {mine_map[row][col] = '0';}}int mine_count = DEFAULT_MINE;while (mine_count > 0) {int row = rand() % MAX_ROW + 1;int col = rand() % MAX_COL + 1;if (mine_map[row][col] == '1') { //将雷设置为 1//此处已经有雷continue;}mine_count--;mine_map[row][col] = '1';}}//打印初始界⾯void Print_Interface(char map[MAX_ROW + 2][MAX_COL + 2]) {printf(" ");for (int col = 1; col <= MAX_COL; col++) {printf("%d ", col);}printf("\n ");for (int col = 1; col <= MAX_COL; col++) {printf("--");}printf("\n");for (int row = 1; row <= MAX_ROW ; row++) {printf("%02d |", row);for (int col = 1; col <= MAX_COL; col++) {printf("%c ", map[row][col]);}printf("\n");}}//写⼀个统计周围雷数个数的函数int Around_Mine_count(int row, int col) {return (mine_map[row - 1][col - 1] - '0'+ mine_map[row - 1][col] - '0'+ mine_map[row - 1][col + 1] - '0'+ mine_map[row][col - 1] - '0'+ mine_map[row][col + 1] - '0'+ mine_map[row + 1][col - 1] - '0'+ mine_map[row + 1][col] - '0'+ mine_map[row + 1][col + 1] - '0');}//写⼀个判断该位置周围是否有雷的函数int No_Mine(int row, int col) {if (Around_Mine_count(row, col) == 0) {return 1;}return 0;}//写⼀个掀开该位置周围空地的函数void Open_Blank(int row, int col) {show_map[row - 1][col - 1] = '0' + Around_Mine_count(row - 1, col - 1); show_map[row - 1][col] = '0' + Around_Mine_count(row - 1, col);show_map[row - 1][col + 1] = '0' + Around_Mine_count(row - 1, col + 1); show_map[row][col - 1] = '0' + Around_Mine_count(row, col - 1);show_map[row][col + 1] = '0' + Around_Mine_count(row, col + 1);show_map[row + 1][col - 1] = '0' + Around_Mine_count(row + 1, col - 1); show_map[row + 1][col] = '0' + Around_Mine_count(row + 1, col);show_map[row + 1][col + 1] = '0' + Around_Mine_count(row + 1, col + 1); }//写⼀个判断游戏结束的函数int Success_Sweep(char show_map[MAX_ROW + 2][MAX_COL + 2]) { int count = 0;for (int row = 1; row <= MAX_ROW; row++) {for (int col = 1; col <= MAX_COL; col++) {if (show_map[row][col] == '*') {count++;}}}if (count == DEFAULT_MINE) {return 1;}return 0;}//开始游戏void StartGame() {while (1) {printf("请输⼊您要掀开的坐标:");int row = 0;int col = 0;while (1) {scanf("%d %d", &row, &col);if (row < 1 || row > MAX_ROW || col < 1 || col > MAX_COL) {printf("您的输⼊有误,请重新输⼊!\n");continue;}if (show_map[row][col] != '*') {printf("该位置已被掀开,请重新选择\n");continue;}break;}//判断该地⽅是否有雷if (mine_map[row][col] == '1') {Print_Interface(mine_map);printf("该地⽅有雷,游戏结束\n");break;}if (No_Mine(row, col)) {show_map[row][col] = '0';Open_Blank(row, col);}show_map[row][col] = '0' + Around_Mine_count(row, col);//判断是否掀开所有空地if (Success_Sweep(show_map) == 1) {Print_Interface(mine_map);printf("您已成功扫雷\n");break;}system("cls");//更新地图Print_Interface(show_map);}}int main() {if (Menu() == 0) {exit(0);}srand((unsigned int)time(NULL));Init_Interface();Print_Interface(show_map);StartGame();system("pause");return 0;}效果图:数字代表周围雷的个数以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

C语言编写的扫雷游戏源代码

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语言扫雷程序大作业代码

原创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语言扫雷程序代码

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

python扫雷简易代码

python扫雷简易代码

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

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

扫雷游戏代码

扫雷游戏代码

扫雷游戏代码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语言扫雷源代码

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

用python写扫雷游戏实例代码分享

用python写扫雷游戏实例代码分享

⽤python写扫雷游戏实例代码分享扫雷是⼀个⾮常经典的WIN游戏,我们教给⼤家⽤python语⾔来写出这个游戏,以下是全部实例代码:#!/usr/bin/python#coding:utf-8#python 写的扫雷游戏import sysimport randomclass MineSweeping():#扫雷主程序def __init__(self,row = 8 ,line= 8,mineNum = 15):self.row = rowself.line = lineself.score = 0 #分数self.mineNum = mineNumself.xy_list = [[0 for i in range(self.line)] for i in range(self.row)]def initData(self):# 初始化状态值# 游戏开始的时候状态值为清零(再重新设置状态值)self.xy_list = [[0 for i in range(self.line)] for i in range(self.row)]# 设置雷的数量maxMine = self.mineNumwhile maxMine > 0 :num_x = random.randint(0,self.row-1)num_y = random.randint(0,self.line-1)if self.xy_list[num_x][num_y] == 0:self.xy_list[num_x][num_y] = 1maxMine -= 1#获取x坐标def get_pos(self,str_pos):#获取x坐标while 1:try:num_x = raw_input(str_pos)if int(num_x) in range(self.line) and num_x :breakelse:print u'输⼊⽆效值'except:passreturn int(num_x)#进⾏扫雷def mine_clear(self,x,y):# 设置显⽰进⾏扫过的数⽬# 设置数字# 0 表⽰扫过的雷# 1 表⽰类# 2 表⽰扫过的类#获取坐标的数字pos = self.xy_list[x][y]if pos == 0 :self.xy_list[x][y] = 2return 0elif pos == 2 :return 2else:return 1#界⾯的显⽰def mineFace(self,state):#显⽰界⾯的内容#设置游戏的状态#1 表⽰运⾏的状态#2 表⽰输出的状态#3 表⽰游戏结束的状态#4 表⽰游戏获得了完胜if state == 1:print '+=================+'print ' Game start 'print '+=================+'tt = ' #'print '**************************'for i in range(self.line):str_t = ''for t in xrange(self.row):str_t += ttprint "|%s|"%(str_t,)print '**************************'print 'Please input values of x,y(0-7):' #刷新⽤户界⾯if state == 2:tt = ' #'print '**************************'for i in range(self.line):str_t = ''for t in xrange(self.row):if self.xy_list[i][t] == 2:str_t += str(self.xy_list[i][t]).rjust(2) else:str_t += ttprint "|%s|"%(str_t,)print '**************************'if state == 3:print '**************************'for i in range(self.line):str_t = ''for t in xrange(self.row):if int(self.xy_list[i][t]) != 1:str_t += ' 2'else:str_t += ' *'print "|%s|"%(str_t,)print '**************************'if state == 4:tt = ' #'print '**************************'for i in range(self.line):str_t = ''for t in xrange(self.row):if self.xy_list[i][t] == 2:str_t += str(self.xy_list[i][t]).rjust(2) else:str_t += ' @'print "|%s|"%(str_t,)print '**************************'def MainLoop(self):#创建游戏主循环#创建界⾯的运⾏self.mineFace(1)self.score = 0self.initData()#print self.xy_list# 进⼊主循环while 1:#获取坐标的位置x = self.get_pos(' X = ')y = self.get_pos(' Y = ')num = self.mine_clear(x,y)#判断是不过的了完胜win = Truefor i in self.xy_list:if 0 in i:win = Falsebreakif win:num = 4#执⾏刷新界⾯的函数if num == 0:self.mineFace(2)self.score += 10elif num == 2:print u'这个位置已经被排过了,证实没有雷'elif num == 1:print '+=================+'print ' Game over 'print '+=================+'print u'分数 : ', self.scoreself.mineFace(3)# 是不是进⾏下⼀句next = raw_input(u'是够进⾏下⼀局:Y or N ')if next.upper().startswith('Y'):print u'下⼀局开始'self.nextGame()else:print '>>> Game exit'breakelse:self.score += 10print u'恭喜您获得的完全的胜利'print u'分数 : ', self.scoreself.mineFace(4)next = raw_input(u'是够进⾏下⼀局:Y or N ')if next.upper().startswith('Y'):print u'下⼀局开始'self.nextGame()else:print '>>> Game exit'break# 下⼀局初始化信息def nextGame(self):self.mineFace(1)self.score = 0self.initData()if __name__ == '__main__':mi = MineSweeping(10,10,20)mi.MainLoop()sys.exit()如果⼤家在测试的时候还有任何疑问,可以在下⽅的留⾔区讨论,感谢⼤家对的⽀持。

简易vb扫雷代码

简易vb扫雷代码

简易vb扫雷代码Dim X As Integer, total%Private Sub Command1_Click()RandomizeDim k As Integer, m As Integerw = Form1.Widthh = Form1.Height * 0.9X = Val(InputBox("请输入行列数"))For i = 1 To XFor j = 1 To Xk = (i - 1) * X + jLoad Label1(k)Label1(k).Caption = ""Label1(k).Visible = TrueLabel1(k).Width = w \ XLabel1(k).Height = h \ XLabel1(k).Top = h / X * (i - 1)Label1(k).Left = w / X * (j - 1)If (i + j) Mod 2 = 0 ThenLabel1(k).BackColor = QBColor(12)ElseLabel1(k).BackColor = QBColor(15)End IfLabel1(k).FontSize = 260 \ XLabel1(k).Tag = IIf(Int(Rnd * 20 + 1) Mod 19 = 1, "○", " ") If Label1(k).Tag = "○" Then total = total + 1Label1(k).Alignment = 2Next jNext iLabel1(0).BackColor = QBColor(0)For i = 1 To XFor j = 1 To XIf j + 1 <= X And i > 1 ThenIf Label1((i - 2) * X + j + 1).Tag = "○" Then m = m + 1 End If If j + 1 <= X And i + 1 < X ThenIf Label1(i * X + j + 1).Tag = "○" Then m = m + 1End IfIf i + 1 <= X And j > 1 ThenIf Label1(i * X + j - 1).Tag = "○" Then m = m + 1End IfIf i > 1 And j > 1 ThenIf Label1((i - 2) * X + j - 1).Tag = "○" Then m = m + 1End IfIf j + 1 <= X ThenIf Label1((i - 1) * X + j + 1).Tag = "○" Then m = m + 1End IfIf i + 1 <= X ThenIf Label1(i * X + j).T ag = "○" Then m = m + 1End IfIf j > 1 ThenIf Label1((i - 1) * X + j - 1).Tag = "○" Then m = m + 1End IfIf i > 1 ThenIf Label1((i - 2) * X + j).Tag = "○" Then m = m + 1End IfLabel1((i - 1) * X + j).ToolTipText = mm = 0NextNextEnd SubPrivate Sub Form_Load()Label1(0).Visible = FalseMe.Width = 8000Me.Height = Me.WidthEnd SubPrivate Sub Label1_Mousedown(Index As Integer, Button As Integer, Shift As Integer, p As Single, q As Single)Static gross%If Button = 2 Then La bel1(Index).Caption = "※"If Button = 1 ThenIf Label1(Index).Tag = "○" ThenMsgBox "你挖到雷了"gross = 0For i = 1 To X * XLabel1(i).Caption = Label1(i).TagNext iFor i = 1 To X * X '延时Label1(i).BackColor = vbWhiteNextFor i = 1 To 1000000DoEventsNextFor i = 1 To X * XUnload Label1(i)NextElseLabel1(Index).BackColor = vbGreenLabel1(Index).Caption = Label1(Index).ToolTipTextIf Label1(Index).ToolTipText = "0" ThenIf Index Mod X = 0 Then i = Index / X Else i = Int(Index / X) + 1If Index Mod X = 0 Then j = X Else j = Index Mod XIf j + 1 <= X And i > 1 ThenLabel1((i - 2) * X + j + 1).Caption = Label1((i - 2) * X + j + 1).ToolTipText End IfIf j + 1 <= X And i + 1 < X ThenLabel1(i * X + j + 1).Caption = Label1(i * X + j + 1).ToolTipText End IfIf i + 1 <= X And j > 1 ThenLabel1(i * X + j - 1).Caption = Label1(i * X + j - 1).ToolTipText End IfIf i > 1 And j > 1 ThenLabel1((i - 2) * X + j - 1).Caption = Label1((i - 2) * X + j - 1).ToolTipText End IfIf j + 1 <= X ThenLabel1((i - 1) * X + j + 1).Caption = Label1((i - 1) * X + j + 1).ToolTipText End IfIf i + 1 <= X ThenLabel1(i * X + j).Caption = Label1(i * X + j).ToolTipT extEnd IfIf j > 1 ThenLabel1((i - 1) * X + j - 1).Caption = Label1((i - 1) * X + j - 1).ToolTipText End IfIf i > 1 ThenLabel1((i - 2) * X + j).Caption = Label1((i - 2) * X + j).ToolTipText End IfEnd IfEnd IfEnd Ifgross = 0If Label1.Count > 1 ThenFor i = 1 To X * XIf Label1(i).Caption = "※" Then gross = gross + 1Next iEnd Ifs = 0If Label1.Count > 1 ThenFor i = 1 To X * XIf Label1(i).BackColor = vbGreen Then s = s + 1Next iEnd IfDebug.Print "s的值是"; sDebug.Print "gross"; grossDebug.Print "total"; totalIf s + gross = X * X Then '确保探测完所有方块msg = MsgBox("恭喜你清完了所有雷,是否重新开始?", vbYesNo) If msg = vbYes ThenFor i = 1 To X * XUnload Label1(i)NextEnd Ifgross = 0End IfEnd Sub。

C语言实现简易扫雷

C语言实现简易扫雷

C语⾔实现简易扫雷⾸先,写代码之前要将整体思路写出来:扫雷游戏:1.需要两个⼆维数组,⼀个⽤来展⽰,⼀个⽤来放雷;2.整体⾻架在代码中都有注释说明;3.游戏难度⽐较简单,适合初学者观看,如果有⼤佬看明⽩,可以指点⼀⼆.//使⽤⼆维数组来表⽰地图,此处需要2个⼆维数组,第⼀个⼆维数组表⽰地雷的雷阵,第⼆个⼆维数组表⽰⽤户看到的地图//扫雷地图⼤⼩9*9;但是⼆维数组11*11#define _CRT_SECURE_NO_WARNINGS#include<stdio.h>#include<stdlib.h>#define MINE_COUNT 10#define ROW 9#define COL 9char show_map[ROW + 2][COL + 2];char mine_map[ROW + 2][COL + 2];int Menu(){int choice = -1;printf("************************\n");printf("* 欢迎来到扫雷游戏 *\n");printf("* 请您选择 *\n");printf("* 1.开始游戏 *\n");printf("* 2.离开游戏 *\n");printf("************************\n");while (1){scanf("%d", &choice);if (choice == 1){return 1;break;}else if (choice == 2){exit(2);}else{printf("输⼊⾮法,请重新输⼊!\n");continue;}}}void Init(){ //初始化布雷srand(time(0));memset(mine_map, '0', (ROW + 2)*(COL + 2));memset(show_map, '*', (ROW + 2)*(COL + 2));int count = MINE_COUNT;int row = -1;int col = -1;while (count>=0){row = rand() % ROW + 1;col = rand() % COL + 1;if (show_map[row][col] == '*'){mine_map[row][col] = '1';count--;continue;}}}void Print(){ // 1 2 3 4 5 6 7 8 9printf(" "); // -----------------for (int col = 1; col <= COL; col++) // 01 | | | | | | | | |{ // -----------------printf(" %d ", col);}printf("\n ---------------------------\n");for (int row = 1; row <= ROW; row++){printf("%02d ", row);printf(" |%c |%c |%c |%c |%c |%c |%c |%c |%c |\n", show_map[row][1], show_map[row][2], show_map[row][3], show_map[row][4], show_map[row][5], show_map[row][6], show_map[row][7], show_map[row][8], show_map[row][9]);printf(" ---------------------------\n");}}char MineBoom(){printf(" ");for (int col = 1; col <= COL; col++){printf(" %d ", col);}printf("\n ---------------------------\n");for (int row = 1; row <= ROW; row++)printf("%02d ", row);printf(" |%c |%c |%c |%c |%c |%c |%c |%c |%c |\n", mine_map[row][1], mine_map[row][2], mine_map[row][3], mine_map[row][4], mine_map[row][5], mine_map[row][6], mine_map[row][7], mine_map[row][8], mine_map[row][9]);printf(" ---------------------------\n");}}char IsFull(){int ful = COL*ROW - MINE_COUNT;for (int row = 1; row <= ROW; row++){for (int col = 1; col <= COL; col++){{if (show_map[row][col] == '1' || show_map[row][col] == '0'){ful--;}}}}if (ful == 0){return 'p';}}char PlayerMove(char mine_map[ROW + 2][COL + 2], char show_map[ROW + 2][COL + 2]){int row = -1;int col = -1;while (1){printf("请玩家选的位置(输⼊格式:坐标坐标):");scanf("%d %d", &row, &col);if (row < 1 || row>ROW || col>COL || col < 1){printf("输⼊越界,请重新输⼊!\n");continue;}if (row > 0 && row<10 && col>0 && col < 10){if (show_map[row][col] == '*'){//1.有雷显⽰雷区,结束游戏if (mine_map[row][col] == '1'){MineBoom();return 'n';break;}//3.显⽰此位的周围⼀圈是否有雷else if (mine_map[row][col] == '0'){int count = '0';if (mine_map[row - 1][col - 1] == '1'){count++;}if (mine_map[row - 1][col ] == '1'){count++;}if (mine_map[row - 1][col + 1] == '1'){count++;}if (mine_map[row ][col - 1] == '1'){count++;}if (mine_map[row][col + 1] == '1'){count++;}if (mine_map[row + 1][col - 1] == '1'){count++;}if (mine_map[row + 1][col ] == '1'){count++;}if (mine_map[row + 1][col + 1] == '1'){count++;}{show_map[row][col] = count;Print();return 'k';}else{printf("已经选过,请重新输⼊!\n");continue;}}else{printf("输⼊⾮法,请重新输⼊!\n");continue;}}}}void Game(){if (Menu() == 1)//1.选择菜单{Init();//2.初始化,布雷Print(); //3.打印棋盘while (1){if (PlayerMove(mine_map,show_map) == 'n'){ printf("踩到雷啦,游戏结束!\n");break;}else if (IsFull() == 'p'){printf("恭喜玩家胜利!\n");break;}else {continue;}}}system("pause");}int main(){Game();return 0;}。

扫雷源代码(精)

扫雷源代码(精)

#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语言扫雷游戏代码及详细注释扫雷游戏代码及详细注释扫雷游戏做为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语言编写扫雷代码示例编写扫雷游戏的代码涉及到图形界面、事件处理等,因此需要使用相应的库来简化这些操作。

下面是一个使用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语言扫雷程序代码以下是一份基于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语言扫雷代码以下是一份简单的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语言扫雷程序代码很高兴能够回答这个问题,关于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语言扫雷程序的实现,希望对你有所帮助。

扫雷游戏Java源代码

扫雷游戏Java源代码

扫雷游戏Java源代码import java.awt.BorderLayout;import java.awt.Container;import java.awt.Font;import java.awt.GridLayout;import java.awt.Insets;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JPanel;import javax.swing.Timer;public class ScanLei1 extends JFrame implements ActionListener{ private static final long serialVersionUID = 1L;private Container contentPane;private JButton btn;private JButton[] btns;private JLabel b1;private JLabel b2;private JLabel b3;private Timer timer;private int row=9;private int col=9;private int bon=10;private int[][] a;private int b;private int[] a1;private JPanel p,p1,p2,p3;public ScanLei1(String title){super(title);contentPane=getContentPane();setSize(297,377);this.setBounds(400, 100, 400, 500);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);timer =new Timer(1000,(ActionListener) this);a = new int[row+2][col+2];initGUI();}public void initGUI(){p3=new JPanel();b=bon;JMenuBar menuBar=new JMenuBar();JMenu menu1=new JMenu("游戏");JMenu menu2=new JMenu("帮助");JMenuItem mi1=new JMenuItem("初级");JMenuItem mi2 = new JMenuItem("中级");JMenuItem mi3 =new JMenuItem("高级");mi1.addActionListener(this);menu1.add(mi1);mi2.addActionListener(this);menu1.add(mi2);mi3.addActionListener(this);menu1.add(mi3);menuBar.add(menu1);menuBar.add(menu2);p3.add(menuBar);b1=new JLabel(bon+"");a1=new int[bon];btn =new JButton("开始");btn.addActionListener(this);b2=new JLabel("0");b3=new JLabel("");btns=new JButton[row*col];p=new JPanel();p.setLayout(new BorderLayout());contentPane.add(p);p.add(p3,BorderLayout.NORTH);//combo=new JComboBox(new Object[]{"初级","中级","高级"} );//加监听/*combo.addItemListener(new ItemListener(){}});*/p1=new JPanel();//在那个位置//(( FlowLayout)p1.getLayout()).setAlignment( FlowLayout.RIGHT);p1.add(b1);p1.add(btn);p1.add(b2);p1.add(b3);p.add(p3,BorderLayout.NORTH);p.add(p1,BorderLayout.CENTER);p2=new JPanel();p2.setLayout(new GridLayout(row,col,0,0));for(int i=0;i<row*col;i++){btns[i]=new JButton("");btns[i].setMargin(new Insets(0,0,0,0));btns[i].setFont(new Font(null,Font.BOLD,25));btns[i].addActionListener(this);btns[i].addMouseListener(new NormoreMouseEvent());p2.add(btns[i]);}contentPane.add(p,BorderLayout.NORTH);contentPane.add(p2,BorderLayout.CENTER);}public void go(){setVisible(true);}public static void main(String[] args){new ScanLei1("扫雷").go();}public void out(int[][] a,JButton[] btns,ActionEvent e,int i,int x,int y){ int p=1;if(a[x][y]==0){a[x][y]=10;btns[i].setEnabled(false); //33for(int l=y-1;l<=y+1;l++){int m=x-1-1;int n=l-1;p=1;System.out.println(a[1][2]);if(n>-1&&n<col&&m>-1&&m<row){for(int q=0;q<row&&p==1;q++){//col-->row;if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){if(a[x-1][l]!=0&&a[x-1][l]!=10){btns[n+col*q].setText(a[x-1][l]+"");a[x-1][l]=10;btns[n+col*q].setEnabled(false);}else if(a[x-1][l]==0){//a[x-1][l]=10;btns[n+col*q].setEnabled(false);out(a,btns,e,n+col*q,x-1,l); ////55////a[x-1][l]=10;btns[n+col*q].setEnabled(false);}p=0;}}}p=1;m=x;if(n>-1&&n<col&&m>-1&&m<col){for(int q=0;q<row&&p==1;q++){if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){if(a[x+1][l]!=0&&a[x+1][l]!=10){btns[n+col*q].setText(a[x+1][l]+"");a[x+1][l]=10;btns[n+col*q].setEnabled(false);}else if(a[x+1][l]==0){out(a,btns,e,n+col*q,x+1,l);///55////a[x+1][l]=10;btns[n+col*q].setEnabled(false);}p=0;}}}}int m=x-1;int n=y-1-1;p=1;if(n>-1&&n<col&&m>-1&&m<col){for(int q=0;q<row&&p==1;q++){if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){if(a[x][y-1]!=0&&a[x][y-1]!=10){btns[n+col*q].setText(a[x][y-1]+"");a[x][y-1]=10;btns[n+col*q].setEnabled(false);}else if(a[x][y-1]==0){out(a,btns,e,n+col*q,x,y-1);a[x][y-1]=10;btns[n+col*q].setEnabled(false);}p=0;}}}p=1;m=x-1;n=y+1-1;if(n>-1&&n<col&&m>-1&&m<col){for(int q=0;q<row&&p==1;q++){if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){if(a[x][y+1]!=0&&a[x][y+1]!=10){btns[n+col*q].setText(a[x][y+1]+"");a[x][y+1]=10;btns[n+col*q].setEnabled(false);}else if(a[x][y+1]==0){out(a,btns,e,n+col*q,x,y+1);a[x][y+1]=10;btns[n+col*q].setEnabled(false);}p=0;}}}}}public void actionPerformed(ActionEvent e) {if(e.getActionCommand()=="初级"){row=9;col=9;bon=10;a1=new int[bon];b=bon;//setSize(297,377);a = new int[row+2][col+2];this.remove(p2);timer.stop();b1.setText("10");b2.setText("0");b3.setText("");btns=new JButton[row*col];p2=new JPanel();p2.setLayout(new GridLayout(row,col,0,0));for(int i=0;i<row*col;i++){btns[i]=new JButton(" ");btns[i].setMargin(new Insets(0,0,0,0));btns[i].setFont(new Font(null,Font.BOLD,25));btns[i].addActionListener(this);btns[i].addMouseListener(new NormoreMouseEvent());p2.add(btns[i]);}contentPane.add(p2,BorderLayout.CENTER);//setSize(297,377);this.pack();for(int i=0;i<row*col;i++){btns[i].setText(" ");btns[i].setEnabled(true);}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){a[i][j]=0;}}}else if(e.getActionCommand()=="中级"){row=16;col=16;bon=40;//setSize(33*col,33*row+80);a1=new int[bon];a = new int[row+2][col+2];b=bon;this.remove(p2);timer.stop();b1.setText("40");b2.setText("0");b3.setText("");btns=new JButton[row*col];p2=new JPanel();p2.setLayout(new GridLayout(row,col,0,0));for(int i=0;i<row*col;i++){btns[i]=new JButton(" ");btns[i].setMargin(new Insets(0,0,0,0));btns[i].setFont(new Font(null,Font.BOLD,25));btns[i].addActionListener(this);btns[i].addMouseListener(new NormoreMouseEvent());p2.add(btns[i]);}contentPane.add(p2,BorderLayout.CENTER);this.pack();//setSize(33*col,33*row+80);for(int i=0;i<row*col;i++){btns[i].setText("");btns[i].setEnabled(true);}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){a[i][j]=0;}}}else if(e.getActionCommand()=="高级"){row=16;col=32;bon=99;setSize(33*col,33*row+80);a1=new int[bon];a = new int[row+2][col+2];b=bon;this.remove(p2);timer.stop();b1.setText("99");b2.setText("0");b3.setText("");btns=new JButton[row*col];p2=new JPanel();p2.setLayout(new GridLayout(row,col,0,0));for(int i=0;i<row*col;i++){btns[i]=new JButton(" ");btns[i].setMargin(new Insets(0,0,0,0));btns[i].setFont(new Font(null,Font.BOLD,25));btns[i].addActionListener(this);btns[i].addMouseListener(new NormoreMouseEvent());p2.add(btns[i]);}contentPane.add(p2,BorderLayout.CENTER);//setSize(33*col,33*row+80);this.pack();for(int i=0;i<row*col;i++){btns[i].setText("");btns[i].setEnabled(true);}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){a[i][j]=0;}}}if(e.getSource()==btn){timer.start();b=bon;b3.setText("");//System.out.println(bon);//清空for(int i=0;i<row*col;i++){btns[i].setText("");btns[i].setEnabled(true);}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){a[i][j]=0;}}//产生随机数for(int i=0;i<bon;i++){ int p=1;int m=(int)(Math.random()*row*col);while(p==1){int l=1;int j;for( j=0;j<i&&l==1;j++){if(a1[j]==m){m=(int)(Math.random()*row*col);l=0;}}if(j==i){a1[i]=m;p=0;}}}b1.setText(bon+"");b2.setText("0");//布雷for(int i=0;i<bon;i++){int x=(a1[i]/col+1);int y=(a1[i]%col+1);a[x][y]=100;}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){if(i==0||j==0||i==row+1||j==col+1){a[i][j]=0;}}}for(int i=1;i<=row;i++){for(int j=1;j<=col;j++){if(a[i][j]!=100){for(int l=j-1;l<=j+1;l++){if(a[i-1][l]==100){a[i][j]++;}if(a[i+1][l]==100){a[i][j]++;}}if(a[i][j-1]==100){a[i][j]++;}if(a[i][j+1]==100){a[i][j]++;}}}}}if(e.getSource()==timer){String time=b2.getText().trim();int t=Integer.parseInt(time);//System.out.println(t);if(t>=600){timer.stop();}else{t++;b2.setText(t+"");}}for(int i=0;i<col*row;i++){if(btns[i].getText()!="★"){int x=i/col+1;int y=i%col+1;if(e.getSource()==btns[i]&&a[x][y]==100){btns[i].setText("★");btns[i].setEnabled(false);a[x][y]=10;for(int k=0;k<col*row;k++){int m1=k/col+1;int n1=k%col+1;if(a[m1][n1]!=10&&btns[k].getText()=="★"){btns[k].setText("*o*");}}for(int j=0;j<col*row;j++){int m=j/col+1;int n=j%col+1;if(a[m][n]==100){btns[j].setText("★");btns[j].setEnabled(false);b3.setText("你输了!!");}btns[j].setEnabled(false);a[m][n]=10;}timer.stop();}else if(e.getSource()==btns[i]){if(a[x][y]==0){out(a,btns,e,i,x,y);a[x][y]=10;btns[i].setEnabled(false);}if(a[x][y]!=0&&a[x][y]!=10){btns[i].setText(a[x][y]+"");btns[i].setEnabled(false);a[x][y]=10;}}}else if(btns[i].getText()=="★"){}}}class NormoreMouseEvent extends MouseAdapter{public void mouseClicked(MouseEvent e) {System.out.println(b);for(int i=0;i<col*row;i++){int x1=i/col+1;int y1=i%col+1;if(e.getSource()==btns[i]&&btns[i].getText()!="★"&&a[x1][y1]!=10){if(e.getButton()==MouseEvent.BUTTON3){btns[i].setText("★");b--;if(b==0){int flag=0;for(int j=0;j<col*row;j++){int x=j/col+1;int y=j%col+1;if(a[x][y]==100&&btns[j].getText()=="★"){flag++;}}if(flag==bon){timer.stop();b3.setText("你赢了!");}}b1.setText(b+"");}}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);}}}}}}。

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语言扫雷游戏。

C++实现简易版扫雷游戏

C++实现简易版扫雷游戏

C++实现简易版扫雷游戏⽬录⼀、菜单栏⼆、创建棋盘数组三、初始化棋盘四、打印棋盘五、布置雷六、排查雷七、全部代码总结1 2 3 4 5 6 7 8 9 10 1112 13 14 15 16 17 18//测试⽂件#include"game.h"void menu(){printf("**************************\n"); printf("**** 1.play ********\n"); printf("**** 0.exit ********\n"); printf("**************************\n");19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80}//玩游戏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);//布置雷SetMineBoard(mine, ROW, COL);//排查雷FindBoard(mine, show, ROW, COL);}int main(){int input = 0;srand((unsigned int)time(NULL));do{menu();printf("请选择:");scanf("%d", &input);switch(input){case1:game();//玩游戏break;case0:printf("退出游戏\n");break;default:printf("选择错误,请重新选择\n");break;}} while(input);return0;}//声明⽂件#pragma once#include<stdio.h>#include<stdlib.h>#include<time.h>//⽤宏定义来定义棋盘⾏与列,便于修改其⼤⼩#define ROW 9#define COL 9#define ROWS ROW+2#define COLS COL+2//放置雷的个数#define EASY_COUNT 10//初始化棋盘void InitBoard(char board[ROWS][COLS], int rows, int cols, char set);//打印棋盘void DisplayBoard(char board[ROWS][COLS], int row, int col);//布置雷void SetMineBoard(char board[ROWS][COLS], int row, int col);//排查雷void FindBoard(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col); //定义⽂件#include"game.h"//初始化棋盘void InitBoard(char board[ROWS][COLS], int rows, int cols, char set){int i = 0;for(i = 0; i < rows; i++){81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 int j = 0;for(j = 0; j < cols; j++){board[i][j] = set;}}}//打印棋盘void DisplayBoard(char board[ROWS][COLS], int row, int col){int i = 0;printf("--------------------------------\n");//⾏提⽰for(i = 0; i <= row; i++){printf("%d ", i);}printf("\n");for(i = 1; i <= row; i++){int j = 0;//列提⽰printf("%d ",i);for(j = 1; j <= col; j++){printf("%c ", board[i][j]);}printf("\n");}printf("--------------------------------\n");}//布置雷void SetMineBoard(char board[ROWS][COLS], int row, int col){int x = 0;int y = 0;int count = 0;//已经布置雷的个数while(count < EASY_COUNT){x = rand() % row + 1;y = rand() % col + 1;if(board[x][y] == '0'){board[x][y] = '1';count++;}}}int GetMineBoard(char board[ROWS][COLS], int x, int y){return(board[x - 1][y - 1] + board[x - 1][y] + board[x - 1][y + 1]+ board[x][y - 1] + board[x][y + 1]+ board[x + 1][y - 1] + board[x + 1][y] + board[x + 1][y + 1] - 8 * '0');}//排查雷void FindBoard(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col) {int x = 0;int y = 0;int win = 0;//已经排查雷的个数while(win < row * col - EASY_COUNT){printf("请输⼊要排查的坐标:");scanf("%d %d", &x, &y);if(x >= 1 && x <= col && y >= 1 && y <= col){if(mine[x][y] == '1')143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172{printf("很遗憾,你被炸死了\n");DisplayBoard(mine, ROW, COL); break; }else{show[x][y] = GetMineBoard(mine, x, y) + '0'; DisplayBoard(show, ROW, COL); win++; }}else { printf("坐标⾮法,请重新输⼊\n"); }}if (win == row * col - EASY_COUNT){ printf("恭喜您,排雷成功!\n"); DisplayBoard(mine, ROW, COL); }}总结到此这篇关于C++实现简易版扫雷游戏的⽂章就介绍到这了,更多相关C++扫雷内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define MAX 100//最大范围为100x100
struct place{
int show;//显示状态(-1为不显示,0为显示@,1为显示status)
char status;//身份(数字为周围8位地雷数,*为地雷,#号为边界标志)
//设置地雷
//初始条件:已有雷区,地雷数目,长度,宽度
//操作结果:在已有雷区放置指定定数目地雷
srand((unsigned)time(NULL));
int i;
for(i=1;i<=number;i++){
int l,w;
l=rand()%length+1;
w=rand()%width+1;
if(mine_area[w][l].status=='*'){
else if(mine_area[i][j].status=='#')
printf("#");
else if(mine_area[i][j].status=='*')
printf("*");
printf(":%d ",mine_area[i][j].show);
}
printf("\n");
}
}
void print_all(place mine_area[][MAX+2],int length,int width){
do{
int x,y;
system("cls");
printf("游戏开始!");
print_out(mine_area,0);
get_open_seat(&x,&y);
if(!open(mine_area,x,y)){
end(mine_area);
break;
}
}while(1);
}
int main(){
mine_area[0][i].show=-1;mine_area[0][i].status='#';
}
for(i=1;i<=MAX+1;i++)
for(j=1;j<=MAX+1;j++){
mine_area[i][j].show=0;mine_area[i][j].status=0;
}
}
/*设置雷区*/
}
void set(place mine_area[MAX+2][MAX+2]){
int choose;
int length,width,mine_num;
printf("请选择游戏难度:1.简单;2.一般;3.困难;4.自定义\n");
scanf("%d",&choose);
switch(choose){
mine_area[i][j].show=1;
}
j=1;
}
return 0;
case 0:
for(i=x-1;i<=x+1;i++)
for(j=y-1;j<=y+1;j++)
if(mine_area[i][j].show==0)
open(mine_area,i,j);//依次将周围没打开的位置打开
return 1;
printf(" | ");
}
for(i=1,printf("\n\t");mine_area[i][j].status!='#';i++){
printf(" V ");
}
printf("\n");
for(i=1,j=1;i<=MAX+1&&mine_area[i][j].status!='#';i++){
printf("%5d->\t",i);
for(;j<=MAX+1&&mine_area[i][j].status!='#';j++){
if(mine_area[i][j].show!=style){
if(mine_area[i][j].status<=8)
printf(" %c ",mine_area[i][j].status+48);
};
/*显示函数*/
void print_all(place mine_area[][MAX+2]){
for(int i=0;i<=MAX+1;i++){
for(int j=0;j<=MAX+1;j++){
if(mine_area[i][j].status<=8)
printf("%d",mine_area[i][j].status+48);
printf("#");
else if(mine_area[i][j].status=='*')
printf("*");
printf(":%d ",mine_area[i][j].show);
}
printf("\n");
}
}
void print_out(place mine_area[][MAX+2],int style){
place mine_area[MAX+2][MAX+2];
init(mine_area);
//print_all(mine_area);
set(mine_area);
//print_out(mine_area,1);
operate(mine_area);
system("pause");
return 0;
i--;
continue;
}
mine_area[w][l].status='*';
}
}
void get_number(place mine_area[][MAX+2],int i,int j){
//无地雷位置获得其周围地雷数
//初始条件:已安放地雷的雷区,无地雷位置坐标i,j
//操作结果:将周围地雷数赋给该位置的status
case 1:
length=10;width=10;mine_num=10;
break;
case 2:
length=20;width=20;mine_num=50;
break;
case 3:
length=30;width=30;mine_num=120;
break;
case 4:
get_setnumber(&length,&width,&mine_num);
}
for(i=1;i<=length+1;i++){
mine_area[width+1][i].show=-1;mine_area[width+1][i].status='#';
}
}
void set_mine(place mine_area[][MAX+2],int number,int length,int width){
get_number(mine_area,i,j);
}
}
void get_setnumber(int *p_length,int *p_width,int *p_mine_num){
//获取设置信息
//初始条件:储存长、宽、地雷数的地址
//操作结果:将长、宽、地雷数赋值为用户输入的值
printf("请输入雷区大小:");
}
switch(mine_area[x][y].status)
{
case '*':
for(i=1,j=1;i<=MAX+1&&mine_area[i][j].status!='#';i++){
for(;j<=MAX+1&&mine_area[i][j].status!='#';j++){
if(mine_area[i][j].status=='*')
//获取打开位置
//初始条件:用于储存位置信息的x,y
//操作结果:为x,y赋值
printf("\n");
printf("请输入要打开位置地址(例如3,2):");
scanf("%d",x);getchar();
scanf("%d",y);
}
int open(place mine_area[][MAX+2],int x,int y){
}
void set_number(place mine_area[][MAX+2],int length,int width){
int i,j;
for(i=1;i<=width;i++)
相关文档
最新文档