[Turn on the C Language bald journey] Minesweeper Game

hello, minasan.

Remember who had great fun with big-bottom computers and playing minesweeping with friends before?

Take advantage of the last small tail at the end of the year to learn how to use C language to implement a simple version of the Minesweeper game!

Finished Product Display:

Catalog

1. Ideas Analysis

2. Included header files and macro definitions

3. Major Functions Used

1. Initialize the board

2. Mine Layout

3. Mine clearance

4. Find the number of Mines nearby

5. Print board

6. Expand the board

7. Judging Win or Lose

8. integration

1. Ideas Analysis

Here we make the simplest 9 × 9-grid Minesweeper game, 81 of which must have the same type of storage, so it's easy to think of using a two-dimensional array for storage.

Then we started to think about what the Minesweeper game needs to do?

ps: Here the thunder is represented by the character''1', the character''0'for those without thunder, and the character'*' for undetected areas.

1. The menu interface is indispensable and the simplest, so let's not go into it.

2. Initialize the board by first placing no thunder in all the cells. At this point, we want to think that the system will have a lightning board (equivalent to the final answer) and the board presented to the user during the clearing process, so we will set up two boards when setting up. If you set up the board at this time, your first reaction is to set up 9 directly. × 9 array right? However, if you think about the number of mines in the eight surrounding grids when you sweep again, the middle grids are good. If the grids on the border are not difficult to handle? So we chose to add two more rows and two more columns around them (expanding the area) so that we could have eight grids around the grids we wanted to sort out.

Fig.

3. After the board has been initialized, we need to keep Rayan down. At this time, we should pay special attention to Ann's Ray. He needs to be in the middle 9 × 9 of the grid, and randomly placed, so we need to use Generation of Random Numbers for srand and rand Functions . Then print the board.

4. When everything is ready, it is time for the user to clear the mines. First, the user should check if there are any mines in the squares of the user platoon. If there are no, check the eight nearby squares. If there are several squares with mines, the number will be displayed. Here we also think that when there are no mines in several nearby grids (not just eight), the search area will spread out, so we write an additional set of diffusion functions.

Fig.

5. Finally, it's a function of whether we win or lose, when we put the middle 9 × After 81 (total number of grids) - 10 (number of mines) of the 9 grids have been sorted out, they also represent winning. If you step on a thunder halfway, you lose

2. Included header files and macro definitions

#define ROW 11
#define COL 11//Used to define 11 × Array of 11

#define R 9
#define C 9//Define 9 rows, 0 columns

#define easy_count 10//total number of Mines defined 10

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <time.h>
#include <stdlib.h>

//Initialize the board
void init_board(char arr[ROW][COL], int row, int col, char c);

//Mine Layout
void set_mine(char mine[ROW][COL],int r,int c);

//Mine clearance
void find_mine(char mine[ROW][COL],char show[ROW][COL], int r, int c);

//Find the number of Mines nearby
int get_mine_count(char mine[ROW][COL], int x, int y);

//Print board
void show_board(char arr[ROW][COL], int r, int c);

//Expand the board
void spread_board(char mine[ROW][COL],char show[ROW][COL], int row, int col);

3. Major Functions Used

1. Initialize the board

//Initialize the board
void init_board(char arr[ROW][COL], int row, int col, char c)
{
	int i = 0,j = 0;
	for (i = 0; i < row; i++)
	{
		for (j = 0; j < col; j++)
		{
			arr[i][j] = c;
		}
	}
}

Here's a little detail, and char c didn't rush to replace it with'0'or'*' when I used the last parameter, because we know that to initialize two boards, printing with'0'and'*' is redundant. Instead of a new parameter c, enter the arguments''0'or'*' on the call.

Also note: every time you invoke an array, ask yourself silently what I want to do with 11 × 11 or 9 × Area of 9. Here we're going to initialize the whole board to 11 × 11. row and col use 11 when calling this function.

2. Mine Layout

//Mine Layout
void set_mine(char mine[ROW][COL], int r, int c)
{
	int count = easy_count;
	int x = 0, y = 0;
	while (count)
	{
		x = rand() % r + 1;
		y = rand() % c + 1;
		if (mine[x][y] == '0')
		{
			mine[x][y] = '1';
			count--;
		}
	}
}

