When playing with roommates, the time of King glory, use c language to realize a three piece chess game (detailed explanation)

Posted by neo777ph on Thu, 10 Mar 2022 16:56:09 +0100

 

catalogue

🍑 What is Sanzi

🍑 create a file

🍑 Game menu

🍑 Post selection

🍑 Create a game function

🍎 Create a chessboard

         🍎 Chess player

         🍎 Computer chess

         🍎 Judge whether the chessboard is full

         🍎 Judge whether to win or lose

🍑 What is Sanzi

Sanzi is a kind of black and white chess. Sanzi chess is a traditional folk game, also known as Jiugong chess, circle fork, one dragon, Jingzi chess and so on. Connect the diagonals of the square and put three pieces on the opposite sides in turn. As long as you walk your three pieces into a line, the other party will lose. Knowing these principles, we can try to write Sanzi chess in C language.

🍑 create a file

When we begin to write code, we should first introduce the concept of multiple files, that is, modular programming. It means encapsulating functions with different functions into different files. In this Gobang game, we want to create a game H header file, and main C and game C source file. We should not underestimate the concept of multiple files. The concept of multiple files can not only make the code more orderly, but also make it more convenient for us to maintain in the future. Therefore, learning to create multiple files and use them reasonably is a skill that every programmer must learn

🍑 Game menu

Friends who have played the game know that there must be a page for us to choose at the beginning of the game. We can choose to start the game or exit the game when we don't want to play, so we first need to set a menu.

void menu()
{
    printf("********************************\n");
    printf("*********  1. play     *********\n");
    printf("*********  0. exit     *********\n");
    printf("********************************\n");
}

🍑 Situation after selection

When we enter the choice, we will face three situations. If we choose 1 to start the game and 2 to exit the game, when we choose the wrong choice, we should inform the user that the choice is wrong! Here we use do while loop and switch statement to realize this function.

void test()
{
    int input = 0;
    do
    {
        menu();
        printf("Please select:>");
        scanf("%d", &input);
        switch (input)
        {
        case 1:
            game();//game
            break;
        case 0:
            printf("Exit the game\n");
            break;
        default:
            printf("Selection error\n");
            break;
        }
    } while (input);
}

🍑 Create a game function

void game()
{
    char ret = 0;
    //Store chess data
    char board[ROW][COL] = {0};
    //Initialize the chessboard to full space
    InitBoard(board, ROW, COL);
    //Print chessboard
    DisplayBoard(board, ROW, COL);
    while (1)
    {
        //Players play chess
        player_move(board, ROW, COL);
        DisplayBoard(board, ROW, COL);
        //Judge whether to win or lose
        ret = is_win(board, ROW, COL);
        if (ret != 'C')
        {
            break;
        }
        //Computer chess
        computer_move(board, ROW, COL);//Play chess at random
        DisplayBoard(board, ROW, COL);
        ret = is_win(board, ROW, COL);
        if (ret != 'C')
        {
            break;
        }
    }
    if (ret == '*')
    {
        printf("The player won\n");
    }
    else if (ret == '#')
    {
        printf("The computer won\n");
    }
    else
    {
        printf("it ends in a draw\n");
    }
    //DisplayBoard(board, ROW, COL);
}

//
//In any case, the game is over
//Player wins - '*'
//Computer wins - '#'
//Draw - 'Q'
//Continue - 'C'

We need to prepare a game C file to store our Sanzi code, and began to write our code about the game.

🍎 Create a chessboard

We first create a two-dimensional array to store the information we input into the chessboard, and initialize our chessboard so that the value of the array is equal to the space

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

After creating the binary array, we need to print out the boundary of the chessboard, so as to bring a better impression to the user. We can use "|" and "-" - "to print the boundary of the chessboard

 

