Backgammon mini game (C language)

Introduction

Backgammon, I believe that many of you have played it when you were young. Draw two lines horizontally and vertically, ✔ or × in the 9 grids, and see whoever connects to a line first will win. Here, our opponent is a computer.
This little game combinesarray, loop statementThere are two main contents for programming. Coupled with sub-file programming, it can finally be formed.

general idea

The advantage of programming by file is that the program is concise, the division of labor is orderly, and it is convenient for debugging. Here, split into three files. respectively

game.h: header file, which encapsulates various functions together for easy calling
game.c: definition of game functions
test.c: test file, used to achieve the final effect

insert image description here

Then the most important thing is this game.c file. The idea is mainly: initialization, printing the chessboard, players playing chess, computer playing chess, judging winning or losing (including judging whether the chessboard is full), these five functions are written.

Initialize and print

Generally, we start with the main function. First, we need to give the player a menu and understand how to operate it, then just print it out.

void menu()
{
    
    
    printf("**********************\n");
    printf("********1.PLAY********\n");
    printf("********0.EXIT********\n");
    printf("**********************\n");
    printf("**********************\n");
}

Because the game is simple, we set it to be able to play this small game multiple times, and leave the game decision to the player. Then we use the do-while statement to package and add the switch package option.

int input = 0;
    do
    {
    
    
        menu();
        printf("请选择:");
        scanf("%d", &input);
        switch (input)
        {
    
    
        case 1:
            game();
            break;
        case 0:
            printf("已退出游戏。\n");
            break;
        default:
            printf("输入错误,请重新输入。\n");
            break;
        }
    } while (input);

When entering the game, we should initialize the board first, just use space characters for initialization.

void BoardInit(char board[ROW][COL], int row, int col)
{
    
    
    for (int i = 0; i < row; i++)
    {
    
    
        for (int j = 0; j < col; j++)
        {
    
    
            board[i][j] = ' ';
        }
    }
}

The next step is to print out the chessboard; as we said above, only drawing lines to divide it into 9 grids will give players a clear feeling. There are obviously three rows and three columns in three chess pieces, and there are only two dividing lines, horizontal and vertical, so we need to perform -1, and there is no need to draw extra lines. A two-dimensional plane can be printed out using two for loops.

void BoardPrint(char board[ROW][COL], int row, int col)
{
    
    
    for (int i = 0; i < row; i++)
    {
    
    
        //打印数据内容和竖列的分隔线
        for (int j = 0; j < col; j++)
        {
    
    
            printf(" %c ",board[i][j]);
            if (j < col - 1)
            {
    
    
                printf("|");
            }
        }
        //打完记得换行
        printf("\n");
        //打印横列的分隔线
        if (i < row - 1)
        {
    
    
            for (int j = 0; j < col; j++)
            {
    
    
                printf("---");
                if (j < col - 1)
                {
    
    
                    printf("|");
                }
            }
            printf("\n");
        }

    }
}

Effect:
insert image description here

player and computer playing chess

The next step is to start playing chess. Start with the player playing chess. In the eyes of the player, the subscript 0 corresponds to the coordinate 1, so when entering the coordinates, it is necessary to perform -1 operation on the player's input value. On the chessboard, we need to judge whether the player's input coordinate exceeds the range, and if it does not exceed the range, whether the coordinate is occupied. With these questions in mind, we can write code.

void PlayerMove(char board[ROW][COL], int row, int col)
{
    
    
    int x = 0, y = 0;
    printf("玩家下棋:\n");
    while (1)
    {
    
    
        printf("请输入下棋位置坐标,用空格隔开");
        scanf("%d %d", &x, &y);
        //在棋盘范围内
        if (x >= 1 && x <= row && y >= 1 && y <= col)
        {
    
    
            if (board[x-1][y-1] == ' ')
            {
    
    
                board[x-1][y-1] = '*';
                break;

            }
            else
            {
    
    
                printf("当前位置已有,请重新输入。\n");
            }
        }
        else//棋盘范围外
        {
    
    
            printf("超出输入范围,请重新输入。\n");
        }
    }
    
}

To play chess with a computer, we need to know how to let the computer play chess automatically. Here, we use random numbers to play chess randomly, just take the modulo of the random numbers. Then judge whether it is empty.

//Random number seed
srand((unsigned int)time(NULL));

void ComputerMove(char board[ROW][COL], int row, int col)
{
    
    
    int x=0, y=0;
    printf("电脑下棋:\n");
    while (1)
    {
    
    
    //rand()代表随机数
        x = rand() % row;
        y = rand() % col;
        if (board[x][y] == ' ')
        {
    
    
            board[x][y] = '#';
            break;
        }
    }
   
}

Determine whether it is connected to a line

