C language to realize minesweeper game (code written by novice Xiaobai, remember to pay attention!)

Article directory

foreword

game design ideas

header file definition, function declaration

function definition

Statement of Game Rules

Arrangement of mines

game implementation function

Definition of main function and menu function

Summarize

foreword

The minesweeper game is a very classic small game, which can also exercise our thinking to a certain extent, stimulate our brain's thinking ability and creativity. So how do we implement a minesweeper game in C language? This time we will use some of the most basic C language grammar to implement the minesweeper game.

game design ideas

We will define two arrays, one array is used to store the information of the arranged mines, and the other array is used to store the information of the mines that have been checked out (used to interact with the player), by modifying the information of the second array to] To achieve the purpose of demining. When calculating the number of surrounding mines with a boundary of 1, the array will go out of bounds, so in order to prevent this phenomenon, we can leave an extra circle around it. For example, if we want to play 9✖9, then we define the array size of 11✖11.

header file definition, function declaration

Next, I will show all the functions used in minesweeper. For the convenience of calling, I put all the codes in a C language folder for implementation.

0  1  2  3  4  5  6  7  8  9  
1  *  *  *  *  *  *  *  *  *
2  *  *  *  *  *  *  *  *  *
3  *  *  *  *  *  *  *  *  *
4  *  *  *  *  *  *  *  *  *
5  *  *  *  *  *  *  *  *  *
6  *  *  *  *  *  *  *  *  *
7  *  *  *  *  *  *  *  *  *
8  *  *  *  *  *  *  *  *  *
9  *  *  *  *  *  *  *  *  *

code show as below:

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

//布局9*9方格
#define ROW 9
#define COL 9

//防止在计算边界为1的周围雷数时,数组越界,所以我们将数组扩大,防止数组越界。
#define ROWS    ROW + 2
#define COLS    COL + 2

#define MINE_COUNT 10//地雷个数



//游戏实现
void play();
//初始化界面布局
void InitBoard(char board[ROWS][COLS], int rows, int cols, char set);
//打印布局
void DisplayBoard(char board[ROWS][COLS], int rows, int cols);
//布置地雷
void SetMine(char board[ROWS][COLS], int row, int col);
//判断成功排除后剩下的方格数是否等于地雷数
int IsWin(char show[ROWS][COLS], int row, int col);
//使用递归函数来实现周围没地雷时展开多个
void spread(char mine[ROWS][COLS], char show[ROWS][COLS], int x, int y);
//计算周围地雷个数
int mine_count(char mine[ROWS][COLS], int x, int y); 
//扫雷
void FindMine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col);
//递归实现连续排除周围地雷
void spread(char mine[ROWS][COLS], char show[ROWS][COLS], int x, int y);


Function Definition
Game Rules

First of all, the function recursive method is used to realize the surrounding 8 squares, if there are no mines, it will be expanded at one time, and the ASC|| code value is used to calculate the number of surrounding 8 squares, and it will be displayed in digital form Come out the number of mines around.

Next, you can perform a simple demining operation, enter the coordinates for demining, until all the mines are cleared, you will pass the game, if the input coordinates are exactly the coordinates of the mines arranged. Then congratulations, you stepped on the mine, then the game will end, you can choose to continue playing or quit.

start

code show as below:

int IsWin(char show[ROWS][COLS], int row, int col)
{
    
    
    int num = 0;
    //排除一个地雷时便进行累加
    for (int i = 1; i <= row; i++)
    {
    
    
        for (int j = 1; j <= col; j++)
        {
    
    
            if (show[i][j] == '*')
                num++;
        }
    }
    return num;
}

void spread(char mine[ROWS][COLS], char show[ROWS][COLS], int x, int y)
{
    
    
    int count = mine_count(mine, x, y);//周围地雷的个数(此时是字符的ASCII码值)

    if (count == 0)
    {
    
    
        show[x][y] = ' ';
        int i = 0, j = 0;

        for (i = -1; i <= 1; i++)
        {
    
    
            for (j = -1; j <= 1; j++)
            {
    
    
                //连续排除时限制范围在棋盘范围内
                if ((x + i) > 0 && (y + i) > 0 && (x + i < ROWS) && (y + j < COLS) && show[x + i][y + j] == '*')
                {
    
            
                    spread(mine, show, x + i, y + j);//递归实现周围如果都没地雷连续排除
                }
            }
        }
    }
    else
    {
    
    
        show[x][y] = count + '0';//将字符ASCII码值转换为数字从而显示
    }
}

int mine_count(char mine[ROWS][COLS], int x, int y)
{
    
    
    //将周围八个方格中字符的ASCII码值之和减去八个‘0’的值得到周围地雷个数
    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, y = 0;

    while (1)
    {
    
    
        printf("请输入排雷坐标:>");
    loop:
        scanf("%d%d", &x, &y);
        if (x >= 1 && x <= row && y >= 1 && y <= col)//判断坐标是否合法
        {
    
    
            if (mine[x][y] == '1')//‘1’为地雷
            {
    
    
                printf("你已踩到雷,游戏结束\n");
                DisplayBoard(mine, ROW, COL);
                break;
            }
            else
            {
    
    
                spread(mine, show, x, y);//计算周围地雷数量,连续排除无雷的方格
                DisplayBoard(show, ROW, COL);
            }
        }
        else
        {
    
    
            printf("请输入正确的坐标:");
            goto loop;
        }
        int ret = IsWin(show, row, col);
        if (ret == MINE_COUNT)//当累加的地雷数量等于布置地雷的数量则说明地雷全部排除
        {
    
    
            printf("恭喜你,通关成功!\n");
            break;
        }
    }
}

