C language implementation of three chess (super detailed)

Three chess introduction:

Backgammon is a traditional folk game, also known as Jiugong Chess, Circle Chacha Chess, One Dragon, Tic Tac Toe and so on. The game is divided into two sides to play against each other. Both sides place pieces on the 9-grid chessboard in turn. The first to move their three pieces into a line is considered a victory, while the opponent loses.

Writing three chess pieces allows us to learn how to organize a larger code.

We divide the code into three modules:

test.c---used to test the game logic

game.c---function implementation

game.h---function declaration

Where game.c and game.h are game modules

Code implementation idea:

First, we need to print a menu on the screen, let the player choose 1 to enter the game, choose 0 to exit the game, if the choice is not 1 or 0, tell the player that the choice is wrong, please choose again. So in the test module test.c:

#define _CRT_SECURE_NO_WARNINGS 1
#include"game.h"//Include your own header file to use ""
void menu()
{
  printf("***************************\n");
  printf("*****     1.play      *****\n");
  printf("*****     0.exit      *****\n");
  printf("***************************\n");
}

int main()
{
  int input = 0;
   do
   {
	 menu();
	 printf("please choose:\n");
	 scanf("%d", &input);
	 switch (input)
	 {
	   case 1:
		 game();//The game function is to realize the three chess
		 break;
	   case 0:
		 printf("exit the game\n");
		 break;
	   default:
		 printf("Wrong selection, please try again:\n");
		 break;
     }
	}while (input);//The convenience of setting 1 to enter the game and 0 to exit the game is: if you choose 1 (or an integer other than 0),
//If the input is true, continue to enter the loop. If it is 0, if it is false, it will print "exit the game" and exit the loop.
	return 0;
}

The printf, scanf functions need a header file, so we are in game.h:

 

At this point, we can run the code to check whether there is a problem. When writing larger codes, we must develop this good habit, otherwise it will be difficult to find out where the error is in the end if there is a problem with the code.

Ok, the next thing we have to do is to implement the game() function.

To play chess, we must first have a chessboard, and also record the position of the player playing chess with the computer. We can output such a simple chessboard on the computer:

   |   |
---|---|---
   |   |   
---|---|---
   |   |

 

Such a three-row and three-column board is very similar to a two-dimensional array, so we can create a 3*3 two-dimensional array to record the chess pieces. Considering that we may want to play games with a larger board in the future, all the two-dimensional arrays involved The value of the dimension array size must be changed. For convenience, we define a row (row) and column (column) in game.h

Notice! Symbols defined by #define are all uppercase. In the future, we only need to change the rows and columns in the header file. Next, we need to initialize and print the chessboard. We first write the functions we need in the test logic module test.c:

#define _CRT_SECURE_NO_WARNINGS 1
#include"game.h"
void menu()
{
	printf("***************************\n");
	printf("*****     1.play      *****\n");
	printf("*****     0.exit      *****\n");
	printf("***************************\n");
}

void game()
{
	//A 3*3 two-dimensional array is required to store data
	char board[ROW][COL] = { 0 };
	//initialization (initialization) board
	Initboard(board, ROW, COL);
	//show checkerboard
	DisplayBoard(board, ROW, COL);
}
int main()
{
	int input = 0;
	do
	{
		menu();
		printf("please choose:\n");
		scanf("%d", &input);
		switch (input)
		{
		case 1:
			game();
			break;
		case 0:
			printf("exit the game\n");
			break;
		default:
			printf("Wrong selection, please try again:\n");
			break;
		}
	} while (input);
	return 0;
}

After writing the functions we need, we must declare them in game.h:

#pragma once

//header file inclusion
#include<stdio.h>

#define ROW 3
#define COL 3

//function declaration

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

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

Write and implement in game.c:

#define _CRT_SECURE_NO_WARNINGS 1
#include"game.h"

//Initialize the board
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] = ' ';//Traverse the array once, and initialize all the contents of the chessboard to ' ';
		}
	}
}

//show checkerboard
void DisplayBoard(char board[ROW][COL], int row, int col)
{
	int i = 0, j = 0;
	for (i = 0; i < row; i++)//A total of row rows are printed
	{
		for (j = 0; j < col; j++)//print each column
		{
			printf(" %c ", board[i][j]);
			if (j < col - 1)//The last extra column '|' is not printed
				printf("|");
		}
		printf("\n");
		if (i < row - 1)//The extra line at the end is not printed
		{
			for (j = 0; j < col; j++)
			{
				printf("---");
				if (j < col - 1)
					printf("|");
			}
			printf("\n");
		}
	}
}

 

