test.c
#include "game.h"
void menu() {
printf("*****************************************\n");
printf("********** 1: play **********************\n");
printf("********** 0:exit **********************\n");
printf("*****************************************\n");
}
void game() {
char mine[ROWS][COLS] = { 0 };
char show[ROWS][COLS] = { 0 };
InitBoard(mine,ROWS,COLS, '0');
InitBoard(show,ROWS,COLS, '*');
DisplayBoard(show, ROW, COL);
PutLei(mine, ROW, COL);
DisplayBoard(mine, ROW, COL);
char res = 'C';
do{
res = SaoLei(mine, show, ROW, COL);
if (res=='S') {
printf("踩到雷了,游戏结束!\n");
DisplayBoard(mine, ROW, COL);
}
else if (res == 'W') {
printf("恭喜你,全部排雷成功!\n");
DisplayBoard(mine, ROW, COL);
}
else {
DisplayBoard(show, ROW, COL);
}
} while (res == 'C');
}
int main() {
srand((unsigned int)time(NULL));
int input = 0;
do {
menu();
printf("请选择:>");
scanf_s("%d",&input);
switch (input) {
case 1:
game();
break;
case 0:
printf("退出游戏\n");
break;
default:
printf("输入错误\n");
break;
}
} while (input);
return 0;
}
game.h
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROW 9
#define COL 9
#define ROWS ROW+2
#define COLS ROW+2
void InitBoard(char arr[ROWS][COLS],int row,int col, char set);
void DisplayBoard(char arr[ROWS][COLS], int row, int col);
void PutLei(char arr[ROWS][COLS], int row, int col);
char SaoLei(char main[ROWS][COLS], char show[ROWS][COLS], int row, int col);
game.c
#include "game.h"
void InitBoard(char arr[ROWS][COLS], int row, int col, char set) {
int i = 0;
int j = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
arr[i][j] = set;
}
}
}
void DisplayBoard(char arr[ROWS][COLS], int row, int col) {
int i = 0;
int j = 0;
printf("***** 扫雷游戏 ****\n");
for (int j = 0; j <= col; j++) {
printf("%d ", j);
}
printf("\n");
for (int i = 1; i <= row; i++) {
printf("%d ", i);
for (int j = 1; j <= col; j++) {
printf("%c ", arr[i][j]);
}
printf("\n");
}
printf("***** 扫雷游戏 ****\n");
}
void PutLei(char arr[ROWS][COLS], int row, int col) {
int count = MINE_COUNT;
while (count) {
int x = rand() % row + 1;
int y = rand() % col + 1;
if (arr[x][y] == '0') {
arr[x][y] = '1';
count--;
}
}
}
int remain(char arr[ROWS][COLS],int row,int col) {
int count = 0;
for (int i = 1; i <= row; i++) {
for (int j = 1; j <= col; j++) {
if (arr[i][j] == '*') {
count++;
}
}
}
return count;
}
char SaoLei(char mine[ROWS][COLS], char show[ROWS][COLS],int row, int col) {
int x = 0;
int y = 0;
while(1){
printf("请输入扫雷坐标:>");
scanf_s("%d %d", &x, &y);
if (x > 0 && x <= row && y > 0 && y <= col) {
if (show[x][y] == '*') {
if (mine[x][y] == '1') {
return 'S';
}
int count = 0;
int i = 0;
int j = 0;
for (i = x - 1; i <= x + 1; i++) {
for (j = y - 1; j <= y + 1; j++) {
if (mine[i][j] == '1') {
count++;
}
}
}
show[x][y] = count + '0';
int mine = remain(show, row, col);
if (mine == MINE_COUNT) {
return 'W';
}
return 'C';
}
else {
printf("坐标已经占位!");
}
}
else {
printf("输入坐标非法!");
}
}
return 'C';
}
