Implementation details of simple Sanzi chess (C language)

        Sanzi game contains a variety of knowledge such as array, loop and function. It is a good topic to exercise thinking logic for small partners who first know C language. The following figure shows the final simple implementation of Sanzi chess:

 

During the implementation of Sanzi chess, three new items need to be created:

1,test.c

2,game.h

3,game.c

      test.c is used to store the code of the test part, game.h is used to store the declaration of functions, and game.c is used to store the specific definitions of various functions. The specific implementation ideas of Sanzi chess are as follows: 1. Print the initial menu of Sanzi chess by using printf function; 2. The user inputs 1 or 0 through the keyboard to indicate whether to enter the game; 3. After the user chooses to enter the game, print the chessboard and play chess with the computer; 4. Judge the winner or loser of chess and output the result of chess. Before designing the program, we need to consider the scalability requirements behind the code, so the number of rows and columns of the chessboard are defined as symbols.

1, Print the menu of Gobang

    Use the printf function to print the menu. Pay attention to the alignment and try to make the printed menu beautiful. Among them, 1 represents entering the Sanzi game and 0 represents exiting without entering the game.

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

2, User input to determine whether to enter the game

      After the previous print menu, the user will choose whether to enter the game. In the first case, enter 1 to enter the game; The second is to select 0 and not enter the game; There may also be input errors. Game () encapsulates the code of the game, because users may want to play the game many times or input errors. So, put this code into the do...while() loop.

void test()
{
	int input = 0;
	srand((unsigned)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);
}

  3, Print the chessboard and the process of playing chess

        Each time the user enters the game, first initialize the chessboard, and then print the chessboard, so that the user can input the correct chessboard position to play chess.

(1) Initialize the chessboard. The InitBoard() function initializes all positions of the chessboard into spaces, mainly using two for loops. This step is mainly to clear all the information of the last game when the user wants to play the game again.

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

(2) The printing of chessboard is realized by DisplayBoard() function. In the process of re printing, because the elements in the string are spaces initially, additional symbols are required to display them. Therefore, elements such as "|" and "---" are added in cyclic printing. In the process of printing, we still need to pay attention to the scalability of the code and cannot write the code dead.

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

The result of printing the checkerboard function is

(3) After printing the chessboard, you can start playing chess. In the process of playing chess, it is a cycle composed of players playing chess and computer playing chess.

       < 1>   In the process of playing chess, the player must first judge the legitimacy of the coordinates entered by the player. The legitimacy involves whether the position is legal and whether the position has played chess before. If none, change the space to '*' to indicate that the player is playing chess at this position. It should be noted that since the position understood by the player deviates from the position of the array in the code, it can be corrected with - 1.

void  play_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)//Coordinate legitimacy judgment
		{
			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!\n");
		}
	}
		
}

     < 2> In the process of computer playing chess, the computer needs to generate a random number between 0 and 2 to represent the position of computer playing chess. The position under the computer uses' # 'instead of space.

void computer_move(char board[ROW][COL], int row, int col)
{
	printf("Computer chess:>\n");
	int x = 0;
	int y = 0;

	while (1)
	{
		x = rand() % ROW;//rand()%ROW random numbers range from 0 to row-1
		y = rand() % COL;

		if (board[x][y] == ' ')
		{
			board[x][y] = '#';
			break;
		}
	}
}

    So far, the code can complete the process of playing chess between players and computers. Of course, the code of computer chess needs to be further optimized and better algorithms should be used. The logic of the whole program has run through. But there is still a lack of steps to best produce results.

4, The function of judging whether to win or lose

      After players play chess with computers, they also need to judge whether players win or computers win, or draw. We use is_win function to judge this result. When a row element, a column element or a diagonal element is' * ', it means that the player wins; When both are '#', it means that the computer wins. If these two conditions are not satisfied, judge whether the chessboard is full. If it is full, it means a draw. If it is not full, you can continue to play chess.

char is_win(char board[ROW][COL], int row,int col)
{
	int i = 0;
	//All elements in a row are equal
	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][1];
		}
	}
	//All elements in a column are equal
	for (i = 0; i < row; i++)
	{
		if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[0][i] != ' ')
		{
			return board[1][i];
		}
	}
	//Diagonal judgment
	if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != ' ')
	{
		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))
	{
		return 'Q';
	}
	//The game continues
	return 'C';
}

Where is_ The full function is used to determine whether the chessboard is full.

int is_full(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;
}

The above is all the code to realize Sanzi chess!

Tags: C Back-end

Posted on Tue, 09 Nov 2021 20:39:06 -0500 by evil turnip