At this point, we can run it again to check whether the chessboard we wrote is printed correctly. If all goes well, then we will consider starting to play chess. First, the player plays chess, and the player inputs the coordinates of the chess piece to be placed. Here we should note that the coordinates of the first element of the two-dimensional array should be [0][0], but the player may not be a programmer. In the eyes of the player, the first The coordinates of the element are [1][1], so the range of x should be 1~ROW, and the range of y should be 1~COL. After the player makes a move, he needs to print the chessboard so that the player can see where he is playing, and then it is the computer's turn to make a move. The computer moves randomly, but it cannot play in the place where the player has already made a move. The same is true for the player. When the computer makes a move Finally, the chessboard should be printed, so that the player can see the current situation of the chessboard. This cycle continues until one side wins or there is a tie, so after each move, we have to judge whether there is a victory or a tie. According to this idea, we are in the logic test code module test.c:

#define _CRT_SECURE_NO_WARNINGS 1
#include"game.h"
void menu()
{
	printf("***************************\n");
	printf("*****     1.play      *****\n");
	printf("*****     0.exit      *****\n");
	printf("***************************\n");
}

void game()
{
	//A 3*3 two-dimensional array is required to store data
	char board[ROW][COL] = { 0 };
	//Initialize the board
	Initboard(board, ROW, COL);
	//show checkerboard
	DisplayBoard(board, ROW, COL);

	while (1)
	{
		//player playing chess
		PlayerMove(board, ROW, COL);
		//print checkerboard
		DisplayBoard(board, ROW, COL);
		//judge win or lose
		
		//computer chess
		ComputerMove(board, ROW, COL);
		//print checkerboard
		DisplayBoard(board, ROW, COL);
		//judge win or lose

	}
}
int main()
{
	int input = 0;
	srand((unsigned int)time(NULL));
	do
	{
		menu();
		printf("please choose:\n");
		scanf("%d", &input);
		switch (input)
		{
		case 1:
			game();
			break;
		case 0:
			printf("exit the game\n");
			break;
		default:
			printf("Wrong selection, please try again:\n");
			break;
		}
	} while (input);
	return 0;
}

In the game implementation module game.c:

#define _CRT_SECURE_NO_WARNINGS 1
#include"game.h"

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

//show checkerboard
void DisplayBoard(char board[ROW][COL], int row, int col)
{
	int i = 0, j = 0;
	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");
		}
	}
}

//player playing chess
void PlayerMove(char board[ROW][COL], int row, int col)
{
	int x = 0, y = 0;
	printf("The player plays chess:\n");
	while (1)//The player can only jump out of the loop if the player lands successfully
	{
		printf("Please enter the coordinates where you want to play chess:");
		scanf("%d %d", &x, &y);
		if (x >= 1 && x <= row && y >= 1 && y <= col)//Judging whether the coordinates are legal
		{
			if (board[x - 1][y - 1] == ' ')//Remember not to be board[x][y]
			{
				board[x - 1][y - 1] = '*';//Suppose the player's piece is '*'
				break;
			}
			else//You can't play chess where the stones have already been placed
				printf("The coordinates are taken, please re-enter\n");
		}
		else//Illegal coordinates, player input coordinates out of range
			printf("Invalid coordinates, please re-enter\n");
	}
}

//computer random chess
void ComputerMove(char board[ROW][COL], int row, int col)
{
	int x = 0, y = 0;
	printf("Computer chess:\n");
	
	while (1)//Only when the computer makes a successful move, can it break out of the loop
	{
		x = rand() % row;
		//Call the rand() function to generate a random number, and then modulo a row,
		//Get the coordinates of a random row, such as row=3, rand()%3=0, 1, 2
		y = rand() % col;//ditto
		//To use the rand() function to generate random numbers, you need to call the srand() function to set the random number generator,
		//And srand() only needs to be called once in the whole project (called in test.c)
		//The header files required by these functions are included in game.h

		if (board[x][y] == ' ')//Determine whether the generated coordinates [x][y] are empty
		{
			board[x][y] = '#';//It is not empty, the computer moves
			break;//The move is successful, jump out of the loop
		}
		//If [x][y] is not empty, enter the loop again to generate random coordinates
	}
}

