当前位置:网站首页>[c language] - step by step to achieve minesweeping games
[c language] - step by step to achieve minesweeping games
2022-07-28 06:45:00 【HandsomeDog_ L】
Catalog
Give my mind map when writing this code , This blog is also based on mind mapping
Come to the point
Give my mind map when writing this code , This blog is also based on mind mapping

Game result display
// Because I have some dishes , So set up 4*4 -->4 Specifications , namely 16 Check out 4 Thunder to demonstrate the game code , If you want to challenge a small partner with high difficulty, you can set it by yourself . Then I'll laugh


Game thinking analysis
First show the header file and source file used in this code writing , Convenient for follow-up reading
| test.c | It is used to test the relevant functions of the minesweeping code written, that is game.c Call the function in |
| game.h | It is used to declare the main functions and parameters involved in the mine sweeping code |
| game.c | The body of the code , Yes game.h Define the function declared in |
And sanziqi ( See previous article ) equally , There should be one menu , You can set it as beautiful as you think ----test.c
void menu()
{
printf("****************************\n");
printf("************ Mine clearance ************\n");
printf("********** 1. play *********\n");
printf("********** 0. exit *********\n");
printf("****************************\n");
}
Originally menu() Should belong to game.c But because of menu() It's simple , There is no need to talk with game.c Big head in " Compete for favor " 了
Arrange thunder
Let's look at a picture


