当前位置:网站首页>C language war "minesweeping"
C language war "minesweeping"
2022-06-11 06:14:00 【Desperate Azi】
minesweeper , You might as well write about minesweeping
When you can write about minesweeping
Mine clearance succeeded , It's not a matter of seconds

Catalog
1. User interaction page
2. Minesweeping principle and code implementation
1. User interaction page
- Input 1, It means playing games
- Input 0, It means not playing games
void menu()
{
printf("**************************\n");
printf("******1.play 0.exit******\n");
printf("**************************\n");
}The main function
int main()
{
int n = 0;
do
{
menu();
printf(" Please enter n:");
scanf("%d", &n);
switch (n)
{
case 1:Minesweeper(); break;
case 0:printf(" sign out \n"); break;
default:printf(" Please re-enter \n"); break;
}
} while (n);
return 0;
}First the program starts running by calling menu function , Print start interactive page , Convenient for users to choose .
When user input 1 It means playing games , It is called Minesweeper( Mine clearance ) function
When user input 0 It means not playing games , Just quit the program
If the user enters other values , You will be prompted to re-enter
Application do...while The benefits of recycling : Execute before judge , Come up and go straight in , Let the user choose whether to play the game . If you play the game and play a game , Still want to play , Enter again 1, Keep playing . If you don't want to play, just type 0 Quit the game .
2、 Mine clearance
#define ROW 9
#define COL 9
#define ROWS 11
#define COLS 11
#define NUMBER 10void Minesweeper()
{
srand((unsigned int)time(NULL));
// Minefields
char arr[ROWS][COLS] = { 0 };
// Demining area
char brr[ROWS][COLS] = { 0 };
// Initialize minefield checkerboard
Board(arr, ROWS, COLS, '0');
// Initialize the demining area checkerboard
Board(brr, ROWS, COLS, '*');
// Arrange thunder
Set_mine(arr, ROW, COL);
Print(brr, ROW, COL);
// Start demining
Find_Mine(arr, brr, ROW, COL);
}2.1 Set up a chessboard
Build two checkerboards , The size is 11*11 , One chessboard is a minefield arr[11][11], The other board is the demining area brr[11][11]
Although the size of both chessboards is 11*11, But only the demining area is displayed when demining 9*9 The size of the The board .
Why only the demining area is displayed 9*9 The area is empty ?
- Only demining areas are displayed because they are not visible to the user , If a minefield is displayed, users will know where the mine is
- Display only 9*9 Because of avoiding the cross-border visit when clearing the surrounding mines in the back

