- 扫雷
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#define ROW 9
#define COL 9
#define ROWS 11
#define COLS 11
#define COUNT 10
char Mine[ROWS][COLS];
char Show[ROWS][COLS];
需要两个棋盘,一个是雷图,一个展示给玩家
- 初始化棋盘
void InitBoard(char board[ROWS][COLS], char set)
{
int i = 0;
int 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 i = 0;
int j = 0;
printf("0 ");
for (i = 1; i <= ROW; i++)
{
printf("%d ", i);//打印横标(0--10)
}
printf("\n");
for (i = 1; i <= ROW; i++)//打印竖标(1--10)
{
printf("%d ", i);
for (j = 1; j <= COL; j++)
{
printf("%c ", board[i][j]);//玩家棋盘数组
}
printf("\n");
}
printf("\n");
}
- 设置地雷
void SetMine(char board[ROWS][COLS])
{
int count = COUNT;
while (count)
{
int x = rand() % ROW + 1;
int y = rand() % COL + 1;
if (board[x][y] == '0')
{
board[x][y] = '1';
count--;
}
}
}
- 计算周围的雷数
int GetMineCount(char Mine[ROWS][COLS], int x, int y)
{
return Mine[x - 1][y - 1]
1. Mine[x - 1][y]
2. Mine[x - 1][y + 1]
3. Mine[x][y - 1]
4. Mine[x][y + 1]
5. Mine[x + 1][y - 1]
6. Mine[x + 1][y]
7. Mine[x + 1][y + 1]
8. 8 * '0';
}
- 翻格子
void extend_board(char Mine[ROWS][COLS], char Show[ROWS][COLS], int x, int y)
{
Show[x][y] = GetMineCount(Mine, x, y) + '0';
if (GetMineCount(Mine, x, y) == 0)
{
Show[x - 1][y - 1] = GetMineCount(Mine, x - 1, y - 1) + '0';
Show[x - 1][y] = GetMineCount(Mine, x - 1, y) + '0';
Show[x - 1][y + 1] = GetMineCount(Mine, x - 1, y + 1) + '0';
Show[x][y - 1] = GetMineCount(Mine, x, y - 1) + '0';
Show[x][y + 1] = GetMineCount(Mine, x, y + 1) + '0';
Show[x + 1][y - 1] = GetMineCount(Mine, x + 1, y - 1) + '0';
Show[x + 1][y] = GetMineCount(Mine, x + 1, y) + '0';
Show[x + 1][y + 1] = GetMineCount(Mine, x + 1, y + 1) + '0';
}
}
- 计算剩余未翻开格数
int countnum()
{
int count = 0;
int i = 0;
int j = 0;
for (i = 1; i <= ROWS - 2; i++)
{
for (j = 1; j <= COLS - 2; j++)
{
if (Show[i][j] == '*')
{
count++;
}
}
}
return count;
}
- 输入坐标扫雷
void FindMine(char Mine[ROWS][COLS], char Show[ROWS][COLS])
{
int x = 0;
int y = 0;
while (1)
{
printf("请输入坐标\n");
scanf("%d%d", &x, &y);
if (x >= 1 && x <= ROW && y >= 1 && y <= COL)
{
if (Mine[x][y] == '1')
{
printf("很遗憾,你被炸死了\n");
DisplayBoard(Mine);
break;
}
else
{
extend_board(Mine, Show, x, y);
DisplayBoard(Show);
}
}
else
{
printf("坐标错误\n");
}
if (countnum() == COUNT)
{
printf("你赢了");
break;
}
}
}
- 菜单及流程
int main()
{
srand((unsigned int)time(NULL));
printf("------------------\n");
printf("---- 1.play ----\n");
printf("---- 0.exit ----\n");
printf("------------------\n");
if (getchar() == '1')
{
InitBoard(Mine, '0');
InitBoard(Show, '*');
SetMine(Mine);
DisplayBoard(Show);
FindMine(Mine, Show);
}
system("pause");
return 0;
}