[C Language][Game][Three Connects]

I. Introduction

The rule of the game is: two players play chess on a 3x3 board, as long as one player's three pieces are connected in a straight line, then he wins. If the chessboard is full and there is no winner, then it will be a draw. This blog will introduce the specific steps of how to realize the mini game of backgammon.

2. Modular programming

Modular programming: Put the code of each module in different .c files, and provide the declaration of external callable functions in the .h file. When other .c files want to use the code, you only need to #include "XXX.h "The file is fine. The use of modular programming can greatly improve the readability, maintainability, portability, etc. of the code.
Here I created three files: the game.h file is used to write the declaration of the custom function; the test_game.c file is used to write the definition; the test.c file is used to write the implementation of the entire program. (Here, you only need to #include "game.h" in the c file to connect the header file and the source file)
as follows:

insert image description here

3. The idea of ​​the game

1. Create a menu function to choose to enter the game and exit the game.
2. First, initialize the chessboard. (The game needs to store data during the game, you can use the 3*3 two-dimensional array char board[3][3];) 3. Then,
print the board.
4. Players play chess. (The player enters the position to make a move, 'x' = the player makes a move)
5. The computer makes a move to play chess. (Random position for placement, 'o' = computer placement)
6. How to judge the outcome! They are: player wins, computer wins, and draw. Continue if not finished. (The player wins and returns the character 'x', the computer wins and returns the character 'o', the tie returns the character 'p', and continues to return the character 'c')

4. Realize the game steps/process

1. Create a menu function to choose to enter the game and exit the game

1). Create a menu

void menu()

void menu()
{
    
    
    printf("*************************\n");
    printf("******  1.开始游戏  *****\n");
    printf("******  0.退出程序  *****\n");
    printf("*************************\n");

}

test:
insert image description here

2). Select "Enter Game" and "Exit Game"

#include "game.h"
void menu()
{
    
    
    printf("*************************\n");
    printf("******  1.开始游戏  *****\n");
    printf("******  0.退出程序  *****\n");
    printf("*************************\n");
}
int main()
{
    
    
    int x=0;
    do
    {
    
     
        menu();
        scanf("%d", &x);
        if (x == 1) {
    
    
            game();
            break;
        }
        else if (x == 0)
            break;
        else
            printf("笨蛋,输错了,请重新输入:\n");
    } while (1);
    printf("退出游戏\n");
}

The do while loop is used here because the player must judge whether to start the game at the beginning, and if the player makes a mistake, he needs to re-enter
the test:
insert image description here

2. Initialize the board

void InitBoard(char board[3][3], int row, int col)
{
    
    
     int i, j;
     for(i=0;i<row;i++)
         for (j = 0; j < col; j++)//初始化棋盘,数组里都是空格
         {
    
    
             board[i][j] = ' ';
         }
}

3. Print the chessboard

The chessboard that the player sees should consist of some separating lines and empty positions (two-dimensional array) where chess can be played. These lines are convenient for the player to see the ranks and columns of the board, and the two-dimensional array is used to store the chess pieces. It can be understood that the dividing line is a visual chessboard, and the two-dimensional array is the real chessboard (placing chess pieces). Find the rules and print them line by line from top to bottom.

void DisplayBoard(char board[][COL], int row, int col)//打印棋盘
{
    
    
    int i, j;
    for (i = 0; i < row; i++)//行数
    {
    
    
        for (j = 0; j < col; j++)//循环一次为"   |"
        {
    
    
                printf(" %c ", board[i][j]);
           if(j<col-1)
               printf("|");//少一列符号’|‘
        }
        printf("\n");
        if (i < row - 1)//为了打印两行“---|---|---”
        {
    
    
            for (j = 0; j < col; j++)
            {
    
    
                printf("---");
                if (j < col - 1)
                    printf("|");
            }
            printf("\n");
        }
    }
}

test:
insert image description here

4. Players play chess

First prompt the player to play chess, enter the number of rows and columns with spaces between them, and then print out the chessboard after the player has played the chess. Before, we assigned each element of this two-dimensional array as ' '. At this time, we only need to change the selected ' ' to a chess piece, and call the function of printing the chessboard written above again.