The Mine Layout function notices that the arguments at the time of the call are the system's chessboard, not the user's chessboard. To distinguish this, I'll take part in the same name mine[ROW][COL] of the argument settings.

Ask yourself again that 11 is used here × 11 or 9 × 9, we're laying out the mines here in the middle 81 lattices so we're using 9 × Region 9, both r and c called are 9.

3. Mine clearance

//Mine clearance
void find_mine(char mine[ROW][COL], char show[ROW][COL], int r, int c)
{
	int x = 0, y = 0,win=0;//win is here to pave the way for subsequent judgments, regardless of it
	while (win<r*c- easy_count)
	{
		printf("Please enter the coordinates to be sorted:>\n");
		scanf("%d %d", &x, &y);
		if (x >= 1 && x <= r && y >= 1 && y <= c)//Here you want to determine if the coordinates you entered are legal, in the middle 9 × Within the range of 9, that is, the values of x and y should be between 1 and 9
		{
			if (mine[x][y] == '1')//Previously set the character of the mine is'1', call the system board, if the input x and y exactly correspond to the system board is'1', then step on the mine, the game ends
			{
				printf("Unfortunately, it was blown up\n");
				show_board(mine, R, C);//Dead must also have a look, and finally print the system board (correct answer) to the user
				break;//Exit Loop
			}
			else
			{
				int count = get_mine_count(mine,x,y);//Count, counting the number of mines in the eight surrounding grids, get_ Mine_ The count function is the function that counts the number of Mines
				show[x][y] = count + '0';//Because count is int and array is char, we can also get the character'n (a number)'to represent the number of mines by adding the character'0' to count.
				spread_board(mine,show, x, y);//spread function
				show_board(show, R, C);//Print the Minesweeper in the area that the user has already swept before stepping on it to make the next Minesweeper easier for the user
				win=is_win(show, r, c);//Judging Win/Loss Function Returns an int
			}
		}
		else
		{
			printf("Input coordinates are illegal, please re-enter\n");//Illegal input coordinates
		}
	}
	if (win == r * c - easy_count)//Judging Win or Lose
	{
		printf("Congratulations, mine clearance was successful\n");
		show_board(mine, R, C);
	}
}

4. Find the number of Mines nearby

//Find the number of Mines nearby
int get_mine_count(char mine[ROW][COL], int x, int y)
{
	return mine[x - 1][y - 1] + mine[x - 1][y] + mine[x - 1][y + 1] + mine[x][y - 1] + mine[x][y + 1] + mine[x + 1][y - 1] + mine[x + 1][y] + mine[x + 1][y + 1] - 8 * '0';
}

The number of mines to find returns a number so it is int. mine arrays are all char type, but as long as | Gray | Character''1'minus | Gray | Character''0' without Gray get the number 1. So add up the characters in the eight surrounding cells and subtract the eight characters'0'to get the return value.

5. Print board

//Print board
void show_board(char arr[ROW][COL], int r, int c)
{
	int i = 0, j = 0;
	printf("------------------mine clearance------------------\n\n");//Split lines, or define your own preferences
	for (i = 0; i <= r; i++)
	{
		printf(" %d |",i);//Print 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 in turn to make it easier for users to read coordinates when they are sweeping mines. Here is the horizontal coordinate
	}
	printf("\n---|---|---|---|---|---|---|---|---|---|\n");//Print dividing lines of tables
	for (i = 1; i <= r; i++)
	{
		printf(" %d |", i);//Print 1|, 2|, 3|, 4|, 5|, 6|, 7|, 8|, 9| as vertical coordinates and split lines
		for (j = 1; j <= c; j++)
		{
			printf(" %c |", arr[i][j]);//Print the user's board and splitter lines in turn
		}
		if(i!=r)
		printf("\n---|---|---|---|---|---|---|---|---|---|\n");
	}
	printf("\n------------------mine clearance------------------\n");//Split lines, or define your own preferences
	printf("\n");
}

Printing the board itself is not difficult, because the process is a bit cumbersome and there are a lot of sentences, which require little partners to debug and modify.

6. Expand the board