We all know that there are generally three types of connecting lines, horizontal, vertical, and oblique. We only need to count the number of identical characters in the row or column and diagonal.

char IsWin(char board[ROW][COL], int row, int col)
{
    
    
    //行项
    for (int i = 0; i < row; i++)
    {
    
    
        //Ni记录人,电脑,空
        char NI = board[i][0];
        //num记录相同的
        int num = 0;
        if (NI != ' ')
        {
    
    
            num = 1;
        }
        for (int j = 1; j < col; j++)
        {
    
    
            if (NI != ' '&&board[i][j]==NI)
            {
    
    
                num++;
            }
            if (num == row)
            {
    
    
                return NI;
            }
        }
    }
    //列项
    for (int i = 0; i < col; i++)
    {
    
    
        //Ni记录人,机,空
        char NI = board[0][i];
        //num记录相同的
        int num = 0;
        if (NI != ' ')
        {
    
    
            num = 1;
        }
        for (int j = 1; j < row; j++)
        {
    
    
            if (NI != ' ' && board[j][i] == NI)
            {
    
    
                num++;
            }
            if (num == row)
            {
    
    
                return NI;
            }
        }
        
    }
    //正对角线
    char NI1 = board[0][0];
    int num1 = 0;
    if (NI1 != ' ')
    {
    
    
        num1 = 1;
    }
    for (int i = 1; i < row; i++)
    {
    
    
       
        
        if (NI1 != ' ' && board[i][i] == NI1)
        {
    
    
            num1++;
        }
        if (num1 == row)
        {
    
    
            return NI1;
        }
    }
    //反对角线
    char NI2 = board[0][row - 1];
    int num2 = 0;
    if (NI2 != ' ')
    {
    
    
        num2 = 1;
    }
    for (int i = 1,j=1; i < row,j<col; i++,j++)
    {
    
    
            if (NI2 != ' ' && board[i][row - 1 - j]==NI2)
            {
    
    
                num2++;
            }
            if (num2 == row)
            {
    
    
                return NI2;
            }
        
    }
    //平局
    if (IsFull(board, row, col) == 1)
    {
    
    
        return 'Q';
    }
    //继续
    return 'C';
}

Here, we judge winning or losing based on the form of the return value.
insert image description here
When the board is full, it is a draw.

final package

After entering the game, we enter the game() function. We first define a two-dimensional array, initialize it, print it, and then the player and the computer play chess. When playing chess, we use a loop to play chess multiple times, and Judgment can be made according to the above return value.
Here, we use macro definitions to define the number of rows and columns.
insert image description here
In this way, we only need to modify the values ​​of these two macro variables to change the size of the chessboard.

original code

//test.c
#include"game.h"

void menu()
{
    
    
    printf("**********************\n");
    printf("********1.PLAY********\n");
    printf("********0.EXIT********\n");
    printf("**********************\n");
    printf("**********************\n");
}
void game()
{
    
    
    char board[ROW][COL] = {
    
     0 };
    //初始化
    BoardInit(board, ROW, COL);
    //打印
    BoardPrint(board, ROW, COL);
    //开始下棋
    char ret = 0;
    while (1)
    {
    
    
        //人
        PlayerMove(board, ROW, COL);
        BoardPrint(board, ROW, COL);
        //进行判断输赢
        ret = IsWin(board, ROW, COL);
        //非继续就退出循环
        if (ret != 'C')
        {
    
    
            break;
        }
        //电脑
        ComputerMove(board, ROW, COL);
        BoardPrint(board, ROW, COL);
        //判断
        ret = IsWin(board, ROW, COL);
        if (ret != 'C')
        {
    
    
            break;
        }
    }
    if (ret == '*')
    {
    
    
        printf("你赢了。\n");
    }
    else if (ret == '#')
    {
    
    
        printf("电脑赢了。\n");
    }
    else
    {
    
    
        printf("平局。\n");
    }
    

}

int main()
{
    
    
    //随机种子
    srand((unsigned int)time(NULL));
    int input = 0;
    do
    {
    
    
        menu();
        printf("请选择:");
        scanf("%d", &input);
        switch (input)
        {
    
    
        case 1:
            game();
            break;
        case 0:
            printf("已退出游戏。\n");
            break;
        default:
            printf("输入错误,请重新输入。\n");
            break;
        }
    } while (input);
    return 0;
}
//game.h
#pragma once//防止头文件重复包含
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
//行数和列数,可改变
#define ROW 3
#define COL 3


