扫雷,很经典的一个电脑游戏,踩雷就输,找到剩余所以雷就赢,今天我们来做一个c语言写的扫雷代码。
一、游戏的开始
由于上一次三子棋已经写过游戏主题代码,这里就不详细说明了
void caidan()
{
printf("----------------------\n");
printf("--------输1开始-------\n");
printf("--------输0退出-------\n");
printf("----------------------\n");
}
void game()
{
char mine[ROWS][COLS] = { 0 };
char show[ROWS][COLS] = { 0 };
Initboard(mine, ROWS, COLS, '0');
Initboard(show, ROWS, COLS, '*');
Setmine(mine, ROW, COL, COUNT);
Displayboard(show, ROW, COL);
Findmine(mine, show, ROWS, COLS);
}
void test()
{
srand((unsigned int)time(NULL));
int input = 0;
do
{
caidan();
printf("请输入-》:");
scanf("%d", &input);
switch(input)
{
case 1:
game();
break;
case 0:
printf("退出游戏\n");
break;
default:
printf("选择错误\n");
break;
}
} while (input);
}
int main()
{
test();
return 0;
}
二、game函数详解
1.initboard? ?\\初始化扫雷棋盘
2.displayboard? \\打印棋盘
3.setmine? ?\\埋雷
4.findmine? \\排雷(这里需要用到两个棋盘一个是“1”是雷的内部棋盘,一个是“*”是雷的展示棋盘
为了防止数组越界在mine棋盘多了一行一列)
void Initboard(char board[ROWS][COLS], int rows, int cols, char set)//chushihua
{
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)//dayin
{
int i = 0, j = 0;
for (i = 0; i <= col; i++)
{
printf("%d", i);
}
printf("\n");
for (j = 1; j <= row; j++)
{
printf("%d", j);
for (i = 1; i <= col; i++)
{
printf("%c", board[i][j]);
}
printf("\n");
}
}
void Setmine(char mine[ROWS][COLS], int row, int col, int count)//mailei
{
int x = rand() % 9 + 1;
int y = rand() % 9 + 1;
while (count)
{
if (mine[x][y] == '0')
{
mine[x][y] = '1';
count--;
}
}
}
int countnum(char mine[ROWS][COLS], int x, int y)
{
return mine[x - 1][y - 1] +
mine[x - 1][y] +
mine[x + 1][y] +
mine[x + 1][y - 1] +
mine[x + 1][y + 1] +
mine[x - 1][y + 1] +
mine[x][y + 1] +
mine[x][y - 1] - 8 * '0';
}
void Findmine(char mine[ROWS][COLS], char show[ROWS][COLS], int rows, int cols)
{
int x = 0;
int y = 0;
int win = 0;
while (win < (rows - 2) * (cols - 2) - COUNT)
{
printf("请输入坐标:");
scanf("%d %d", &x, &y);
if (x <= ROW && x<0 && y>=COL && y < 0)
{
if (mine[x][y] == '1')
{
printf("踩雷了!\n");
Displayboard(mine, ROW, COL);
break;
}
else
{
show[x][y] = countnum(mine, x, y) + '0';
Displayboard(show, ROW, COL);
win++;
}
}
else
{
printf("输入错误!\n");
}
}
if (win == (rows - 2) * (cols - 2) - COUNT)
{
printf("排雷成功!\n");
Displayboard(mine, rows, cols);
}
}
三、声明
#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 COUNT 10
void Initboard(char board[ROWS][COLS], int rows, int cols, char set);
void Setmine(char mine[ROWS][COLS], int row, int col, int count);
void Displayboard(char board[ROWS][COLS], int row, int col);
void Findmine(char mine[ROWS][COLS], char show[ROWS][COLS], int rows, int cols);
总结
扫雷代码并不难,和三子棋大同小易
|