C language foundation - three chess (detailed explanation)

Preface: The complete code will be given at the end of the article. The previous code will not be comprehensive because it is easy to explain, and it is for reference only.

Table of contents

1. Rules of backgammon game

2. How to analyze the layout

3. Code display and explanation

1. Game menu

2. Display the chessboard

3. Players play chess

4. Computer chess

5. Judge win/lose/tie

4. Full code display

1.game.h

2.game.c

3.test.c

5. Summary


1. Rules of backgammon game

My friends must have        played backgammon when they were young. It is nothing more than a three- by - three chessboard . There is no child to drop, that is, nine grids are occupied , resulting in a tie .

2. How to analyze the layout

       We know that writing codes requires a neat and orderly design. Even designing an extremely simple game like three-moon chess cannot be done in just a few dozen lines of code.

       As shown in the figure below, we create our own header file " game.h" to centrally store the header files we need to use and declare the functions we need to use. We only need to declare our own header files in the source file Just #include "game.h" .

 

In addition, we create a new source file game.c to focus on creating the functions we need.

 Finally, the main code of our game is written in the source file test.c.

3. Code display and explanation

1. Game menu

Any game needs a menu to choose how the game plays.

void menu()//打印菜单函数
{
	printf("******************************\n");
	printf("*******     1.play     *******\n");
	printf("*******     0.exit     *******\n");
	printf("******************************\n");

}
char board[ROW][COL] = {'0'};//游戏数组
int main()
{
	int input = 0;
	do {
		menu();
		printf("请选择->:");
		scanf("%d", &input);//选择
		switch (input)
		{
		case 1:
			printf("三子棋\n");
			break;
		case 0:
			printf("退出游戏\n");
			break;
		default:
			printf("选择错误,请重新选择\n");
			break;
		}
	} while (input);
	return 0;
}

         We create a menu (menu) function to specifically output our menu, and use the do-while loop and switch-case statement to realize the loop play of the game.

       Here is a little trick , we know that the judgment condition of while is 0 is false , and non-zero is true , so we use case 0 as the exit game, and it can also terminate the loop , and input 1 or other numbers , it will continue to loop, restart choose.

2. Display the chessboard

Our ideal chessboard looks like this, which obviously requires a two-dimensional array, and the elements of this two-dimensional array are all " ", (space) .

void SetBoard(char board[ROW][COL], int row, int col)//创建棋盘函数
{
	int i;
	int j;
	for (i = 0; i < row; i++)
	{
		for (j = 0; j < col; j++)
		{
			board[i][j] = ' ';
		}
	}
}
void ShowBoard(char board[ROW][COL],int row,int col)//展示棋盘函数
{
	int i;
	int 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)
		printf("---|---|---\n");
	}
}

       Above we have defined the array char board[ROW][COL] = {'0'} , which is defined as an array with only one element "0", and then we create the chessboard through the first function SetBoard above , and then Use the ShowBoard function to decorate and display the chessboard.

3. Players play chess

void PlayerMove(char board[ROW][COL], int row, int col)//玩家下棋函数
{
	while (1)
	{
		printf("玩家下棋(选择坐标):");
		int x, y;
		scanf("%d %d", &x, &y);
		if (x >= 1 && x <= ROW && y >= 1 && y <= COL)
		{
			if (board[x - 1][y - 1] == ' ')
			{
				board[x - 1][y - 1] = '*';
				break;
			}
			else
				printf("该坐标已被占用,请重新输入:\n");
		}
		else
			printf("输入的坐标错误,请重新输入:\n");
	}


}

       We play chess here to modify the elements of the array . Players input a coordinate to judge whether the position is empty. If it is empty, they will drop '*' . If the input coordinates are out of bounds, a warning will be issued and the input will be re-entered . Here, players need to pay attention to one thing when playing chess, that is, players are not necessarily programmers , they will not enter the subscript corresponding to the array when they choose the coordinates, they will be 2 3 if it is two rows and three columns , we only need to let these two numbers Both -1 , the effect can be achieved.

4. Computer chess

void ComputerMove(char board[ROW][COL], int row, int col)//电脑下棋函数
{
	printf("电脑下棋:\n");
	int x, y;
	while (1)
	{
		x = rand() % row;
		y = rand() % col;
		if (board[x][y] == ' ')
		{
			board[x][y] = '#';
			break;
		}
	}
}
srand((unsigned int)time(NULL));//生成随机数,rand函数需要用,此处无用,供参考

One of the key points of computer chess is randomness . The coordinates here need to use the rand function to generate random numbers. Note that the computer itself does not pay as much attention to chess as players. The generated random numbers can be between 0-2 . When playing chess with a computer, we stipulate that the move is '#' .

5. Judge win/lose/tie

