(C language) minesweeping game

Posted by kkibak on Wed, 05 Jan 2022 10:29:24 +0100

catalogue

For the comprehensive application of circular statements, conditional statements and arrays in C language, comments are provided at the end of each code. I hope you can understand them

 

Article catalog

Preface (required knowledge points)

For the comprehensive application of circular statements, conditional statements and arrays in C language, write a minesweeping game

1. Use the while for do while statement

2. Use the switch if statement

3. Using two-dimensional array

4. Use of random numbers (follow my blog in previous periods)

5. Function call

6. Function declaration, macro definition and use

1, Create file

The first step is to create two c , file, text , file for testing, and game file for creating functions

Step 2: create a h header file, put the header file, macro and function declaration required in the first two files into this file to make c) tidier documents

2, Write

1. Introduce the main function into the test

The code example is as follows:

#Pragma warning (disable: 4996) / / vs2019 scanf and other functions need to close the warning
#include "game.h" / / introduce the define macro function declaration defined in the header file
void menu()//Menu interface
{
	printf("**********************************\n");//Minesweeping interface
	printf("*        Welcome to Minesweeper        *\n");
	printf("*           1.Play games           *\n");
	printf("*           0.Exit the game           *\n");
	printf("**********************************\n");
}
void game()
{
	char mine[ROWS][COLS] = { 0 };//Store mine information
	char show[ROWS][COLS] = { 0 };//Game interface for users
	Initboard(mine, ROWS, COLS, '0');//Initialize ray (for the editor)
	Initboard(show, ROWS, COLS, '*');//Initialize thunder (show players)
	Setmine(mine, ROWS, COLS);//Using random numbers to generate random mines
	Display(show, ROW, COL);//Show the initialized interface to the player
	Display(mine, ROW, COL);//It is not necessary to write the program set by Leibu (at will)
	Findmine(show, mine, ROW, COLS);//The player's demining function realizes demining according to the coordinates provided by the player
}
void main()
{
	int input = 0;//Define variables for ---- > selection by user input
	srand((unsigned int)time(NULL));//Set random numbers to generate random mines on a 9 * 9 chessboard
	do
	{
		menu();//Call menu function
		printf("Please select serial number---->");
		scanf("%d", &input);//User input variable value
		switch (input)//Play or exit the game according to user input
		{
		case 1:
			game();//Select 1 to play the game and call the game function
			break;
		case 0:
			printf("\nexit\n");//User enters 0 to exit the program
			break;
		default:
			printf("Serial number selection error, please re select\n");//If the user inputs wrong, return to cycle judgment 0 / 1 again
		}
	} while (input);//According to the de circulation input by the user, the user input 1 continues to play the game, and the player input 0 terminates the program
}

2. Header file + macro + function declaration

The code example is as follows:

#pragma once
#include <stdio.h>
#include <stdlib. h> / / srand's header file
#include <time. h> / / header file of timeH function
#define ROW 9 / / define macros to facilitate uniform modification
#define COL 9 / / set Lei in the 9 * 9 grid to prevent the two-dimensional array from crossing the boundary
#define ROWS ROW+2 / / prevent the two-dimensional array from accessing beyond the boundary. Set two more rows and two more columns during initialization
#define COLS COL+2
#define EASY_COUNT 10 / / set 10 mines
void Initboard(char board[ROWS][COLS], int rows, int cols, char set);//Use function after function declaration 
void Display(char board[ROWS][COLS], int row, int col);
void Setmine(char board[ROWS][COLS], int row, int col);
void Findmine(char show[ROWS][COLS], char mine[ROWS][COLS], int row, int col);

In the 9 * 9 minesweeping game shown in the figure, the outer frame we set is a 11 * 11 two-dimensional array. We set the Minesweeper in the 9 * 9 grid, including the 9 * 9 grid presented to the player. The two extra lines of 11 * 11 are respectively to prevent the two-dimensional array from being accessed beyond the boundary and causing errors.

Some students don't understand why cross-border access occurs. We imagine that if we directly set up a 9 * 9 grid, we should visit the grid in the lower left corner to judge whether there are thunder in the eight grids around him. Some grids are obviously outside the grid we see, which leads to cross-border access. Accessing outside the two-dimensional array will cause errors

3. Functions required by the game

