Ideas to share the three-middle chess game

Ideas to share the three-middle chess game

Today, I am very happy to share with you my feelings and some ideas of practicing three-middle chess.

  1. First, let’s build a project. This time it’s different. In order to subdivide the code clearly, create a header file (game.h) (used to include some header files and declare some functions), and then create two Source files (game.c and test.c) (one is the game code or some function parts, the other is the test part is mainly some external frameworks).
  2. Then first build a framework, as shown in the figure below.
    Insert picture description here
    This menu part can be realized by a menu(), the code is as follows:
void menu()
{
    
    
	printf("******************\n");
	printf("***   1.play   ***\n");
	printf("***   0.exit   ***\n");
	printf("******************\n");
}

In addition, we participate in the game by entering the number. If it is 1, it will participate in the game, and if it is 0, the game will be ended. If other numbers are entered, the input error will be printed and entered again. Everyone sees that different operations are performed according to the entered number. Have you thought of the switch statement? We use this to achieve it, the code in the test.c source file is as follows:

int main()
{
    
    
	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;
}

Let's try it first and see if we can achieve this feature.
Insert picture description here

Everyone still thinks this is very simple, let us continue to dig deeper!
3. Now is the big project inside game().
(1) Because we are designing a three-piece chess, we regard it as a character array with three rows and three columns. Because this is a chessboard, we directly write the name of the array as board,board[ROW][COL],
we are here Instead of directly writing the number of rows and columns of the array, you can make a macro definition, which helps compatibility. If you do gobang or other forms next time, you can directly modify the information in the macro definition. Our code in the game.h header file is as follows:

#define ROW 3
#define COL 3

We only need to add in each source file

#include "game.h"

That's it.
(2) We initialize the chessboard array so that every bit is a space. In game.h we write a function InitBoard() declaration

//初始化棋盘
void InitBoard(char board[ROW][COL], int row, int col);

Then we can implement this function in game.c.

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

(3) After initializing the chessboard, we first print the chessboard, which is similar to the initialization chessboard above, first declare

//打印棋盘
void DisplayBoard(char board[ROW][COL], int row, int col);

Realize it again

void DisplayBoard(char board[ROW][COL], int row, int col)
{
    
    
	int i = 0;
	for (i = 0; i < row; i++)
	{
    
    
		//打印数据
		printf(" %c | %c | %c \n", board[i][0], board[i][1], board[i][2]);
		//打印分割的行
		if (i < row - 1)
		printf("---|---|---\n");
	}
}

Although this code realizes the printing of the chessboard, the compatibility is not good. If you don't print the three-person chess board, change it to five-person chess, etc., this code will not work. So now modify the code and change the printing to loop form

void DisplayBoard(char board[ROW][COL], int row, int col)
{
    
    
	int i = 0;
	for (i = 0; i < row; i++)
	{
    
    
		//打印数据
		//printf(" %c | %c | %c \n", board[i][0], board[i][1], board[i][2]);
		int j = 0;
		for (j = 0; j < col; j++)
		{
    
    
			printf(" %c ", board[i][j]);
			if (j < col - 1)
				printf("|");
		}
		printf("\n");
		//打印分割的行
		if (i < row - 1)
		{
    
    
			//printf("---|---|---\n");
			for (j = 0; j < col; j++)
			{
    
    
				printf("---");
				if (j < col - 1)
					printf("|");
			}
			printf("\n");
		}
	}
}

Insert picture description here
The board is printed out, whether it is three-piece chess or five-piece chess or other forms, you can print out the correct board just by changing the macro definition.
(4) Now we can proceed to the chess session. Because this is a manual battle, we have two functional players playing chess and computer chess. The code is as follows:

//玩家下棋
void PlayerMove(char board[ROW][COL], int row, int col);

//电脑下棋
void ComputerMove(char board[ROW][COL], int row,int col);

(5) Now we are writing the code of the PlayerMove() function. We change the elements of the chessboard array by reading the input coordinates. At the same time, we must prevent the input of some special situations. Therefore, we need to judge the input coordinates. Whether the coordinate is in the string, and the element under the coordinate is a space ( At the same time, note that since the beginning of the array in C language starts from 0, when judging the array element under this coordinate, remember to reduce the number of rows and columns by 1 ! )

void PlayerMove(char board[ROW][COL], int row, int col)
{
    
    
	int x = 0;
	int 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] != ' ')
			{
    
    
				printf("坐标被占用,请重新输入!\n");
			}
			else
			{
    
    
				board[x-1][y-1] = '*';
				break;
			}
		}
		else
		{
    
    
			printf("坐标非法,请重新输入!\n");
		}
	}
}

(6) To play chess on the computer, in order to ensure the progress of random chess, we generate random numbers in the form of rand(), and then use the timestamp as the starting point of random number generation, so we perform a random number starting point in the main function Proceed, so we use the following random number starting point

srand((unsigned int)time(NULL));

At the same time include the header file in the game.h header file

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

The computer chess code is as follows:

void ComputerMove(char board[ROW][COL], int row,int col)
{
    
    
	printf("电脑走:>\n");
	while(1)
	{
    
    
		int x = rand() % row;
		int y = rand() % col;
		if (board[x][y] == ' ')
		{
    
    
			board[x][y] = '#';
			break;
		}
	}
}

(7) Now you can play chess, and finally judge the situation of winning or losing:
(1) One is the result of winning or losing.
(2) One is that the game is not over yet.
(3) Finally, it is a tie.
Pass a character variable ret. Control and judge the situation of winning or losing.
Here we still use a function CheckWin () to proceed, the function declaration is not written, the code is as follows:

//判断输赢
char CheckWin(char board[ROW][COL], int row, int col)
{
    
    
	int i = 0;

	//三行
	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 < row; 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[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];
	//平局
	if (IsFull(board, row, col) == 1)
	{
    
    
		return 'Q';
	}
	return 'C';
}

When judging a tie, refer to the IsFull() function to determine whether the game should be ended

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

After the above code design, game() basically achieves

void game()
{
    
    
	char ret = '0';
	//数组的存储是二维数组
	char board[ROW][COL];//初始化为空格
	//初始化棋盘
	InitBoard(board, ROW, COL);
	DisplayBoard(board, ROW, COL);
	while (1)
	{
    
    
		//玩家下棋
		PlayerMove(board,ROW,COL);
		ret = CheckWin(board, ROW, COL);
		if (ret != 'C')
		{
    
    
			break;
		}
		DisplayBoard(board, ROW, COL);
		//电脑下棋
		ComputerMove(board,ROW,COL);//随机下棋
		ret = CheckWin(board, ROW, COL);
		if (ret != 'C')
		{
    
    
			break;
		}
		DisplayBoard(board, ROW, COL);
	}
	if (ret == '*')
		printf("玩家赢了\n");
	else if (ret == '#')
		printf("电脑赢了\n");
	else if (ret == 'Q')
		printf("平局\n");
	DisplayBoard(board, ROW, COL);
}

Now let’s play a three-man chess game!
Insert picture description here
After a PK with the computer, finally won when the board is full! ( )
Thank you for watching. As Xiaobai, the writing is not very thorough. I hope everyone will bear your advice. Thank you!

Guess you like

Origin blog.csdn.net/weixin_51548091/article/details/113092325