int IsFull(char board[ROW][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;
}

char IsWin(char board[ROW][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[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))//判断平局
	{
		return 'Q';
	}
	return 'C';
}

Here we define the IsWin function to judge winning or losing, and realize it by returning a value .

We stipulate the following four ways to judge the progress of the game:

Player wins --> returns '*'
computer wins --> returns '#'
draw --> returns 'Q'
game continues --> returns 'C'

       Why is this stipulated? We know that the player's piece is '*' , and if the player wins, then one of our rows, columns, or diagonals will be '*' , so we can return an element at will, and the following code can be realized player wins. The computer wins in the same way. At the same time, we will also have the result of a draw , so how is it a draw? Quite simply, if no one wins and the board is filled , isn't that a draw?

So we define the IsFull function to judge whether the array is full, and return 1 if it is full, so that the final if judgment statement is true , and finally return 'Q' , and return 0 if it is not full, and finally return 'C' .

	char ret = 0;//判断结果
		case 1:
			SetBoard(board, ROW, COL);//创建棋盘
			ShowBoard(board, ROW, COL);//展示棋盘
			while (1)
			{
				//玩家先开始下棋
				PlayerMove(board, ROW, COL);
				ShowBoard(board, ROW, COL);//下棋之后展示棋盘
				//判断输赢
				ret = IsWin(board, ROW, COL);
				if (ret != 'C')
					break;
				//电脑开始下棋
				ComputerMove(board, ROW, COL);
				ShowBoard(board, ROW, COL);//下棋之后展示棋盘
				//判断输赢
				ret = IsWin(board, ROW, COL);
				if (ret != 'C')
					break;
			}
			if (ret == '*')
				printf("玩家赢\n");
			else if (ret == '#')
				printf("电脑赢\n");
			else
				printf("平局\n");
			break;

 Here is the main function judgment , we define ret to receive the return value of the IsWin function , and use the if -else judgment statement to realize the judgment of the game result.

4. Full code display

1.game.h

#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#define ROW 3//行数为三
#define COL 3//列数为三
void SetBoard(char board[ROW][COL], int row, int col);//创建棋盘
void ShowBoard(char board[ROW][COL], int row, int col);//展示棋盘
void PlayerMove(char board[ROW][COL], int row, int col);//玩家下棋
void ComputerMove(char board[ROW][COL], int row, int col);//电脑下棋
char IsWin(char board[ROW][COL], int row, int col);//判断输赢

2.game.c

#include"game.h"
void SetBoard(char board[ROW][COL], int row, int col)//创建棋盘函数
{
	int i;
	int j;
	for (i = 0; i < row; i++)
	{
		for (j = 0; j < col; j++)
		{
			board[i][j] = ' ';
		}
	}
}
void ShowBoard(char board[ROW][COL],int row,int col)//展示棋盘函数
{
	int i;
	int 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)
		printf("---|---|---\n");
	}
}
void PlayerMove(char board[ROW][COL], int row, int col)//玩家下棋函数
{
	while (1)
	{
		printf("玩家下棋(选择坐标):");
		int x, y;
		scanf("%d %d", &x, &y);
		if (x >= 1 && x <= ROW && y >= 1 && y <= COL)
		{
			if (board[x - 1][y - 1] == ' ')
			{
				board[x - 1][y - 1] = '*';
				break;
			}
			else
				printf("该坐标已被占用,请重新输入:\n");
		}
		else
			printf("输入的坐标错误,请重新输入:\n");
	}


}
void ComputerMove(char board[ROW][COL], int row, int col)//电脑下棋函数
{
	printf("电脑下棋:\n");
	int x, y;
	while (1)
	{
		x = rand() % row;
		y = rand() % col;
		if (board[x][y] == ' ')
		{
			board[x][y] = '#';
			break;
		}
	}
}
//玩家赢-->'*'
//电脑赢-->'#'
//平局-->'Q'
//游戏继续-->'C'
int IsFull(char board[ROW][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;
}

char IsWin(char board[ROW][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[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))//判断平局
	{
		return 'Q';
	}
	return 'C';
}

3.test.c

#include"game.h"
void menu()//打印菜单函数
{
	printf("******************************\n");
	printf("*******     1.play     *******\n");
	printf("*******     0.exit     *******\n");
	printf("******************************\n");

}
char board[ROW][COL] = {'0'};//游戏数组
int main()
{
	srand((unsigned int)time(NULL));//生成随机数,供电脑下棋使用
	int input = 0;
	char ret = 0;//判断结果
	do {
		menu();
		printf("请选择->:");
		scanf("%d", &input);//选择
		switch (input)
		{
		case 1:
			SetBoard(board, ROW, COL);//创建棋盘
			ShowBoard(board, ROW, COL);//展示棋盘
			while (1)
			{
				//玩家先开始下棋
				PlayerMove(board, ROW, COL);
				ShowBoard(board, ROW, COL);//下棋之后展示棋盘
				//判断输赢
				ret = IsWin(board, ROW, COL);
				if (ret != 'C')
					break;
				//电脑开始下棋
				ComputerMove(board, ROW, COL);
				ShowBoard(board, ROW, COL);//下棋之后展示棋盘
				//判断输赢
				ret = IsWin(board, ROW, COL);
				if (ret != 'C')
					break;
			}
			if (ret == '*')
				printf("玩家赢\n");
			else if (ret == '#')
				printf("电脑赢\n");
			else
				printf("平局\n");
			break;
		case 0:
			printf("退出游戏\n");
			break;
		default:
			printf("选择错误,请重新选择\n");
			break;
		}
	} while (input);
	return 0;
}

5. Summary

       This is probably the case for the creation of three chess. The blogger is also a beginner. There may be more improvement plans in many places. In the future, I will improve myself through continuous learning to improve the code. At the same time, I would like to thank my friends for their patience. My explanation, if you have any questions or suggestions for improvement, please feel free to comment by private message.

       Finally, I hope that our little friends who like programming can go further and further and get their favorite offers. If you like the blogger’s article, don’t forget to click three times . See you next time!

Guess you like

Origin blog.csdn.net/2303_78442132/article/details/131936381