In the function declaration module game.h:

#pragma once

//header file inclusion
#include<stdio.h>
#include<stdlib.h>
#include<time.h>

#define ROW 3
#define COL 3

//function declaration

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

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

//player playing chess
void PlayerMove(char board[ROW][COL], int row, int col);

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

After writing here, we can run the code. If there is no error, the interaction between the player and the computer playing chess can now be realized.

 The next thing we have to do is to judge the winning or losing situation after each move. We write the IsWin() function in the code logic test module test.c to judge whether the three rows, three columns, and diagonals of the chessboard are the same. Or the same situation does not appear and the board is full. In order to maintain the continuation and termination of the game, the IsWin() function will tell us four situations:

1. The player wins;

2. The computer wins;

3. Draw;

4. The game continues;

//judge win or lose
//Player wins -- returns '*'
//computer win -- return '#'
//draw -- returns 'Q'
//continue -- return 'C'
char IsWin(char board[ROW][COL], int row, int col)
{
	int i = 0;
	for (i = 0; i < row; i++)//Determine whether there are three identical rows
	{
		if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != ' ')
		{
			return board[i][0];//If there are three equals, return this symbol directly
			//Directly return the pieces of the winning side, which is the convenience of the design of the return value
		}
	}
	for (i = 0; i < col; i++)//judgment column
	{
		if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[0][i] != ' ')
		{
			return board[0][i];
		}
	}
	//Judgment Diagonal
	if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[1][1] != ' ')
	{
		return board[1][1];
	}
	//Judgment Diagonal
	if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[1][1] != ' ')
	{
		return board[1][1];
	}
	//judge whether a tie
	if (IsFull(board,row,col))//Design an IsFull function to judge whether there is a tie
                          //If there is a tie, return 1, enter the if statement, if there is no tie, return 0
	{
		return 'Q';
	}
	//game continues
	return 'C';//If neither side wins and there is no tie, the code goes here and the game continues
}

This is the IsWin() function we wrote. It should be noted that the return value of this function is designed. If we find that one side wins after comparing the rows, columns, and diagonals, we don't need to judge whether the same symbol is '#' It is still '*', but directly returns the same symbol, and then analyzes it in the logic test module.

At this point, we have basically completed all the code design, and finally we only need to analyze the board outcome after each move in test.c, so we need to accept the return value of the IsWin function and analyze the progress and termination of the game , and the process of the computer players taking turns to play is a loop, and the game will end only when the result occurs, jumping out of the loop, let's take a look at the complete code.

Here is the code in test.c:

#define _CRT_SECURE_NO_WARNINGS 1
#include"game.h"
void menu()
{
	printf("***************************\n");
	printf("*****     1.play      *****\n");
	printf("*****     0.exit      *****\n");
	printf("***************************\n");
}

void game()
{
	//A 3*3 two-dimensional array is required to store data
	char board[ROW][COL] = { 0 };
	//Initialize the board
	Initboard(board, ROW, COL);
	//show checkerboard
	DisplayBoard(board, ROW, COL);
	int ret = 0;
	while (1)
	{
		//player playing chess
		PlayerMove(board, ROW, COL);
		//print checkerboard
		DisplayBoard(board, ROW, COL);
		//judge win or lose
		ret = IsWin(board, ROW, COL);
		if ('C' != ret)
		{
			break;//If the return value is not 'C', it must be a draw, player wins, computer wins
			//One of these, and any of these three means game over.
			//Break out of the loop, announce the result
		}
		//computer chess
		ComputerMove(board, ROW, COL);
		//print checkerboard
		DisplayBoard(board, ROW, COL);
		//judge win or lose
		ret = IsWin(board, ROW, COL);
		if ('C' != ret)//The computer also judges the winner after the hand is finished
		{
			break;
		}
	}
    //announce the result
	if ('*' == ret)
	{
		printf("player wins\n");
	}
	else if ('#' == ret)
	{
		printf("computer wins\n");
	}
	else
	{
		printf("draw\n");
	}
}
int main()
{
	int input = 0;
	srand((unsigned int)time(NULL));
	do
	{
		menu();
		printf("please choose:\n");
		scanf("%d", &input);
		switch (input)
		{
		case 1:
			game();
			break;
		case 0:
			printf("exit the game\n");
			break;
		default:
			printf("Wrong selection, please try again:\n");
			break;
		}
	} while (input);
	return 0;
}