//Expand the board
void spread_board(char mine[ROW][COL], char show[ROW][COL], int x, int y)
{
	if (x >= 1 && x <= 9 && y >= 1 && y <= 9)//Because this is a set of recursive functions, we want to set the range, so we first judge whether the values of x and y are legal, if not set, then we will see that the array crosses the boundary.
	{
		while (mine[x - 1][y] == '0'&&show[x-1][y]=='*')
		{
			int count = get_mine_count(mine, (x - 1), y);
			if (count == 0)
			{
				show[x - 1][y] = '0';
				spread_board(mine, show, (x - 1), y);
			}
			else 
				break;
		}
		while (mine[x + 1][y] == '0' && show[x + 1][y] == '*')
		{
			int count = get_mine_count(mine, (x + 1), y);
			if (count == 0)
			{
				show[x + 1][y] = '0';
				spread_board(mine, show, (x + 1), y);
			}
			else
				break;
		}
		while (mine[x][y - 1] == '0' && show[x][y-1] == '*')
		{
			int count = get_mine_count(mine, x, (y - 1));
			if (count == 0)
			{
				show[x][y - 1] = '0';
				spread_board(mine, show, x, (y - 1));
			}
			else
				break;
		}
		while (mine[x][y + 1] == '0' && show[x][y+1] == '*')
		{
			int count = get_mine_count(mine, x, (y + 1));
			if (count == 0)
			{
				show[x][y + 1] = '0';
				spread_board(mine, show, x, (y + 1));
			}
			else
				break;
		}
	}
}

Take one example, where the value of mine[x-1][y] in the system checkboard is'0'without mines and the value of show[x-1][y] in the user's checkboard is'*', i.e. the user has not scanned the grid for mines (the author neglected this statement at the beginning of writing), both statements are satisfied, and get_ Mine_ The count function reads in to see if there are any mines in the eight grids around [x-1][y], and then determines if count is 0 (there are no mines around it), so the [x-1][y] point can be scanned out and assigned a value of'0'.

7. Judging Win or Lose

//Judging Win or Lose
int is_win(char show[ROW][COL],int r,int c)
{
	int x = 1, y = 1,win=0;
	for (x = 1; x <= r; x++)
	{
		for (y = 1; y <= c; y++)
		{
			if (show[x][y] != '*')
				win++;
		}
	}
	return win;
}

* Each detected user's board has a value that is not'*', that is, every grid scanned wins+1, adding to the end, as long as the value of win equals r * c - easy_count (9*9-10=71) [this statement is in the last if judgment statement in mine clearance], which proves that the user won and the mine was cleared successfully.

8. integration

void menu()//menu
{
	printf("**************\n");
	printf("****1.play****\n");
	printf("****2.exit****\n");
	printf("**************\n");
}
void game()
{
	char mine[ROW][COL]={0};//System Checkerboard
	char show[ROW][COL]={0};//User Checkerboard


	init_board(mine, ROW, COL, '0');//Initialize the system board to'0'
	init_board(show, ROW, COL, '*');//Initialize user's checkerboard to'*'(not detected)

	set_mine(mine, R, C);//Mine Layout

	show_board(show, R, C);
	
	find_mine(mine,show, R, C);//Mine clearance

}
void test()
{
	int input=0;
	do
	{
		menu();
		printf("Please select:>\n");
		scanf("%d", &input);
		switch (input)
		{
		case 1:
		{
			game();
			break;
		}
		case 0:
		{
			printf("Exit Game\n");
			break;
		}
		default:
		{
			printf("Input error, please re-enter\n");
			break;
		}
		}
	} while (input!=1&&input!=0);
}

int main()
{
	srand((unsigned int)time(NULL));
	test();
	return 0;
}//Finally, it ends with a short and intricate dream function, with so many function codes behind a few short sentences

Finally, there are seven days left for the New Year! Here I wish you all good luck in the Year of the Tiger and good luck in the Spring Festival. Family harmony lasts for a long time and social harmony strengths increase. Happy New Year Festival reunion, health and safety!

Quickly pull up the pk from your own game program written by your good friend!


Attach another game here [Turn on the C Language Baldness Tour] Triple Chess Game

Keywords: C Game Development

Added by fuzzy1 on Wed, 26 Jan 2022 08:55:52 +0200