//初始化
void BoardInit(char board[ROW][COL], int row, int col);
//打印棋盘
void BoardPrint(char board[ROW][COL], int row, int col);
//玩家下棋
void PlayerMove(char board[ROW][COL], int row, int col);
//电脑下棋
void ComputerMove(char board[ROW][COL], int row, int col);
//判断
char IsWin(char board[ROW][COL], int row, int col);
//game.c
#include"game.h"
//初始化
void BoardInit(char board[ROW][COL], int row, int col)
{
    
    
    for (int i = 0; i < row; i++)
    {
    
    
        for (int j = 0; j < col; j++)
        {
    
    
            board[i][j] = ' ';
        }
    }
}
//打印
void BoardPrint(char board[ROW][COL], int row, int col)
{
    
    
    for (int i = 0; i < row; i++)
    {
    
    
        //打印数据内容和竖列的分隔线
        for (int j = 0; j < col; j++)
        {
    
    
            printf(" %c ",board[i][j]);
            if (j < col - 1)
            {
    
    
                printf("|");
            }
        }
        //打完记得换行
        printf("\n");
        //打印横列的分隔线
        if (i < row - 1)
        {
    
    
            for (int j = 0; j < col; j++)
            {
    
    
                printf("---");
                if (j < col - 1)
                {
    
    
                    printf("|");
                }
            }
            printf("\n");
        }

    }
}
//玩家下棋
void PlayerMove(char board[ROW][COL], int row, int col)
{
    
    
    int x = 0, y = 0;
    printf("玩家下棋:\n");
    while (1)
    {
    
    
        printf("请输入下棋位置坐标,用空格隔开");
        scanf("%d %d", &x, &y);
        //在棋盘范围内
        if (x >= 1 && x <= row && y >= 1 && y <= col)
        {
    
    
            if (board[x-1][y-1] == ' ')
            {
    
    
                board[x-1][y-1] = '*';
                break;

            }
            else
            {
    
    
                printf("当前位置已有,请重新输入。\n");
            }
        }
        else//棋盘范围外
        {
    
    
            printf("超出输入范围,请重新输入。\n");
        }
    }
    
}
//电脑下棋
void ComputerMove(char board[ROW][COL], int row, int col)
{
    
    
    int x=0, y=0;
    printf("电脑下棋:\n");
    while (1)
    {
    
    
        x = rand() % row;
        y = rand() % col;
        if (board[x][y] == ' ')
        {
    
    
            board[x][y] = '#';
            break;
        }
    }
   
}

//判断棋盘是否已经满了
int IsFull(char board[ROW][COL], int row, int col)
{
    
    
    for (int i = 0; i < row; i++)
    {
    
    
        for (int j = 0; j < col; j++)
        {
    
    
            if (board[i][j] == ' ')
            {
    
    
                return 0;
            }
        }
    }
    return 1;
}
//判断是否赢了
char IsWin(char board[ROW][COL], int row, int col)
{
    
    
    //行项
    for (int i = 0; i < row; i++)
    {
    
    
        //Ni记录人,机,空
        char NI = board[i][0];
        //num记录相同的
        int num = 0;
        if (NI != ' ')
        {
    
    
            num = 1;
        }
        for (int j = 1; j < col; j++)
        {
    
    
            if (NI != ' '&&board[i][j]==NI)
            {
    
    
                num++;
            }
            if (num == row)
            {
    
    
                return NI;
            }
        }
    }
    //列项
    for (int i = 0; i < col; i++)
    {
    
    
        //Ni记录人,机,空
        char NI = board[0][i];
        //num记录相同的
        int num = 0;
        if (NI != ' ')
        {
    
    
            num = 1;
        }
        for (int j = 1; j < row; j++)
        {
    
    
            if (NI != ' ' && board[j][i] == NI)
            {
    
    
                num++;
            }
            if (num == row)
            {
    
    
                return NI;
            }
        }
        
    }
    //正对角线
    char NI1 = board[0][0];
    int num1 = 0;
    if (NI1 != ' ')
    {
    
    
        num1 = 1;
    }
    for (int i = 1; i < row; i++)
    {
    
    
       
        
        if (NI1 != ' ' && board[i][i] == NI1)
        {
    
    
            num1++;
        }
        if (num1 == row)
        {
    
    
            return NI1;
        }
    }
    //反对角线
    char NI2 = board[0][row - 1];
    int num2 = 0;
    if (NI2 != ' ')
    {
    
    
        num2 = 1;
    }
    for (int i = 1,j=1; i < row,j<col; i++,j++)
    {
    
    
            if (NI2 != ' ' && board[i][row - 1 - j]==NI2)
            {
    
    
                num2++;
            }
            if (num2 == row)
            {
    
    
                return NI2;
            }
        
    }
    //平局
    if (IsFull(board, row, col) == 1)
    {
    
    
        return 'Q';
    }
    //继续
    return 'C';
}

Guess you like

Origin blog.csdn.net/m0_74068921/article/details/130549135