Be careful : The outermost layer of the minefield ( White area ) No thunder , And mine clearance is not allowed , Because I only showed the middle of the demining area 9*9 The board
2.2 Initialize chessboard
// Initialize the minesweeping chessboard
void Board(char arr[ROWS][COLS], int rows, int cols, char n)
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
arr[i][j]= n;
}
}
}use arr[ROWS][COLS] To receive the data that needs to be initialized Array
use rows To receive That's ok
use cols To receive Column
use n To receive what needs to be initialized Elements ( for example n=‘*’, Just initialize all the fields in the array to ‘*’)
First initialize the minefields to characters ‘0’
After initializing the demining area to characters ‘*’
2.3 Arrange thunder
// Arrange thunder
void Set_mine(char arr[ROWS][COLS], int row, int col)
{
int a = 0;
while (a < NUMBER)
{
int i = rand() % row + 1;
int j = rand() % col + 1;
if (arr[i][j] != '1')
{
arr[i][j] = '1';
a++;
}
}
}After initializing the minefield , It's time to lay out the thunder
use arr[ROWS][COLS] To receive what needs to be mined Array
use row To receive That's ok
use col To receive Column
notes : The incoming rows and columns are listed separately 9, Because ray can only be arranged in 9*9 Region , In order to avoid the number of surrounding mines exceeding the limit in the following statistics
Arrangement NUMBER A thunder , let a=0, loop a < NUMBER Time , Every time the layout succeeds, thunder will a++,rand() %row
Indicates that the range for obtaining random values is [0,row),rand() % row + 1 Indicates that the range of random values obtained is [1,row]
That's ok :1~row
Column :1~col
Why the minimum random value is 1?
Because if the outermost layer of the minefield is mined , When counting the number of surrounding mines, it is easy to cause cross-border visits
In the use of rand() Before the function, you need to use srand((unsigned int)time(NULL)), To prevent random values from repeating each time , Just use the timestamp to initialize
2.4 Print the checkerboard for minesweeping
// Print minesweeping chessboard
void Print(char arr[ROWS][COLS], int row, int col)
{
printf("*********** Print chessboard *************\n");
for (int i = 0; i <= row ; i++)
{
printf("%d ", i);
}
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");
}
}
To beautify and prompt the effect of direct printing :********** Print chessboard **********
In order to facilitate the user to input the required position : Print line numbers and column labels
- Column labels are printed directly in one cycle , From what 0 Start Because the first column prints the line number
- The line number is printed before a line of checkerboard in the minesweeping area each time , Just print a line number
4.5 Start demining
// Start demining
void Find_Mine(char arr[ROWS][COLS], char brr[ROWS][COLS], int row, int col)
{
while (1)
{
int a = 0;
int b = 0;
printf(" Please enter the subscript you want to clear :");
scanf("%d%d", &a, &b);
if (a > 0 && a < 10 && b > 0 && b < 10)
{
if (arr[a][b] == '1')
{
printf(" sorry , You stepped on thunder \n");
Print(arr, ROW, COL);
break;
}
else
{
int count = Mine_Num(arr, a, b);
if (count == 0)
{
brr[a][b] = ' ';
Spread(arr, brr, a, b);
Print(brr, ROW, COL);
}
else
{
brr[a][b] = count + '0';
Print(brr, ROW, COL);
}
}
}
else
{
printf(" Please re-enter :\n");
}
if (success(brr, ROW, COL))
{
printf(" Congratulations on your success \n");
Print(arr, ROW, COL);
break;
}
}
}The overall idea of demining :
Demining cannot be done only once , You have to queue many times , And find out all the locations that are not mine , In the end, only the position of the mine left in the minefield is not discharged . Therefore, it is necessary to input the index of demining for many times , Let's use a loop .
After entering the mine clearance subscript, we need to determine whether the entered subscript is within the printed mine clearance area (9*9)
If it is not within the range, you need to re-enter , If it is in the range, you need to judge whether this position is thunder , If it is ray, the game will fail . If it is not a mine, assign the number of surrounding mines to the corresponding position of the demining area and print , If there is no thunder around, display a space and print the area around it that is not thunder . Then judge whether the number of positions of the remaining demining areas without rows is the same as the number of mines. If so, it will prove that demining is successful , Otherwise, continue demining .
Count the number of thunder around :
// The number of thunder around
int Mine_Num(char arr[ROWS][COLS], int a, int b)
{
return arr[a - 1][b - 1] +
arr[a - 1][b] +
arr[a - 1][b + 1] +
arr[a][b - 1] +
arr[a][b + 1] +
arr[a + 1][b - 1] +
arr[a + 1][b] +
arr[a + 1][b + 1] - 8 * '0';
}
Put the minefield arr[a][b] , The corresponding values in the surrounding coordinates are added up and subtracted 8*‘0’, Why subtract 8*‘0’, Because the characters in the minefield are not thunder ‘0’, What Lei put is the character ‘1’, So add up the characters around it and subtract 8*‘0’, It becomes a number ,( There is 8 The coordinates are 8*‘0’).
If you return 0, It means there is no thunder around , Go to judge whether there is thunder around the eight coordinates in turn , Recursion until ray is found , And you can't cross the line
If not 0, Returns other numbers, assuming letters a To represent that number , It means there are a A thunder , You don't expand the surrounding coordinates , And assign the position of the subscript of the row to a+‘0’( It means that the number is converted into characters again ), And print in that location .
Expand the area without thunder :
// Unfold the thunder that is not around
void Spread(char arr[ROWS][COLS], char brr[ROWS][COLS], int x, int y)
{
if (x >= 1 && x <= ROW && y >= 1 && y <= COL)
{
for (int around_x = -1; around_x <= 1; around_x++)
{
for (int around_y = -1; around_y <= 1; around_y++)
{
if (arr[x + around_x][y + around_y] == '0')
{
int count = Mine_Num(arr, x + around_x, y + around_y);
if (count == 0)
{
if (brr[x + around_x][y + around_y] == '*')
{
brr[x + around_x][y + around_y] = ' ';
Spread(arr, brr, x + around_x, y + around_y);
}
}
else
{
brr[x + around_x][y + around_y] = count + '0';
}
}
}
}
}Because we expand the coordinates around , Recursion to use , So it may cause cross-border visits , The first step we take into this function is to determine whether the coordinates are in the region , If the surrounding coordinates are also empty, put ‘ ’ Assign a value to the corresponding minesweeping area position
Why set the chessboard to 11*11?
If the coordinates we checked are (1,1), When we count the coordinates around us, we won't cross the border to visit , Because the chessboard of our minefield is 11*11, The thunder we arranged is 9*9 Inside the chessboard .
Judge success :
// Judge success
int success(char brr[ROWS][COLS], int row, int col)
{
int count = 0;
for (int i = 1; i <= row; i++)
{
for (int j = 1; j <= col; j++)
{
if (brr[i][j] == '*')
{
count++;
}
}
}
if (count == NUMBER)
{
return 1;
}
return 0;
}
Traverse the position of the minesweeping area displayed on the screen , If ‘*’ Equal to the number of thunder , It means that the minesweeping is successful .
notes : For each coordinate, its value will be determined by ‘*’ Change to the number of mines around it .
边栏推荐
- C语言大战“扫雷”
- CCF 2013 12-4 interesting numbers
- Verilog realizes binocular camera image data acquisition and Modelsim simulation, and finally matlab performs image display
- 数组部分方法
- Matlab实现均值滤波与FPGA进行对比,并采用modelsim波形仿真
- Linux Installation redis
- Do you know the functions of getbit and setbit in redis?
- Global case | how Capgemini connects global product teams through JIRA software and confluence
- 我们真的需要会议耳机吗?
- Elk log system practice (VI): comparison between vector and filebeat for technology selection
猜你喜欢

Squid agent

Cenos7 builds redis-3.2.9 and integrates jedis

Build the first power cloud platform

Review Servlet

This is probably the most comprehensive project about Twitter information crawler search on the Chinese Internet

Servlet

The artistic director and production designer of Disney's Mandalorian revealed the virtual scene production behind it

ThymeleafEngine模板引擎

Servlet

学好C语言从关键字开始
随机推荐
This point of arrow function
[reading this article is enough!!! Easy to understand] confidence level understanding (95% confidence level and confidence interval)
ThymeleafEngine模板引擎
Servlet
Markdown + typora + picgo experimental report template attached
Use com youth. banner. Solution to the inflateexception reported by the banner plug-in
All questions and answers of database SQL practice niuke.com
autojs,读取一行删除一行,停止自己外的脚本
[daily exercises] 1 Sum of two numbers
Invert an array with for
Free get | full function version of version control software
ERROR 1215 (HY000): Cannot add foreign key constraint
Data quality: the core of data governance
Chapter 1 of machine learning [series] linear regression model
Elk log system practice (VI): comparison between vector and filebeat for technology selection
What should the cross-border e-commerce evaluation team do?
我们真的需要会议耳机吗?
On the social moral and ethical issues behind short videos (personal point of view, for reference only)
11. Gesture recognition
[IOS development interview] operating system learning notes