Two questions 1. Where should ray put it ?2. What should ray say ?
answer :1. Ray should be put into a character array , Might as well set up boom[ROWS][COLS]
2. Lei Yong '1' Express , Non mine use '0' Express , Notice the '1' and '0' Is the character 1 and 0. Why choose to use '1' and '0'? The summary at the end of the article will be given in detail
ps: there ROWS and COLS Corresponding to the 11 That's ok 11 Column , namely Orange Box . Some friends will ask if my chessboard is 9*9 Well. , Set to 11*11 Isn't it a waste of space ! But it is not , This setting can Avoid array out of bounds The problem of . Why are you say that? ?
Let's look at the above Green box , Its function is to check (x,y) Characters surrounded by eight squares 1( Thunder ) The number of , screening (8,8) Of course, there will be no array out of bounds , If I go to check (1,1) (1,2)...(9,9) That is, the outermost one 32 Lattice , What happens ? Green box Will visit not belong to Red box The content of ,( An inappropriate metaphor : You went to get something that shouldn't belong to you ) Of course it can't . The computer will tell you mercilessly error. So , We should set it to 11*11 Of , The elements in the outermost circle can be omitted , But not without ! We only operate the middle 9*9 That's it .
Check the thunder
Like the green box above , We checked (8,8), There is 3 A thunder , What should I do when the investigation comes out ? Should I put this "3" Save it . How to save it? ? Of course, array is also used .
At this time, a small partner is eager to try :int show[ROWS][COLS], Created an integer array ;
Then I can only say : You wave , Still on the first floor . And look down
I'm going to use char show[ROWS][COLS], An array of character types . Why do we do this ? Let's sell it first , The reason will be given in the function definition section .
ok, The above is our thinking analysis , The real big head is coming
The idea is programmed
The first step, of course, is to write our test.c 了
// Game test module
#define _CRT_SECURE_NO_WARNINGS 1
#include "game.h"
void menu()
{
printf("****************************\n");
printf("************ Mine clearance ************\n");
printf("********** 1. play *********\n");
printf("********** 0. exit *********\n");
printf("****************************\n");
}
void game()
{
// Information storage about mines
//1. Create an array to store Lei
char boom[ROWS][COLS] = { 0 };
//2. Create an array to display the detected mines
char show[ROWS][COLS] = { 0 };
// Initialize two arrays
InitBoard(boom, ROWS, COLS, '0');
InitBoard(show, ROWS, COLS, '*');
// Print chessboard
//DisplayBoard(boom, ROW, COL);
DisplayBoard(show, ROW, COL);//
// Arrange thunder
Setboom(boom, ROW, COL);
//DisplayBoard(boom, ROW, COL);
// Mine clearance
Findboom(boom, show, ROW, COL);
}
void test()
{
int choice = 0;
srand((unsigned int)time(NULL));// Time stamp
do
{
menu();
printf(" Please select :>");
scanf("%d", &choice);
switch (choice)
{
case 1:
game();
break;
case 0:
printf(" Quit the game \n");
break;
default:
printf(" Wrong choice , To choose !\n");
break;
}
} while (choice);
}
int main()
{
test();
return 0;
}
It can be found that it is not very concise and simple
main() Called test(),test() Called menu() If input 1,test() Call again game(),game() Also called a series of functions . Then we can play the minesweeping game .
Careful friends will find a #include "game.h" This is actually a form of header file name , It's just that we define this by ourselves , Unlike #include<stdio.h> #include<math.h> These are vs Self contained . You just need to remember : If you want to quote the header file defined by yourself, add " "
Function to " Declare before use "
Let's see game.h What's in it
1 // Module declaration
2 // Global definition of some data , Convenient for subsequent modification
3
4
5
6 #define ROW 9
7 #define COL 9
8
9 #define ROWS ROW+2
10 #define COLS COL+2
11 // The number of mines
12 #define BOOM_COUNT 10
13
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <time.h>
17 // Function return type Function name Function parameter
18 void InitBoard(char board[ROWS][COLS], int rows, int cols, char set);
19 void DisplayBoard(char board[ROWS][COLS], int row, int col);
20 void Setboom(char board[ROWS][COLS], int row, int col);
21 void Findboom(char boom[ROWS][COLS], char show[ROWS][COLS], int row, int col);
18-21 OK, these functions are game() Repeatedly called , The declaration already exists , It's not clear yet , We define them as game.c Inside
Let's talk about each of them
InitBoard()
Initialize the array to what you want InitBoard() Return type viod Parameters One char Type array , Two integer numbers , The number of a character Do you still remember the key sold above , I put show[][] Also defined as char type , Now let me tell you the answer , I put show[][] Defined as and boom[][] Same char type , Just for , Give Way InitBoard() One function operates on two arrays , Make the code simpler , It avoids my need to initialize show[][] To redefine another function Below DisplayBoard() The same is true
|
DisplayBoard()
Print array contents
void DisplayBoard(char board[ROWS][COLS], int row, int col) { int i = 0; int j = 0; // Print column number for (i = 0; i <= col; i++) { printf("%d ", i); } printf("\n"); for (i = 0; i <= col; i++) { printf("--"); } printf("\n"); // Print line number for (i = 1; i <= row; i++) { printf("%d", i); printf("|");// Then print the contents of the array for (j = 1; j <= col; j++) { printf("%c ", board[i][j]); } printf("\n"); } } |
Setboom()
Arrange thunder -> hold boom[][] Replace the corresponding coordinates in with characters 1 '1'
Randomly set the location of the mine
void Setboom(char board[ROWS][COLS], int row, int col) { int count = BOOM_COUNT; while (count) { int x = rand() % row + 1;// Give Way x The scope is 1-9 int y = rand() % col + 1;// Give Way y The scope is 1-9 if (board[x][y] == '0') { board[x][y] = '1'; count--; } } } |
Findboom()
find boom[x][y] Surrounding characters 1 '1' And put the '1' The number of is saved to show[x][y]
// Go to the one around the coordinate we want to check 8 The number of mines in a grid int get_boom_count(char boom[ROWS][COLS], int x, int y) {
return boom[x - 1][y] + boom[x - 1][y - 1] + boom[x][y - 1] + boom[x + 1][y - 1] + boom[x + 1][y] + boom[x + 1][y + 1] + boom[x][y + 1] + boom[x - 1][y + 1] - 8 * '0'; } void Findboom(char boom[ROWS][COLS], char show[ROWS][COLS], int row, int col)// Two arrays , Same coordinates , One represents thunder , One represents the number of mines around the coordinates { int x = 0; int y = 0; int rest_blank = 0;// use To express The rest is not the number of Ray's lattice
while (rest_blank < row * col - BOOM_COUNT) { printf(" Please enter the coordinates to be checked :>"); scanf("%d%d", &x, &y); // It's time to judge the legitimacy of coordinates , That is, the coordinates to be checked should be 9*9 The range of the grid if (x >= 1 && x <= row && y >= 1 && y <= col) { // Coordinates are legal //1. yes Thunder if (boom[x][y] == '1') { printf(" unfortunately , You're killed in the blast \n"); // At least let players " Die clear " DisplayBoard(boom, row, col);// Show me the distribution of thunder break; } else //2. It's not ray { // Calculation x,y There are several mines around the coordinates int count = get_boom_count(boom, x, y); // Save the number of mines found in show In the array show[x][y] = count + '0';// An integer is converted to the corresponding character plus '0' Such as 3+'0'=='3' DisplayBoard(show, row, col); // Find a ray rest_blank It's self increasing rest_blank++; } } else { printf(" It's illegal to enter coordinates , Please re-enter !\n"); } } // Judge Is it equal to the number of all non thunder lattices if (rest_blank == row * col - BOOM_COUNT) { printf(" congratulations , Mine clearance is successful \n"); DisplayBoard(boom, row, col); } } |
Finally, let's take a look at game.c The content of is actually the summary of the above functions
// Function definition module
#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;
// Print column number
for (i = 0; i <= col; i++)
{
printf("%d ", i);
}
printf("\n");
for (i = 0; i <= col; i++)
{
printf("--");
}
printf("\n");
// Print line number
for (i = 1; i <= row; i++)
{
printf("%d", i);
printf("|");// Then print the contents of the array
for (j = 1; j <= col; j++)
{
printf("%c ", board[i][j]);
}
printf("\n");
}
}
void Setboom(char board[ROWS][COLS], int row, int col)
{
int count = BOOM_COUNT;
while (count)
{
int x = rand() % row + 1;// Give Way x The scope is 1-9
int y = rand() % col + 1;// Give Way y The scope is 1-9
if (board[x][y] == '0')
{
board[x][y] = '1';
count--;
}
}
}
// Go to find the one around the coordinate we want to see 8 The number of mines in a grid
int get_boom_count(char boom[ROWS][COLS], int x, int y)
{
return boom[x - 1][y] +
boom[x - 1][y - 1] +
boom[x][y - 1] +
boom[x + 1][y - 1] +
boom[x + 1][y] +
boom[x + 1][y + 1] +
boom[x][y + 1] +
boom[x - 1][y + 1] - 8 * '0';
}
//
void Findboom(char boom[ROWS][COLS], char show[ROWS][COLS], int row, int col)// Two arrays , Same coordinates , One represents thunder , One represents the number of mines around the coordinates
{
int x = 0;
int y = 0;
int rest_blank = 0;// Used to indicate the number of remaining non ray lattices
while (rest_blank < row * col - BOOM_COUNT)
{
printf(" Please enter the coordinates to be checked :>");
scanf("%d%d", &x, &y);
// It's time to judge the legitimacy of coordinates , That is, the coordinates to be checked should be 9*9 The range of the grid
if (x >= 1 && x <= row && y >= 1 && y <= col)
{
// Coordinates are legal
//1. It's ray
if (boom[x][y] == '1')
{
printf(" unfortunately , You're killed in the blast \n");
// At least let players " Die clear "
DisplayBoard(boom, row, col);// Show me the distribution of thunder
break;
}
else //2. It's not ray
{
// Calculation x,y There are several mines around the coordinates
int count = get_boom_count(boom, x, y);
// Save the number of mines found in show In the array
show[x][y] = count + '0';
DisplayBoard(show, row, col);
// Find a ray rest_blank It's self increasing
rest_blank++;
}
}
else
{
printf(" It's illegal to enter coordinates , Please re-enter !\n");
}
}
// Judge whether it is equal to the number of all non mine lattices
if (rest_blank == row * col - BOOM_COUNT)
{
printf(" congratulations , Mine clearance is successful \n");
DisplayBoard(boom, row, col);
}
}ok, This is the end of the big part
Summarize the notes
#define _CRT_SECURE_NO_WARNINGS 1
This is actually to make the compiler compile scanf No error is reported when , Because some compilers ( For example, my own VS2019) Will think scanf unsafe , I suggest you use scanf_s. But I don't listen to its advice , I will use it scanf, Just add the above sentence in front of the code
About the setting of Lei
Make full use of the attributes of numbers , '1' It means ray , 2 It means that there are 2 A thunder This is real 2,
'2' It can be printed out as an array element , Let's think visually that there are two mines around , This is a character '2', But it has the attribute of numbers .
It may be a little winding , Ha ha ha , But it should be understood
About the setting of array type
In fact, I didn't expect to put show[][] Set to char type , I am writing InitBoard() When , All of a sudden . I'll initialize two arrays , Can you use a function , But a function can only initialize an array of one type , And the initialization object and initialization content must be of the same type ( I don't want to force type conversion ow )
initialization char Type of boom[][] by '0' ( There should be no thunder at the beginning ) Want a function
Initial remarks int Type of show[][] by '*' ( At first, what we should see is *, Cover the location of thunder , I won't let you see , hum ) It's a little impractical
So just put show[][] Also defined as char type , thus , The array type and the type of initialization content are unified .
and DiaplayBoard() You don't have to worry about the type
Deficiencies in the game
1. Around the number 8 When it's a grid ,get_boom_count() You can use circulation , Why don't I use it , Because it's intuitive , Friends are easier to understand
2. While checking out ray , Can't unfold . Interested partners can use recursion
screening boom[x][y] Around 8 Lattice --> 1. It's ray , Just count and save to show[x][y] 2. It's not ray , Check the eight grids around it
Until the outer circle is full of thunder ( In fact, I don't know much about the rules of the game of minesweeping ). In order to avoid repeated screening of some grids , You can define an array specifically to indicate whether a grid has been checked . The array is initialized to 0, Once checked , The corresponding coordinates are assigned 1.
3. Use recursion to find Fibonacci sequence , Embodies the above ideas , You can read another blog I wrote ( It's a wave of small advertisements ) Fibonacci sequence is art _HandsomeDog_L The blog of -CSDN Blog
Small tips
It is suggested that small partners have a clear idea when writing this type of code , How can we do it ------- Mind mapping
Except for the big guys
The three piece chess written in the last article also has a mind map , Forgot to post it , Let me put it in the comments section of sanziqi , Interested partners can go to see
Because the editor's level is really Limited , Please correct any mistakes , Thank you very much for your feedback
This article is about 10000 words ,( Mostly code ), Take a rest after reading your eyes , See you later !
边栏推荐
猜你喜欢

Leetcode 刷题日记 剑指 Offer II 053. 二叉搜索树中的中序后继

Explain in detail
![[PTA----输出全排列]](/img/66/d1699cd55fa5ff4a55e3e150d02c1b.png)
[PTA----输出全排列]

Problem solving for ACM freshmen in Jiangzhong on October 26

【动态规划--买卖股票的最佳时期系列】

Project compilation nosuch*** error problem

关于Shader KeyWord的整理

结构体、位段、联合体(共用体)的大小如何计算

What's a good gift for your girlfriend on the Chinese Valentine's day in 2022? Practical and beautiful gift recommendation
![[哈希表基础知识]](/img/8f/54a4780a02f81e5de3d92c25248e1e.png)
[哈希表基础知识]
随机推荐
刷题记录----反转链表(反转整个链表)
图形管线基础(一)
Development of Quantitative Trading Robot System
刷题记录----二叉树
Leetcode 刷题日记 剑指 Offer II 048. 序列化与反序列化二叉树
RayMarching realizes volume light rendering
Mongodb replica set and partitioned cluster
Leetcode brush question diary sword finger offer II 048. serialization and deserialization binary tree
Battle plague Cup -- my account book
About the collation of shader keyword
NiO example
NIO示例
mongoDB快速入门
[hash table basics]
OJ 1089 Spring Festival travel
二维数组实战:螺旋矩阵
项目编译NoSuch***Error问题
[dynamic planning -- the best period for buying and selling stocks Series 2]
OJ 1020 minimum palindromes
explain详解