Introduction to C language Sanzi C language implementation (detailed version)

Posted by just-j on Sun, 21 Nov 2021 09:36:02 +0100

catalogue

1. Principle of Sanzi chess

2. Block code implementation

3. Summary

1. First of all, let's introduce the principle of Sanzi chess

First, we need to have a chessboard. Initially, the chessboard is empty. We can change the space into a certain symbol by means of array. When any row or column or diagonal is the same symbol, one party wins. After a brief introduction to the principle of Sanzi chess, let's explain how to realize the step-by-step goal and code.

2. Block code implementation

1> First, we need to print a menu to guide the user to enter the decision to play the game or exit the game. We use the function to realize this step

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

We nest this function in a set test function. The benefits of this can make our main function as brief as possible. The main function only needs to call the test function to realize the whole project. We use switch case to accept the user's input value and give the corresponding results

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

    } while (input);
}

  In this paragraph, we will talk about the use of srand later. Next, we will introduce the implementation of the game in the game function.

2> Implementation of game function

As mentioned earlier, we need to use an array to implement Sanzi

Therefore, we first need to initialize an array. Since it is a Sanzi chess, we need a two-dimensional array with three rows and three columns. For the convenience of subsequent code maintenance, we first create a new header file, define a ROW and COL in the header file, and take these two values as rows and columns, with the values of three.

#define ROW 3
#define COL 3

At this time, we can easily create a binary array

char board[ROW][COL] = { 0 };

As mentioned earlier, we need to make the printed chessboard space-time at the beginning of the game, so the guard door initializes the array as a space. We use the InitBoard function to achieve this goal.

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

After initializing the array, we need to print out the chessboard. To print the divided keyboard as shown above, we can use two cycles. The outer cycle prints one line each time and the inner cycle prints one column. Note that there is no division on the right and below the chessboard. We add an if judgment to control that the division is only in the middle of the chessboard, We use the DisplayBoard function to achieve this.

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

After calling the two functions in the test function, we can print out an air disk, and then we will explain how the game player and the computer play chess separately.

First, before playing chess, we need to judge whether there is still space on the chessboard. If the chessboard is full, we can't continue playing chess. After judgment, we assume that the player's chess symbol is *, and the computer's chess symbol is #, and we use the symbol to replace the space in the array in the corresponding coordinates. We use player_move function to realize players playing chess.

void player_move(char board[ROW][COL], int row, int col)
{
	printf("Players play chess:>");
	int x = 0;
	int y = 0;

	while (1)
	{
		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("This coordinate is occupied, please re-enter!\n");
			}
		}
		else
		{
			printf("Illegal coordinates, please re-enter!\n");
		}
	}
}

After players play chess, the computer also needs to play chess. At this time, we give a random value. The srand mentioned above is used here. We use rand()%ROW or COL to find a number of 0 ~ 2, and then judge whether the corresponding position is empty. If it is not empty, replace the space in the corresponding number group with #, and if it is empty, give other random numbers.

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;
		}
	}
}

After we realize the chess game between players and computers, we need to write a function to judge the win or lose of both sides. We use Iis_win function to achieve this goal. (here we briefly introduce the principle of is_win function. We judge whether 7 a row or column or diagonal is the same symbol. If yes, we return this symbol. If not, we judge whether the chessboard is empty. After judgment, we return the corresponding symbol. Here we set:
If one row or column or diagonal is the same symbol, the corresponding symbol is returned

If the above conditions are not met and the chessboard is judged as unsatisfactory, 'Q' is returned; if it is judged as full, 'C' is returned.

The specific codes are as follows:

har is_win(char board[ROW][COL], int row, int col)
{
	int i = 0;
	//Three lines
	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];
		}
	}
	//Three columns
	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 judgment
	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 (1 == is_full(board, row, col))i
	{
		return 'Q';
	}
	//continue
	return 'C';
}

By judging the return value of is_win in the game function, we can well judge whether both sides win or lose and whether to continue. The game function is completed as follows

void game()
{
	
	char board[ROW][COL] = { 0 };
	InitBoard(board, ROW, COL);//Initialize chess and cards
	//Print chessboard
	DisplayBoard(board, ROW, COL);
	//play chess
	char ret = 0;
	while (1)
	{
		player_move(board, ROW, COL);
		DisplayBoard(board, ROW, COL);
		ret = is_win(board, ROW, COL);
		if (ret != 'C')
		{
			break;
		}
		computer_move(board, ROW, COL);
		DisplayBoard(board, ROW, COL);
		ret = is_win(board, ROW, COL);
		if (ret != 'C')
		{
			break;
		}
	}
	if (ret == '*')
	{
		printf("Player wins\n");
	}
	else if (ret == '#')
	{
		printf("Computer win\n");
	}
	else
	{
		printf("it ends in a draw\n");
	}
}

3. Summary

In order to make the code brief and clear, we use the header file of game.g, declare all the required functions in it, then establish the source file of game.c, put the specific implementation of the function in it, and then introduce the header file into test.c and game.c respectively, so that the code can be divided into blocks and easy to understand.

See for specific code c language / 2021.11.20 · Wu Changsheng / code - Code cloud - Open Source China (gitee.com)

Welcome to discuss and praise. Thank you for reading.

Topics: C