Minesweeper.h
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define ROW 9
#define COL 9
#define COLA COL+2
#define ROWA ROW+2
void InitializeBoard(char Board[ROWA][COLA],int rowa, int cola,char sign);
void DisplayBoard(char Board[ROWA][COLA], int row,int col);
void SettingMines(char Board[ROWA][COLA], int row, int col);
void EliminateMines(char MineBoard[ROWA][COLA],char ScreenBoard[ROWA][COLA],int row,int col);
test_Minesweeper.c
#define _CRT_SECURE_NO_WARNINGS 1;
#include "Minesweeper.h"
menu()
{
printf("-------------------\n");
printf("----Minesweeper----\n");
printf("-------------------\n");
printf("----1.StartGame----\n");
printf("-------------------\n");
printf("------0. Exit------\n");
printf("-------------------\n");
}
void MinesweeperGame()
{
char MineBoard[ROWA][COLA] = {0};
char ScreenBoard[ROWA][COLA] = {0};
InitializeBoard(MineBoard, ROWA, COLA,'0');
InitializeBoard(ScreenBoard,ROWA,COLA,'@');
SettingMines(MineBoard, ROW, COL);
DisplayBoard(MineBoard,ROW,COL);
printf("\n");
DisplayBoard(ScreenBoard, ROW, COL);
EliminateMines(MineBoard, ScreenBoard,ROW,COL);
}
int main()
{
int input = 0;
srand((unsigned int)time(NULL));
do
{
menu();
printf("Hello Gamer:)");
scanf("%d", &input);
switch (input)
{
case 1:
MinesweeperGame();
break;
case 0:
break;
default:
printf(" Illegal Integer,please enter 1 or 0 :(\n");
break;
}
} while (input);
return 0;
}
Minesweeper.c
#define _CRT_SECURE_NO_WARNINGS 1;
#include"Minesweeper.h"
void InitializeBoard(char Board[ROWA][COLA], int rowa, int cola,char sign)
{
int i, j;
for ( i = 0; i < rowa; i++)
{
for (j = 0; j < cola; j++)
{
Board[i][j] = sign;
}
}
}
void SettingMines(char Board[ROWA][COLA], int row, int col)
{
int num = 10;
while (num>0)
{
int x = rand() % row + 1;
int y = rand() % col + 1;
if (Board[x][y] != '1')
{
Board[x][y] = '1';
num--;
}
}
}
static int detectmines(char MineBoard[ROWA][COLA],int x,int y)
{
return (MineBoard[x - 1][y - 1] + MineBoard[x - 1][y] + MineBoard[x - 1][y + 1] +
MineBoard[x][y - 1] + MineBoard[x][y + 1] +
MineBoard[x + 1][y - 1] + MineBoard[x + 1][y] + MineBoard[x + 1][y + 1]) - 8 * '0';
}
void EliminateMines(char MineBoard[ROWA][COLA], char ScreenBoard[ROWA][COLA], int row, int col)
{
int x, y;
int mark = 10;
while (mark)
{
printf("enter the location to unveil the board:");
scanf("%d,%d", &x, &y);
if (x >= 1 && x <= row && y >= 1 && y <=col)
{
if (MineBoard[x][y] == '1')
{
printf("BOOM!BOOM!BOOM!\n");
DisplayBoard(MineBoard, ROW, COL);
break;
}
else
{
int num = detectmines(MineBoard, x, y);
ScreenBoard[x][y] = num+'0';
DisplayBoard(ScreenBoard, ROW, COL);
mark--;
}
}
else
{
printf("illegal location\n");
}
}
if (mark == 0)
{
printf("you win\n");
DisplayBoard(MineBoard, ROW, COL);
}
}
void DisplayBoard(char Board[ROWA][COLA], int row, int col)
{
int i, j;
for ( i = 0; i <= col; i++)
{
printf("%d ", i);
}
printf("\n");
for ( i = 1; i <= row; i++)
{
printf("%d ", i);
for ( j = 1; j <= col; j++)
{
printf("%c ", Board[i][j]);
}
printf("\n");
}
}