void DisplayBoard(char board[ROW][COL], int row, int col)
{
    int i = 0;
    for (i = 0; i < row; i++)
    {
        //print data
        int j = 0;
        for (j = 0; j < col; j++)
        {
            printf(" %c ", board[i][j]);
            if(j<col-1)
                printf("|");
        }
        printf("\n");
        //Print split lines
        if (i < row - 1)
        {
            for (j = 0; j < col; j++)
            {
                printf("---");
                if (j < col - 1)
                    printf("|");
            }
            printf("\n");
        }
    }
}

🍎 Players play chess

Next, we need to write code so that users can input coordinates to play chess. It is worth mentioning that we do not consider 0 points in our daily input coordinates, so we need to reduce the input x and y by 1.

void player_move(char board[ROW][COL], int row, int col)
{
    int x = 0;
    int y = 0;
    printf("Players play chess\n");
    while (1)
    {
        printf("Please enter coordinates:>");
        scanf("%d %d", &x, &y);
        if (x >= 1 && x <= row && y >= 1 && y <= col)
        {
            //play chess
            if (board[x - 1][y - 1] == ' ')
            {
                board[x - 1][y - 1] = '*';
                break;
            }
            else
            {
                printf("This coordinate is occupied, please re-enter\n");
            }
        }
        else
        {
            printf("Illegal coordinates, please re-enter\n");
        }
    }

🍎 Computer chess

Before writing this code, we should first learn the reference of time stamp, because the code we write should make the computer generate a random value and use the time stamp to return a random number to the computer. Using the rand function requires the header file #include < stdlib h> , the rand function will get a random number from 1 to 9. If this random number goes to% row or col, it will produce a random number from 0 to 2.

srand((unsigned int)time(NULL));
void computer_move(char board[ROW][COL], int row, int col)
{
    int x = 0;
    int y = 0;
    printf("Computer chess:>\n");
    while (1)
    {
        x = rand() % row;//0~2
        y = rand() % col;//0~2
        if (board[x][y] == ' ')
        {
            board[x][y] = '#';
            break;
        }
    }
}

🍎 Judge whether the chessboard is full

static int if_full(char board[ROW][COL], int row, int col)
{
    int i = 0;
    for (i = 0; i < row; i++)
    {
        int j = 0;
        for (j = 0; j < col; j++)
        {
            if (board[i][j] == ' ')
            {
                return 0;//Not full
            }
        }
    }
    return 1;//Full
}

🍎 Judge whether to win or lose

We need to judge who wins first from the three directions of row, column and diagonal

 

char is_win(char board[ROW][COL], int row, int col)
{
    int i = 0;
    //Judgment line
    for (i = 0; i < row; i++)
    {
        if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][1] != ' ')
        {
            return board[i][1];
        }
    }
    //Judgment column
    for (i = 0; i < col; i++)
    {
        if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[1][i] != ' ')
        {
            return board[1][i];
        }
    }
    //diagonal
    if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[1][1] != ' ')
    {
        return board[1][1];
    }
    if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[1][1] != ' ')
    {
        return board[1][1];
    }

    //Judge the draw
    if (if_full(board, row, col) == 1)
    {
        return 'Q';
    }
    
    //continue
    return 'C';
}

Integrate these codes together and write a small sanziqi game. (I put the codes of the three documents at the bottom respectively, and I can use them myself if necessary)

main.c Documents

#include "game.h"

void menu()
{
    printf("********************************\n");
    printf("*********  1. play     *********\n");
    printf("*********  0. exit     *********\n");
    printf("********************************\n");
}

void game()
{
    char ret = 0;
    //Store chess data
    char board[ROW][COL] = {0};
    //Initialize the chessboard to full space
    InitBoard(board, ROW, COL);
    //Print chessboard
    DisplayBoard(board, ROW, COL);
    while (1)
    {
        //Players play chess
        player_move(board, ROW, COL);
        DisplayBoard(board, ROW, COL);
        //Judge whether to win or lose
        ret = is_win(board, ROW, COL);
        if (ret != 'C')
        {
            break;
        }
        //Computer chess
        computer_move(board, ROW, COL);//Play chess at random
        DisplayBoard(board, ROW, COL);
        ret = is_win(board, ROW, COL);
        if (ret != 'C')
        {
            break;
        }
    }
    if (ret == '*')
    {
        printf("The player won\n");
    }
    else if (ret == '#')
    {
        printf("The computer won\n");
    }
    else
    {
        printf("it ends in a draw\n");
    }
    //DisplayBoard(board, ROW, COL);
}

