扫雷游戏的代码完整版放在这里啦
分为三个部分,game.h , game.c ,还有main.c
其中game.c是进行函数实现的功能,main.c是主要的流程
game.h
#pragma once
#include <stdio.h>
#include <time.h>
#define ROW 9
#define COL 9
#define ROWS ROW+2
#define COLS COL+2
//初始化棋盘的声明
void Initboard(char board[ROWS][COLS], int row, int col, char set);
void Initboard(char board[ROWS][COLS], int row, int col, char set);
//打印棋盘
void Displayboard(char board[ROWS][COLS], int row, int col);
//设置雷的棋盘
void Setmine(char board[ROWS][COLS], int row ,int col);
//排雷
int Findmine(char mine[ROWS][COLS], int row, int col);
main.c
#define _CRT_SECURE_NO_WARNINGS 1
#include "game.h"
void static menu()
{
printf("---------------------\n");
printf("----- 1. play -----\n");
printf("----- 0 . exit -----\n");
printf("---------------------\n");
}
void static game()
{
char mine[ROWS][COLS] = { 0 };
char show[ROWS][COLS] = { 0 };
//初始化棋盘
Initboard(mine, ROWS, COLS, '0');
Initboard(show, ROWS, COLS, '*');
//打印棋盘
//Displayboard(mine, ROW, COL);
Displayboard(show, ROW, COL);
//布置雷
Setmine(mine, ROW, COL);
Displayboard(mine, ROW, COL);
int flag = 1;
while (flag) {
printf("请输入坐标:");
int a = 0, b = 0;
scanf("%d %d", &a, &b);
if (a > 9 || a < 1 || b > 9 || b < 1)
printf("请重新输入坐标!\n");
//排雷
if (mine[a][b] == '1') {
printf("炸死了\n");
show[a][b] = '#';
Displayboard(show, ROW, COL);
flag = 0;
}
else {
int Mine = Findmine(mine, a, b);
show[a][b] = Mine + '0';
Displayboard(show, ROW, COL);
}
}
}
int main()
{
int choose = 1;
while (choose)
{
menu();
scanf("%d", &choose);
srand((unsigned int)time(NULL));
switch (choose)
{
case 1:
game();
break;
case 0:
printf("exit\n");
break;
default:
printf("choose error,please again\n");
break;
}
}
return 0;
}
game.c
#define _CRT_SECURE_NO_WARNINGS 1
#include "game.h"
//初始化棋盘
void Initboard(char board[ROWS][COLS], int row, int col, char set)
{
for (int i = 0; i < ROWS; i++){
for (int j = 0; j < COLS; j++) {
board[i][j] = set;
}
}
}
//打印棋盘
void Displayboard(char board[ROWS][COLS], int row, int col)
{
printf("------- 扫雷 -------\n");
for (int i = 0; i <= row; i++) {
printf("%d ", i);
}
printf("\n");
for (int i = 1; i <= row; i++) {
printf("%d ", i );
for (int j = 1; j <= col; j++) {
printf("%c ", board[i][j]);
}
printf("\n");
}
printf("------- 扫雷 -------\n");
}
//布置雷
void Setmine(char board[ROWS][COLS], int row, int col) {
int count = 10;
while (count) {
int x = rand() % 10;
int y = rand() % 10;
if (board[x][y] != '1' && x >= 1 && y >= 1 && x <= 9 && y <= 9) {
board[x][y] = '1';
count--;
}
}
}
//排雷
int Findmine(char mine[ROWS][COLS], int row, int col) {
return mine[row - 1][col] + mine[row + 1][col] + mine[row][col - 1]
+ mine[row][col + 1] + mine[row - 1][col - 1] + mine[row + 1][col + 1]
+ mine[row - 1][col + 1]+ mine[row + 1][col - 1] - 8 * '0';
}
拜拜~~~