game over

lay mines

Here, the rand() function is used to randomly arrange the corresponding mines in the case that there are no mines in the grid. The value of the grid with mines is 1, and the value of the grid without mines is 0. After the mines are arranged, use the print function to print the interface print it out.

In C language, we generally use the rand() function in the <stdlib.h> header file to generate random numbers.
But we can find by using it that the location where we generate mines is the same every time, which means that the random numbers generated by the rand() function are the same every time we use it.
In fact, the random numbers generated by the rand() function we use are all pseudo-random numbers. This data is actually calculated according to a certain formula. We usually call this value a "seed", but we can use srand() Function to redistribute random numbers, so that our random numbers can become different, and we can place mines randomly.

void srand(unsigned int seed);

But we need a parameter of unsinged int type. In actual code writing, we can use time as a parameter. As long as the time we sow seeds is different each time, the random numbers we generate will be different.

Then we can use the time() function in the <time.h> header file to get the current time
as follows:

srand((unsigned)time(NULL));

void SetMine(char board[ROWS][COLS], int row, int col)
{
    
    
    int count = MINE_COUNT;//布置地雷数量
    while (count)
    {
    
    
        //当该方格内没有地雷时随机布置相应数量地雷
        int x = rand() % row + 1;//(行,随机数范围1~9)
        int y = rand() % col + 1;//(列,随机数范围1~9)
        if (board[x][y] == '0')//判断没有地雷
        {
    
    
            board[x][y] = '1';//布置地雷
            count--;//直到布置完所有地雷
        }
    }
}

void DisplayBoard(char board[ROWS][COLS], int row, int col)
{
    
    
    int i = 0, j = 0;
    
    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]);//打印9*9方格内字符布局
        }
        printf("\n");
    }
    printf("\n");
}

void InitBoard(char board[ROWS][COLS], int rows, int cols, char set)
{
    
    
    int i = 0, j = 0;
    for (i = 0; i < rows; i++)
    {
    
    
        for (j = 0; j < cols; j++)
        {
    
    
            board[i][j] = set;//初始化所有方格内的字符
        }
    }
}

game implementation function

First of all, we need to initialize the game layout and print it out, then arrange the mines (that is, the function we want to implement above) and calculate the number of mines in the surrounding 8 squares, and mark the number of nearby mines, and finally we can start Minesweeper.

void SetMine(char board[ROWS][COLS], int row, int col)
{
    
    
    int count = MINE_COUNT;//布置地雷数量
    while (count)
    {
    
    
        //当该方格内没有地雷时随机布置相应数量地雷
        int x = rand() % row + 1;//(行,随机数范围1~9)
        int y = rand() % col + 1;//(列,随机数范围1~9)
        if (board[x][y] == '0')//判断没有地雷
        {
    
    
            board[x][y] = '1';//布置地雷
            count--;//直到布置完所有地雷
        }
    }
}

void DisplayBoard(char board[ROWS][COLS], int row, int col)
{
    
    
    int i = 0, j = 0;
    
    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]);//打印9*9方格内字符布局
        }
        printf("\n");
    }
    printf("\n");
}

void InitBoard(char board[ROWS][COLS], int rows, int cols, char set)
{
    
    
    int i = 0, j = 0;
    for (i = 0; i < rows; i++)
    {
    
    
        for (j = 0; j < cols; j++)
        {
    
    
            board[i][j] = set;//初始化所有方格内的字符
        }
    }
}

Main function definition and menu function
Here is a simple selection interface for playing the game, just like most games on the market, the minesweeper I wrote also has a menu selection function. Perform the corresponding action by selecting one of the options. Invoke the game or exit the game, and prompt for the correct option after entering an incorrect option.

int main()
{
    
    
    //菜单选择界面
    int input = 0, choose = 0;
    printf("&---------------------------&\n");
    printf("|        1、扫雷  Play          |\n");
    printf("|---------------------------|\n");
    printf("|        2、退出  Exit         |\n");
    printf("&---------------------------&\n");
    printf("请选择(1/2)>:");
    do
    {
    
    
        scanf("%d", &input);
        switch (input)
        {
    
    
        case 1:
            while (1)
            {
    
    
                printf("\n");
                play();
                printf("&---------------------------&\n");
                printf("|        1、继续  Continue  |\n");
                printf("|---------------------------|\n");
                printf("|        2、退出  Exit      |\n");
                printf("&---------------------------&\n");
                printf("请输入你的选择:");
            loop:
                scanf("%d", &choose);
                switch (choose)
                {
    
    
                case 1:
                    break;
                case 2:
                    return 0;
                default:
                    printf("请输入正确的选项:");
                    goto loop;
                }
            }
        case 2:
            printf("退出成功!\n");
            return 0;
        default:
            printf("请输入正确的选项:");
            break;
        }
    } while (input);

    return 0;
}

Summary
These are all the codes for the Minesweeper game. We used C language to complete this code. If you want to learn more, you can find explanations about the minesweeper game at station b. Although the interface and implementation of this minesweeper are very rough, this is also a small improvement for me. I also hope that friends who read this article will continue to work hard. keep growing!

Please add a picture description

Guess you like

Origin blog.csdn.net/z2004cx/article/details/128546650