Code implementation of minesweeper game

Tip: After the article is written, the table of contents can be automatically generated. For how to generate it, please refer to the help document on the right.


Preface

This minesweeper is actually similar to the three-piece game we wrote before, both of which use the knowledge of arrays. The following is about writing the minesweeper game code.

1. Minesweeper Game Rules

The minesweeper game we have here is in a 9*9 format, so there are 81 grids. When we randomly open a grid, the number in the grid will be displayed. This number indicates how many mines there are in the eight surrounding grids. If the one we open is Lei will be blown up and the game will be lost. The game will be considered successful only when the grids that are not Lei have been checked.

2. Creation of Minesweeper game files

Before writing this game code, we must first create three files to store different game content. The text.c file is to store the test file of the game, game.c is to store the logic file to implement the game, and game.h is used to store the game. Declaration and definition files, header files can also be stored in them. In other .c files, you only need to include the #include "game.h" header file.

3. Writing game code

1.Create menu file

Before writing the main game code, we need to write a menu function. In the menu function, 1 means starting the game, and 0 means exiting the game.
Insert image description here
In the main function part of the game, we need to use do while and switch loop to implement
Insert image description here
The above code is placed in the text.c file

2. Initialization of the chessboard

In the initialization board, we need to create two arrays, a mine array to store mine information, and a show array to display mine troubleshooting information; we encapsulate an InitBoard function to initialize these two arrays.
Use #define in the game.h file to define ROW COL ROWS COLS and initialize the chessboard statement:
Insert image description here
Insert image description here

The array here uses 11*11 to prevent out-of-bounds access to the array.

Initialization in text.c file:
Insert image description here
The reason why we use a character array here is: when we check mine information, we need to display the number of mines around the target location, and The ASCII code of the character '0' is 48, and the ASCII code of the character '1' is 49. We add up the coordinates around the target position and subtract the character '0'x8 to get the number of mines at the target position, and then The number of characters is displayed in the show array

Implementation in game.c file:
Insert image description here
Note: The set when passing parameters here determines the content of the array initialization, so one more parameter is passed. Just call this InitBoard function twice to initialize two arrays. Here are the function parameters, encapsulated in the game function

3. Print the chessboard

In printing the chessboard, we only need to print the mine detection information
In the text.c file:
Insert image description here
In the game.c file:
Insert image description here
Statement in game.h file:
Insert image description here

4. Lay out mines

The character ‘1’ means thunder, the character ‘0’ means not thunder, and the character ‘*’ means a location that has not been checked yet.
When deploying mines, we need to use random values, so we need to use timestamps, and we also need to use the two functions srand and time and include header files, and we also need to use them when deploying mines. When using #define in the game.h file, declare the number of these 10 mines and the declaration of the layout of the mines.
Insert image description here
Insert image description here
In text.c file:
Insert image description here
Insert image description here

Implementation in game.c file:
Insert image description here

5. Check for mines

is a loop in the process of checking for mines, so we have to use a while loop to implement it. There are 10 mines in rowcol characters. Only when we remove all the mines that are not mines The game is won only after checking the positions, so we write
win < (row * col -EASY_COUNT) in the conditional judgment of while as the condition for judging winning or losing;
The entered coordinate value must be within the range of 9x9
If the coordinate is not within the range of 9x9, the coordinate is illegal
If the entered coordinate position If the content is not an asterisk, it means that the coordinate position has been checked.
If the character at the input coordinate position is equal to '1', it means that the coordinate is mine and the game is over
If none of the above, then display the number of mines with coordinates of 8 around the target position, and check for a win++;
Only when win is equal to the total number of characters minus the number of mines , it means the demining is successful;
Insert image description here
Taking x, y as the target position, adding the eight surrounding coordinates and subtracting 8
'0', we get The result is the number of mines in the eight surrounding coordinates
Insert image description here
Insert image description here
The above codes are all in the game.c file:

The following is in the text.c file:
Insert image description here
The statement in the game.h file:
Insert image description here

4. Overall code

text.c file:

#define _CRT_SECURE_NO_WARNINGS 1
#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);

	//布置雷
	SetMine(mine, ROW, COL);
	//DisplayBoard(mine, ROW, COL);

	//排查雷
	FindMine(mine, show, ROW, COL);
}

int main()
{
    
    
	srand((unsigned int)time(NULL));
	int input = 0;
	do
	{
    
    
		menu();
		printf("请选择>:");
		scanf("%d", &input);
		switch (input)
		{
    
    
		case 1:
			game();
			break;
		case 0:
			printf("退出游戏\n");
			break;
		default:
			printf("选择错误,重新选择\n");
			break;
		}
	} while (input);
	return 0;
}

game.c file:

#define _CRT_SECURE_NO_WARNINGS 1
#include "game.h"

void InitBoard(char board[ROWS][COLS], int rows, int cols, char set)
{
    
    
	int i = 0;
	int 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)
{
    
    
	int i = 0;
	int j = 0;
	printf("---------扫雷--------\n");
	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");
	}
	printf("---------扫雷--------\n");
}


void SetMine(char mine[ROWS][COLS], int row, int col)
{
    
    
	int count = EASY_COUNT;
	while (count)
	{
    
    
		int x = rand() % row + 1;
		int y = rand() % col + 1;
		if (mine[x][y] == '0')
		{
    
    
			mine[x][y] = '1';
			count--;
		}
	}
}

int GetMineCount(char mine[ROWS][COLS], int x, int y)
{
    
    
	return mine[x - 1][y] +
		mine[x - 1][y - 1] +
		mine[x][y - 1] +
		mine[x + 1][y - 1] +
		mine[x + 1][y] +
		mine[x + 1][y + 1] +
		mine[x][y + 1] +
		mine[x - 1][y + 1] - 8 * '0';
}

void FindMine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col)
{
    
    
	int x = 0;
	int y = 0;
	int win = 0;

	while (win < row * col - EASY_COUNT)
	{
    
    
		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
			{
    
    
				//不是雷,就统计x,y坐标周围有几个雷
				int c = GetMineCount(mine, x, y);
				show[x][y] = c + '0';
				DisplayBoard(show, ROW, COL);
				win++;
			}
		}
		else
		{
    
    
			printf("坐标非法,重新输入\n");
		}
	}
	if (win == row * col - EASY_COUNT)
	{
    
    
		printf("恭喜你,排雷成功\n");
		DisplayBoard(mine, ROW, COL);
	}
}

game.h file:

#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 EASY_COUNT 10

//初始化棋盘
void InitBoard(char board[ROWS][COLS], int rows, int cols, char set);

//打印棋盘
void DisplayBoard(char board[ROWS][COLS], int row, int col);

//布置雷
void SetMine(char mine[ROWS][COLS], int row, int col);

//排查雷
void FindMine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col);

Guess you like

Origin blog.csdn.net/2301_78373304/article/details/132645582