Learn C language quickly | Implement three-piece chess in multiple file formats (prenatal education version teaching) from easy to deep

Article directory

    • Introduction to three piece chess
    • Determine the steps to start the configuration file
    • Implementation of game code
      • Step 1. Determine several parts of the main file test.c
        • 1. Write the main body of the game() function
      • Step 2. Declaration of game.h header file
      • Step 3. Function implementation of game.c
        • 1. Implementation of initialization chess piece array function
        • 2. Implementation of printing chessboard function
        • 3. Implementation of the player’s chess function
        • 4. Implementation of computer chess playing function
        • 5. Implementation of judging winning and losing functions
        • 6. Implementation of the tie function
    • The overall code is as follows:
      • test.c code
      • game.h code
      • game.c code

Introduction to Three Piece Chess

Three-piece chess is a traditional folk game, also known as Jiugong chess, Tic-tac-toe, etc. The game is divided into a battle between two sides. Both sides place their chess pieces on the 9-square chessboard in turn. The first one to line up their three chess pieces is considered the winner.

Determine the steps to start the configuration file

What we choose is to use multiple files to teach everyone to complete independently, the implementation of the three-piece game.
First, we need to prepare three files: game.h to declare the function game.c to implement the function definition test.c General file The architecture is completed

Implementation of game code

Step 1. Determine several parts of the main file test.c

  • 1. Use the game’s menu to determine whether to start and exit

Enter 1 to start the game and enter 0 to exit the game.