void PlayerMove(char board[][COL], int row, int col)//玩家下棋
{
    
    
    int x, y;
    printf("玩家下棋:\n");
     printf("请输入下棋的坐标,中间使用空格:\n");
    while (1)
    {
    
    
        scanf("%d %d", &x, &y);//坐标要合法
        if (x >=1 && x <= row && y>=1 && y <= row)
        {
    
    
            if (board[x - 1][y - 1] == ' ')//可以落子
            {
    
    
                board[x - 1][y - 1] = 'X';
                break;
            }
            else
                printf("坐标被占用,不能落子\n");    
        }
        else//坐标非法
            printf("笨蛋输错了,请重新输入:\n");
    }
}

test:
insert image description here

5. The computer plays chess

The computer plays chess similarly to the player, the computer plays chess directly without giving hints. The computer plays chess randomly, and random numbers need to be used here.

void ComputerBorad(char board[][COL], int row, int col)//电脑下棋
{
    
    
    int x, y;
    printf("电脑下棋:\n");
    Sleep(1500);//用来表示电脑思考了1.5秒
    while (1)
    {
    
    
        x = rand() % row;//电脑下棋对应的行坐标
        y = rand() % col;//电脑下棋对应的列坐标
        if (board[x][y] == ' ')
        {
    
    
            board[x][y] = 'O';
            break;
        }
    }
}

test:
insert image description here

6. The way to judge the outcome! They are: player wins, computer wins, and draw. Continue if not finished

1). The way to judge the outcome! They are: player wins, computer wins, and draw. (After playing chess, there will be four results in total: player wins, computer wins, draw and continue. When writing the function, corresponding to these four situations, return '*O', 'X', 'P', 'C' respectively. In each You should make a judgment every time you play chess. First judge whether you win or lose, and here you have to judge every possible result of winning! Only care about the draw if you don’t win, and continue if you don’t have a draw.)

char IsWin(char board[][COL], int row, int col)//判断输赢
{
    
    
    int i;
    //赢的情况下
    for (i = 0; i < row; i++)//行
    {
    
    
        if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != ' ')
            return board[i][0];
    }
    for (i = 0; i < col; i++)//列
    {
    
    
        if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[0][i] != ' ')
            return board[0][i];
    }
    //对角线
    if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != ' ')
        return board[1][1];
    if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] != ' ')
        return board[1][1];
}

judge whether a tie

int IsFull(char board[][COL], int row, int col)
{
    
    
    int i, j;
    for (i = 0; i < row; i++)
    {
    
    
        for (j = 0; j < col; j++)
        {
    
    
            if (board[i][j] == ' ')
               return 0;
        }
    }
    return 1;
}

5. Total code volume

1. The code of the test.c file

#include "game.h"
void menu()
{
    
    
    printf("*************************\n");
    printf("******  1.开始游戏  *****\n");
    printf("******  0.退出程序  *****\n");
    printf("*************************\n");
}
void game()
{
    
    
    char board[ROW][COL] = {
    
     0 };
    char a=0;
    InitBoard(board, ROW, COL);//初始化棋盘
    DisplayBoard(board, ROW, COL);//打印棋盘
    while (1)
    {
    
    
        PlayerMove(board, ROW, COL);//玩家下棋
        DisplayBoard(board, ROW, COL);//打印棋盘
        a=IsWin(board, ROW, COL);//判断输赢
        if (a != 'C')
         break;
        ComputerBorad(board, ROW, COL);//电脑下棋
        DisplayBoard(board, ROW, COL);//打印棋盘
        a = IsWin(board, ROW, COL);//判断输赢
        if (a != 'C')
            break;
    } 
    if (a == 'X')
        printf("玩家赢啦\n");
    else if (a == 'O')
        printf("电脑赢啦\n");
    else if(a=='P')
        printf("平局\n");
}
int main()
{
    
    
    srand((unsigned)time(NULL));
    int x=0;
    do
    {
    
     
        menu();//菜单
        scanf("%d", &x);
        if (x == 1)
        {
    
    
            game();//游戏
            break;
        }
        else if (x == 0)
            break;
        else
            printf("笨蛋,输错了,请重新输入:\n");
    } while (1);
    printf("退出游戏\n");
}