Here is the code in game.c:

#define _CRT_SECURE_NO_WARNINGS 1
#include"game.h"

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

//show checkerboard
void DisplayBoard(char board[ROW][COL], int row, int col)
{
	int i = 0, j = 0;
	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");
		}
	}
}

//player playing chess
void PlayerMove(char board[ROW][COL], int row, int col)
{
	int x = 0, y = 0;
	printf("The player plays chess:\n");
	while (1)//The player can only jump out of the loop if the player lands successfully
	{
		printf("Please enter the coordinates where you want to play chess:");
		scanf("%d %d", &x, &y);
		if (x >= 1 && x <= row && y >= 1 && y <= col)//Judging whether the coordinates are legal
		{
			if (board[x - 1][y - 1] == ' ')//Remember not to be board[x][y]
			{
				board[x - 1][y - 1] = '*';//Suppose the player's piece is '*'
				break;
			}
			else//You can't play chess where the stones have already been placed
				printf("The coordinates are taken, please re-enter\n");
		}
		else//Illegal coordinates, player input coordinates out of range
			printf("Invalid coordinates, please re-enter\n");
	}
}

//computer random chess
void ComputerMove(char board[ROW][COL], int row, int col)
{
	int x = 0, y = 0;
	printf("Computer chess:\n");
	
	while (1)//Only when the computer makes a successful move, can it break out of the loop
	{
		x = rand() % row;
		//Call the rand() function to generate a random number, and then modulo a row,
		//Get the coordinates of a random row, such as row=3, rand()%3=0, 1, 2
		y = rand() % col;//ditto
		//To use the rand() function to generate random numbers, you need to call the srand() function to set the random number generator,
		//And srand() only needs to be called once in the whole project (called in test.c)
		//The header files required by these functions are included in game.h

		if (board[x][y] == ' ')//Determine whether the generated coordinates [x][y] are empty
		{
			board[x][y] = '#';
			break;//The move is successful, jump out of the loop
		}
		//If [x][y] is not empty, enter the loop again to generate random coordinates
	}
}

int IsFull(char board[ROW][COL], int row, int col)
{
	int i = 0, j = 0;
	for (i = 0; i < row; i++)
	{
		for (j = 0; j < col; j++)
		{
			if (board[i][j] == ' ')//Find a space, that is, the board is not full
				return 0;
		}
	}
	return 1;//Not found ' ', after jumping out of two layers of for loops, it comes here, that is, the chessboard is full.
}

//judge win or lose
//Player wins -- returns '*'
//computer win -- return '#'
//draw -- returns 'Q'
//continue -- return 'C'
char IsWin(char board[ROW][COL], int row, int col)
{
	int i = 0;
	for (i = 0; i < row; i++)//Judgment line
	{
		if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != ' ')
		{
			return board[i][0];//If there are three equals, return this symbol directly
			//Directly return the pieces of the winning side, which is the convenience of the design of the return value
		}
	}
	for (i = 0; i < col; i++)//judgment column
	{
		if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[0][i] != ' ')
		{
			return board[0][i];
		}
	}
	//Judgment Diagonal
	if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[1][1] != ' ')
	{
		return board[1][1];
	}
	//Judgment Diagonal
	if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[1][1] != ' ')
	{
		return board[1][1];
	}
	//judge whether a tie
	if (IsFull(board,row,col))
	{
		return 'Q';
	}
	//game continues
	return 'C';
}

Here's the code in game.h:

#pragma once

//header file inclusion
#include<stdio.h>
#include<stdlib.h>
#include<time.h>

#define ROW 3
#define COL 3

//function declaration

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

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

//player playing chess
void PlayerMove(char board[ROW][COL], int row, int col);

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

//judge win or lose
char IsWin(char board[ROW][COL], int row, int col);

Conclusion:

After the operation is correct, we can play the mini game of backgammon we wrote. It is not difficult for the player to win this version, but the difficulty is how to make the computer win. Hahaha, come and try it!

If there are deficiencies in the code, or where you don’t understand, please correct or ask questions in the comment area!

Tags: C C++ programming language

Posted by sangamon on Sun, 05 Mar 2023 05:37:33 +0530