//
//In any case, the game is over
//Player wins - '*'
//Computer wins - '#'
//Draw - 'Q'
//Continue - 'C'
//

void test()
{
    int input = 0;
    srand((unsigned int)time(NULL));

    do
    {
        menu();
        printf("Please select:>");
        scanf("%d", &input);
        switch (input)
        {
        case 1:
            game();//game
            break;
        case 0:
            printf("Exit the game\n");
            break;
        default:
            printf("Selection error\n");
            break;
        }
    } while (input);
}

int main()
{
    test();
    return 0;
}

game.h file

#pragma once


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

#define ROW 3
#define COL 3

//Initialize chessboard
void InitBoard(char board[ROW][COL], int row, int col);

//Print chessboard
void DisplayBoard(char board[ROW][COL], int row, int col);

//Players play chess
void player_move(char board[ROW][COL], int row, int col);

//Computer chess
void computer_move(char board[ROW][COL], int row, int col);

//Judge whether to win or lose
char is_win(char board[ROW][COL], int row, int col);

game.c Documents

#include "game.h"

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


void DisplayBoard(char board[ROW][COL], int row, int col)
{
    int i = 0;
    for (i = 0; i < row; i++)
    {
        //print data
        int j = 0;
        for (j = 0; j < col; j++)
        {
            printf(" %c ", board[i][j]);
            if(j<col-1)
                printf("|");
        }
        printf("\n");
        //Print split lines
        if (i < row - 1)
        {
            for (j = 0; j < col; j++)
            {
                printf("---");
                if (j < col - 1)
                    printf("|");
            }
            printf("\n");
        }
    }
}

void player_move(char board[ROW][COL], int row, int col)
{
    int x = 0;
    int y = 0;
    printf("Players play chess\n");
    while (1)
    {
        printf("Please enter coordinates:>");
        scanf("%d %d", &x, &y);
        if (x >= 1 && x <= row && y >= 1 && y <= col)
        {
            //play chess
            if (board[x - 1][y - 1] == ' ')
            {
                board[x - 1][y - 1] = '*';
                break;
            }
            else
            {
                printf("This coordinate is occupied, please re-enter\n");
            }
        }
        else
        {
            printf("Illegal coordinates, please re-enter\n");
        }
    }
}

void computer_move(char board[ROW][COL], int row, int col)
{
    int x = 0;
    int y = 0;
    printf("Computer chess:>\n");
    while (1)
    {
        x = rand() % row;//0~2
        y = rand() % col;//0~2
        if (board[x][y] == ' ')
        {
            board[x][y] = '#';
            break;
        }
    }
}

static int if_full(char board[ROW][COL], int row, int col)
{
    int i = 0;
    for (i = 0; i < row; i++)
    {
        int j = 0;
        for (j = 0; j < col; j++)
        {
            if (board[i][j] == ' ')
            {
                return 0;//Not full
            }
        }
    }
    return 1;//Full
}

char is_win(char board[ROW][COL], int row, int col)
{
    int i = 0;
    //Judgment line
    for (i = 0; i < row; i++)
    {
        if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][1] != ' ')
        {
            return board[i][1];
        }
    }
    //Judgment column
    for (i = 0; i < col; i++)
    {
        if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[1][i] != ' ')
        {
            return board[1][i];
        }
    }
    //diagonal
    if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[1][1] != ' ')
    {
        return board[1][1];
    }
    if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[1][1] != ' ')
    {
        return board[1][1];
    }

    //Judge the draw
    if (if_full(board, row, col) == 1)
    {
        return 'Q';
    }
    
    //continue
    return 'C';
}

Topics: C Game Development