#include "game.h"//Since we need to call the game.h header file, other required header files
//Put it all in game.h to avoid code redundancy and make the code more concise
//menu
void menu()
{<!-- -->
printf("************************\\
");
printf("******* 1.play *******\\
");
printf("******* 0.exit *******\\
");
printf("************************\\
");
}
int main()
{<!-- -->

int input = 0; //Create a variable to receive the input result
do
{<!-- -->
//Print menu
menu();
printf("Please enter your choice>");
scanf("%d", & amp;input);
switch(input)
{<!-- -->
//Start the game
case 1:
game();//Write the game function here first and then implement it
break;
\t\t\t//exit the game
case 0:
printf("Exit the game!\\
");
break;
default:
printf("Input error, please re-enter!");
break;
}
} while (input);
return 0;
}
1. Write the main body of the game() function
  • 1. Initialization of the chessboard
  • 2. Print the chessboard
  • 3. When players play chessChess pieces are represented by *
  • 4. When playing chess on a computerChess pieces are represented by #
  • 5. Determine winning or losing
    • Player wins return *****
    • Computer Win Return #
    • Draw return Q
    • Continue back C

1. Initialization of the chessboard

Observe the three-piece chessboard. The chessboard is 3×3, so we use a 3×3 array to store the chess pieces and complete the initialization.

void game()//Three-piece game main function
{<!-- -->
char board[ROW][COL] = {<!-- -->0};
//Initialize array
InitBoard(board, ROW, COL);
}
Insert code snippet here

Then first create functions that implement 5 small functions and then call them later

//Three pieces game
void game()
{<!-- -->
char board[ROW][COL] = {<!-- -->0};
//Initialize array
InitBoard(board, ROW, COL);
char ret = 0;//Used to receive the value returned by the win or lose function
char play = 0;//Used to receive the return value that the chess coordinates are occupied
//Print the chessboard
DisplayBoard(board, ROW, COL);
while (1)//Create a loop and keep betting as long as no one wins
{<!-- -->
//Players play chess
play = PlayMove(board, ROW, COL);
if (play == 'P')//When playing chess, if the coordinate input is wrong and the coordinates are occupied, exit the loop
continue;//Do not let the computer play chess
//Judge winning or losing
ret = IsWin(board, ROW, COL);//Receive the result of each judgment
if (ret != 'C')//When the returned value is not C, if you continue, then exit, indicating that someone has won.
{<!-- -->
system("cls");//Clear all chessboards and print them once when exiting
//Print the chessboard
DisplayBoard(board, ROW, COL);
break;
}
//Print the chessboard
DisplayBoard(board, ROW, COL);
//Computer plays chess
ComputerMove(board, ROW, COL);
system("cls");//Clear all the contents of the screen and print the chessboard after each game
//Print the chessboard //Let there be only one chessboard on the screen each time
DisplayBoard(board, ROW, COL);
//Judge winning or losing
ret = IsWin(board, ROW, COL);
if (ret != 'C')//When the returned value is not C, if you continue, then exit, indicating that someone has won.
{<!-- --> //Enter if to end this loop
system("cls");//Clear all chessboards and print them once when exiting
//Print the chessboard
DisplayBoard(board, ROW, COL);
break;
}
}
if (ret == '*')
{<!-- -->
printf("Player wins!\\
");
}
else if (ret == '#')
{<!-- -->
printf("The computer wins!\\
");
}
else
{<!-- -->
printf("Tie!\\
");
}
}

Step 2, declaration of game.h header file

We have already split the game into 5 small parts. Next comes the declaration and definition.

  • For declarations and frequently used header files, we put them all in the header file of game.h
#pragma once
#include <stdio.h> //Input and output header files
#include <stdlib.h> //Get the random function header file, which will be used later
#include <time.h> //The header file that the srand function needs to obtain the timestamp will be used later
#define ROW 3 //Rows of the chessboard
#define COL 3 //Columns of the chessboard
//Initialize array
void InitBoard(char board[ROW][COL],int row,int col);
//Print the chessboard
void DisplayBoard(char board[ROW][COL], int row, int col);
//Players play chess
int PlayMove(char board[ROW][COL], int row, int col);
//Computer plays chess
void ComputerMove(char board[ROW][COL], int row, int col);
//Judge winning or losing
char IsWin(char board[ROW][COL], int row, int col);
//draw
int IsFull(char board[ROW][COL], int row, int col);

Step 3, function implementation of game.c

We have completed the various function names and function declaration. The next step is to implement these small functions in game.c

#include "game.h"//First call it in game.c
//Header files and functions declared in game.h
1. Implementation of initialization chess piece array function

Use a loop to traverse the chess pieces in the array so that all spaces are stored in it.

//Initialize array
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] = ' ';
}
}

}
2. Implementation of printing chessboard function

Observing the chessboard, we found that it is divided into 2 parts.

  • The first part is (space chess piece space | space chess piece space | space chess piece space)
  • The second part is (- – – | – – – | – – -) and each part is output three times

So we use a for loop to write
| There are only two in each line, so you need to write an if judgment

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

\t\t
}

}
3. Implementation of the player’s chess function

What is received here is the coordinates input by the player, usually from 1 to 3
But the array subscript starts from 0, so it is enough to put the row and column entered by the player each time – 1

//Players play chess
int PlayMove(char board[ROW][COL], int row, int col)
{<!-- -->
int x = 0;
int y = 0;
printf("Players play chess");
printf("Please enter the coordinates, separated by spaces ->");
\t
scanf("%d %d", & amp;x, & amp;y);
//Check whether the coordinates are legal
if (x >= 1 & amp; & y >= 1 & amp; & amp; x <= row & amp; & y <= col )
{<!-- -->
if (board[x - 1][y - 1] == ' ')
{<!-- -->
board[x - 1][y - 1] = '*';
}
else
{<!-- -->
printf("The coordinates are occupied, please re-enter!\\
");
return 'P';
}
}
else
{<!-- -->
printf("Input error please re-enter!\\
");
return 'P';
}
\t
}

4. Implementation of computer chess playing function

We let the computer generate random number coordinates every time to generate rows and columns to play chess.

//Computer playing chess
void ComputerMove(char board[ROW][COL], int row, int col)
{<!-- -->
//Randomly play chess
int x = 0;
int y = 0;
printf("Computer playing chess:>\\
");
while (1)
{<!-- -->
x = rand() % row;//The random number generated modulo divides the row we need. The generated number is within rows 0~3
y = rand() % col;
if (board[x][y] == ' ')
{<!-- -->
board[x][y] = '#';
break;
}
}
\t
}
5. Implementation of winning or losing function
//The player wins and returns *
//Computer wins and returns #
//Tie returns Q
//Continue to return to C
char IsWin(char board[ROW][COL], int row, int col)
{<!-- -->
int i = 0;
for (i = 0; i < row; i + + )
{<!-- -->
//Judge the row
if (board[i][0] == board[i][1] & amp; & amp; board[i][1] == board[i][2] & amp; & amp; board[i] [1] != ' ')
{<!-- -->
return board[i][0];
}
//Judgment column
if (board[0][i] == board[1][i] & amp; & amp; board[1][i] == board[2][i] & amp; & amp; board[0] [i] != ' ')
{<!-- -->
return board[0][i];
}
}
//Judge the diagonal
if (board[0][0] == board[1][1] & amp; & amp; board[1][1] == board[2][2] & amp; & amp; board[1] [1] != ' ')
return board[1][1];
//Judge the diagonal
if (board[0][2] == board[1][1] & amp; & amp; board[1][1] == board[2][0] & amp; & amp; board[1] [1] != ' ')
return board[1][1];
//Judge a tie
if (IsFull(board, row, col) == 1)
{<!-- -->
return 'Q';
}
else
{<!-- -->
return 'C';
}
//Continue C
}
6. Implementation of tie judgment function

Traverse the array once. When there are no spaces stored in the array, it means that the chessboard is full. Tie

//Tie
int IsFull(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;
}
}
}
return 1;
}

The overall code is as follows:

test.c code

#define _CRT_SECURE_NO_WARNINGS 1
#include "game.h"
// menu
void menu()
{<!-- -->
printf("************************\\
");
printf("******* 1.play *******\\
");
printf("******* 0.exit *******\\
");
printf("************************\\
");
}
//Three pieces game
void game()
{<!-- -->
char board[ROW][COL] = {<!-- -->0};
//Initialize array
InitBoard(board, ROW, COL);
char ret = 0;
char play = 0;
//Print the chessboard
DisplayBoard(board, ROW, COL);
while (1)
{<!-- -->
//Players play chess
play = PlayMove(board, ROW, COL);
if (play == 'P')
continue;
//Judge winning or losing
ret = IsWin(board, ROW, COL);
if (ret != 'C')
{<!-- -->
system("cls");
//Print the chessboard
DisplayBoard(board, ROW, COL);
break;
}
//Print the chessboard
DisplayBoard(board, ROW, COL);
//Computer plays chess
ComputerMove(board, ROW, COL);
system("cls");
//Print the chessboard
DisplayBoard(board, ROW, COL);
//Judge winning or losing
ret = IsWin(board, ROW, COL);
if (ret != 'C')
{<!-- -->
system("cls");
//Print the chessboard
DisplayBoard(board, ROW, COL);
\t\t\t
break;
}
}
if (ret == '*')
{<!-- -->
printf("Player wins!\\
");
}
else if (ret == '#')
{<!-- -->
printf("The computer wins!\\
");
}
else
{<!-- -->
printf("Tie!\\
");
}
}
int main()
{<!-- -->

int input = 0;
do
{<!-- -->
srand((unsigned int)time(NULL));
//Print menu
menu();
printf("Please enter your choice >");
scanf("%d", & amp;input);
switch(input)
{<!-- -->
//Start the game
case 1:
game();
break;
\t\t\t//exit the game
case 0:
printf("Exit the game!");
break;
default:
printf("Input error, please re-enter!");
break;
}
} while (input);
return 0;
}

game.h code

#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdlib.h>
#define ROW 3
#define COL 3
//Initialize array
void InitBoard(char board[ROW][COL],int row,int col);
//Print the chessboard
void DisplayBoard(char board[ROW][COL], int row, int col);
//Players play chess
int PlayMove(char board[ROW][COL], int row, int col);
//Computer plays chess
void ComputerMove(char board[ROW][COL], int row, int col);
//Judge winning or losing
char IsWin(char board[ROW][COL], int row, int col);
//draw
int IsFull(char board[ROW][COL], int row, int col);

game.c code

#define _CRT_SECURE_NO_WARNINGS 1
#include "game.h"
//Initialize array
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] = ' ';
}
}

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

\t\t
}

}

//Players play chess
int PlayMove(char board[ROW][COL], int row, int col)
{
int x = 0;
int y = 0;
printf("Players play chess");
printf("Please enter the coordinates, separated by spaces ->");
\t
scanf("%d %d", & amp;x, & amp;y);
//Check whether the coordinates are legal
if (x >= 1 & amp; & y >= 1 & amp; & amp; x <= row & amp; & y <= col )
{
if (board[x - 1][y - 1] == ' ')
{
board[x - 1][y - 1] = '*';
}
else
{
printf("The coordinates are occupied, please re-enter!\\
");
return 'P';
}
}
else
{
printf("Incorrect input, please re-enter!\\
");
return 'P';
}
\t
}

//Computer plays chess
void ComputerMove(char board[ROW][COL], int row, int col)
{
//Randomly play chess
int x = 0;
int y = 0;
printf("Computer playing chess:>\\
");
while (1)
{
x = rand() % row;
y = rand() % col;
if (board[x][y] == ' ')
{
board[x][y] = '#';
break;
}
}
\t
}
//Player wins *
//computer wins #
//Draw Q
//Continue C
char IsWin(char board[ROW][COL], int row, int col)
{
int i = 0;
\t
for (i = 0; i < row; i + + )
{
//Judge the row
if (board[i][0] == board[i][1] & amp; & amp; board[i][1] == board[i][2] & amp; & amp; board[i] [1] != ' ')
{
return board[i][0];
}
//Judgment column
if (board[0][i] == board[1][i] & amp; & amp; board[1][i] == board[2][i] & amp; & amp; board[0] [i] != ' ')
{
return board[0][i];
}
\t\t
}
//Judge the diagonal
if (board[0][0] == board[1][1] & amp; & amp; board[1][1] == board[2][2] & amp; & amp; board[1] [1] != ' ')
return board[1][1];
//Judge the diagonal
if (board[0][2] == board[1][1] & amp; & amp; board[1][1] == board[2][0] & amp; & amp; board[1] [1] != ' ')
return board[1][1];
//Judge a tie
if (IsFull(board, row, col) == 1)
{
return 'Q';
}
else
{
return 'C';
}
//Continue C

\t

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