2. The code of the test_game.c file

#include "game.h"
void InitBoard(char board[3][3], int row, int col)//初始化棋盘
{
    
    
     int i, j;
     for(i=0;i<row;i++)
         for (j = 0; j < col; j++)
         {
    
    
             board[i][j] = ' ';
         }
}
void DisplayBoard(char board[][COL], int row, int col)//打印棋盘
{
    
    
    int i, j;
    for (i = 0; i < row; i++)//行数
    {
    
    
        for (j = 0; j < col; j++)//循环一次为"   |"
        {
    
    
                printf(" %c ", board[i][j]);
           if(j<col-1)
               printf("|");//少一列符号’|‘
        }
        printf("\n");
        if (i < row - 1)//为了打印两行“---|---|---”
        {
    
    
            for (j = 0; j < col; j++)
            {
    
    
                printf("---");
                if (j < col - 1)
                    printf("|");
            }
            printf("\n");
        }
    }
}
void PlayerMove(char board[][COL], int row, int col)//玩家下棋
{
    
    
    int x, y;
    printf("玩家下棋:\n");
    printf("请输入下棋的坐标,中间使用空格:\n");
    while (1)
    {
    
    
        scanf("%d %d", &x, &y);//坐标要合法
        if (x >=1 && x <= row && y>=1 && y <= row)
        {
    
    
            if (board[x - 1][y - 1] == ' ')//可以落子
            {
    
    
                board[x - 1][y - 1] = 'X';
                break;
            }
            else
                printf("坐标被占用,不能落子\n");    
        }
        else//坐标非法
            printf("笨蛋输错了,请重新输入:\n");
    }
}
void ComputerBorad(char board[][COL], int row, int col)//电脑下棋
{
    
    
    int x, y;
    printf("电脑下棋:\n");
    Sleep(1500);//1.5秒 
    while (1)
    {
    
    
        x = rand() % row;//电脑下棋对应的行坐标
        y = rand() % col;//电脑下棋对应的列坐标
        if (board[x][y] == ' ')
        {
    
    
            board[x][y] = 'O';
            break;
        }
    }
}
char IsWin(char board[][COL], int row, int col)//判断输赢
{
    
    
    int i;
    //赢的情况下
    for (i = 0; i < row; i++)//行
    {
    
    
        if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != ' ')
            return board[i][0];
    }
    for (i = 0; i < col; i++)//列
    {
    
    
        if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[0][i] != ' ')
            return board[0][i];
    }
    //对角线
    if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != ' ')
        return board[1][1];
    if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] != ' ')
        return board[1][1];
    //平局的情况下
    if (IsFull(board, row, col) == 1)
    {
    
    
        return 'P';
    }
    return 'C';
}
int IsFull(char board[][COL], int row, int col)
{
    
    
    int i, j;
    for (i = 0; i < row; i++)
    {
    
    
        for (j = 0; j < col; j++)
        {
    
    
            if (board[i][j] == ' ')
               return 0;
        }
    }
    return 1;
}

3. The code of the game.h file

#pragma once
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
#define ROW 3//棋盘的行数
#define COL 3//棋盘的列数
void InitBoard(char board[3][3], int row, int col);//初始化棋盘
void DisplayBoard(board, row, col);//打印棋盘
void PlayerMove(char board[][COL], int row, int col);//玩家下棋
void ComputerBorad(char board[][COL], int row, int col);//电脑下棋
char IsWin(char board[][COL], int row, int col);//判断输赢
int IsFull(char board[][COL], int row, int col);//平局的情况

Test:
The computer wins,
insert image description here
the player wins
insert image description here
. This is the first mini-game I have ever played. Write a blog to commemorate it.

Guess you like

Origin blog.csdn.net/plj521/article/details/131153896