game.h文件
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define COUNT_MINE 10
#define ROW 9
#define COL 9
#define ROWS ROW+2
#define COLS COL+2
//初始化棋盘
void InitBoard(char board[ROWS][COLS], int rows, int cols, char set);
//打印棋盘
void DisplayBoard(char board[ROWS][COLS], int row, int col);
//设置雷
void SetBoard(char board[ROWS][COLS],int row, int col, char set);
//扫雷
void FindBoard(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;
for (i = 0; i < rows; i++)
{
int j = 0;
for (j = 0; j < cols; j++)
{
board[i][j] = set;
}
}
}
//打印棋盘
void DisplayBoard(char board[ROWS][COLS], int row, int col)
{
printf("--------扫雷游戏--------\n");
int i = 0;
for (i = 0; i <= col; i++)
{
printf("%d ", i);
}
printf("\n");
for (i = 1; i <= row; i++)
{
printf("%d ", i);
int j = 0;
for (j = 1; j <= col; j++)
{
printf("%c ", board[i][j]);
}
printf("\n");
}
}
//设置雷
void SetBoard(char board[ROWS][COLS],int row, int col, char set)
{
srand((unsigned int)time(NULL));
int count = COUNT_MINE;
while (count)
{
int x = rand() % row + 1;
int y = rand() % col + 1;
if (board[x][y] == '0')
{
board[x][y] = set;
count--;
}
}
}
//扫雷
void FindBoard(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col)
{
int count = ROW * COL - COUNT_MINE;
while (count)
{
int x = 0;
int y = 0;
printf("请输入坐标:>");
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 = 0;
int i = 0;
for (i = x - 1; i <= x + 1; i++)
{
int j = 0;
for (j = y - 1; j <= y + 1; j++)
{
if (mine[i][j] == '1')
count++;
}
}
show[x][y] = count + '0';
DisplayBoard(show, ROW, COL);
}
count--;
}
else
{
printf("坐标非法,请重新输入\n");
}
}
if (count == 0)
{
printf("恭喜你,扫雷成功!\n");
DisplayBoard(mine, ROW, COL);
}
}
test.c文件
#define _CRT_SECURE_NO_WARNINGS
#include"game.h"
//扫雷
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);
//设置雷
SetBoard(mine, ROW, COL, '1');
//DisplayBoard(mine, ROW, COL);
//扫雷
FindBoard(mine, show, ROW, COL);
}
void menu()
{
printf("*************************\n");
printf("***** 1.play *****\n");
printf("***** 0.exit *****\n");
printf("*************************\n");
}
int main()
{
int input = 0;
do
{
menu();
printf("请选择:>\n");
scanf("%d", &input);
switch (input)
{
case 1:
game();
break;
case 0:
printf("退出游戏\n");
break;
default:
printf("非法选择,请重新选择\n");
break;
}
} while (input);
return 0;
}
该文展示了使用C语言编写的扫雷游戏代码,包括棋盘初始化、打印棋盘、设置雷和扫雷的函数实现。玩家可以通过输入坐标进行扫雷操作,程序会检查是否踩到雷并更新显示。
5324