#pragma warning(disable : 4996)
#include "game.h" / / import the required header files, macros, and function declarations
void Initboard(char board[ROWS][COLS], int rows, int cols, char set)//Initialization interface
{
	int i = 0;
	int j = 0;
	for (j = 0; j < rows; j++)
	{
		for (i = 0; i < cols; i++)
		{
			board[i][j] = set;//Initialize * to assign a value to a typical two-dimensional array
		}
	}
}
void Display(char board[ROWS][COLS], int row, int col)//Print out the interface for players to see and make the player interface
{
	int i = 0;
	int j = 0;
	for (i = 0; i <= 9; i++)
	{
		printf("%d ", i);//Print line number
	}
	printf("\n");
	printf("----------------------\n");
	for (j = 1; j <= row; j++)
		{
			printf("%d|", j );//Print column number
			for (i = 1; i <= col; i++)
			{
				printf("%c ", board[i][j]);
			}
			printf("|");
			printf("\n");
		}
	printf("----------------------\n");
}
void Setmine(char board[ROWS][COLS], int row, int col)
{
	int minecount = EASY_COUNT;//Set the number of mines
	while (minecount)//Cyclic de mining
	{
		int x = rand() % 9 + 1;//Because it's a player, you have to start with a subscript of 1, so + 1
		int y = rand() % 9 + 1;
		if (board[x][y] != '1')//Judge whether the position of X and Y coordinates has been mined
		{
			board[x][y] = '1';//If there is no lightning, set the corresponding coordinates as lightning and use '1' to represent lightning
			minecount--;
		}
	}
}
int Getmine(char mine[ROWS][COLS], int x, int y)//When you sweep away a coordinate without mines, the coordinate displays the number of surrounding mines
{
	return (mine[x-1][y]+mine[x+1][y]
		  +mine[x][y-1]+mine[x-1][y-1]+mine[x+1][y-1]
		  +mine[x][y+1]+mine[x-1][y+1]+mine[x+1][y+1]-8*'0');//These coordinates together are characters. Each character '0' can be subtracted to get the corresponding integer data
}
void Findmine(char show[ROWS][COLS], char mine[ROWS][COLS], int row, int col)
{
	int x = 0;//Two variable values are defined, and the user inputs the corresponding mine sweeping coordinates
	int y = 0;
	int win = 0;
	while (win < col * row - EASY_COUNT)//The termination condition of the cycle is that the 9 * 9 chessboard minus the number of thunder is full, and the game is terminated
	{
		printf("Please enter the coordinates to be checked------>");
		scanf("%d %d", &x, &y);//User input mine clearance coordinates
		if (x >= 1 && x <= row && y >= 1 && y <= row)//Judge the correctness of coordinate input
		{
			if (mine[x][y] == '1')//Judge if the character corresponding to the coordinates entered by the user is' 1 ', that is, the user stepped on the thunder, the game is over, and the layout of the thunder is displayed to the player
			{
				printf("I'm sorry you were killed!!\n");
				printf("The minefield is shown in the figure. Refuel next time!!\n");
				Display(mine, ROW, COL);//Display layout
				break;//Cycle to end the next game

			}
			else//The coordinates entered did not step on the mine
			{
				int count = Getmine(mine, x, y);//Call the function to get the number of surrounding mines
				show[x][y] = count + '0';
				if (count == 0)//If there is no thunder around, clear all eight coordinates near the coordinates (set the eight surrounding grids as spaces) (imitating web minesweeping)
				{
					show[x-1][y] = ' ';
					show[x+1][y] = ' ';
					show[x][y +1] = ' ';
					show[x - 1][y +1] = ' ';
					show[x+1][y +1 ] = ' ';
					show[x +1][y-1] = ' ';
					show[x - 1][y-1] = ' ';
					show[x][y-1] = ' ';

				}//The thunder value around the position corresponding to the coordinate is assigned to the show array
				Display(show, ROW, COL);//Display the surrounding area corresponding to the input coordinates
			}
		}
		else
		{
			printf("The coordinates entered are illegal. Please re-enter\n");
		}
		if (win == row * col-EASY_COUNT)//Except for the coordinates of the mine, the mine was cleared successfully
		{
			printf("Congratulations on your success\n");
		}
	}
}

4. Explain a knowledge point

Integer data + character '0' = corresponding character type

eg. 1+'0'='1'

We see that the ASCII value of character 0 is 30 and the value of character 1 is 31, so the numeric character 0 + 1 = character 1

 

 

 

 

 

 

summary

C language is a classic minesweeping game. Beginners of C language can try to knock it by themselves. They can consolidate their knowledge and strengthen their code ability. If there are any problems, they can comment in private at any time. Welcome to discuss it together

Topics: C