(C language) implementation of Sanzi chess

I've been learning C language for a month unknowingly, and I've gained a lot of knowledge. In particular, I'm very excited to learn to write a small Sanzi game. Today, we'll know it. Without much talk, we'll officially start.

1, Three piece chess

The Sanzi chess written this time is divided into three files. Under the same project, they are test.c, game.h and game.c. the test.c file is mainly used to realize the logic of entering the game, exiting the game, judging win or lose, printing the menu, etc., while game.c is used to write the main implementation method of the game, and game.h stores the header file and function declaration.

The specific implementation of Sanzi chess is shown in the figure.

2, The logic of entering or exiting the game

1. test.c file

#include "game.h"
void menu() {
	printf("----------------------------------\n");
	printf("-----------   1.play   -----------\n");
	printf("-----------   0.exit   -----------\n");
	printf("----------------------------------\n");
}
void test() {
	int input = 0;
	do {
		menu();	//menu
		printf("Please select input 1/0: ");	//Choose to continue the game or exit
		scanf("%d", &input);
		switch (input) {
		case 1:					//If it is 1, enter the game
			printf("tic-tac-toe \n");
			break;
		case 0 :
			printf("Exit the game\n");
			break;
		default:
			printf("The number you entered is not in the range, please re-enter\n");
			break;
		}
		printf("\n");
	} while (input);	//If input is 1, continue, if 0, exit the game, and re-enter others
}

int main() {
	test();
	return 0;
}

Here, you can put the header file to be referenced into game.h, so that when the game.c and test.c source files need to reference the same header file, you only need to reference the game.h file, which will be much more convenient. If both source files need to reference #include < stdio. H >, then you only need to reference the game.h file in game.h. Next, let's take a look at the above operation results:

When the code runs without problems, I can put printf("three pieces of chess"); Change to the game function.

3, Initialize chessboard

1. test.c file (not all shown later, but only the content of game function)

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

void game() {

	char board[ROW][COL] = { 0 };	//To print a chessboard, a two-dimensional array needs to be initialized to 0
	Init(board, ROW, COL);	//Initialize the chessboard, that is, initialize all chessboards as spaces.
}
void test() {
	int input = 0;
	do {
		menu();	//Select menu
		printf("Please select input 1/0: ");	//Choose to continue the game or exit
		scanf("%d", &input);
		switch (input) {
		case 1:					//If it is 1, enter the game
			game();
			break;
		case 0 :
			printf("Exit the game\n");
			break;
		default:
			printf("The number you entered is not in the range, please re-enter\n");
			break;
		}
		printf("\n");
	} while (input);	//If input is 1, continue, if 0, exit the game, and re-enter others
}

int main() {
	test();
	return 0;
}

2. game.h file (it will not be displayed when the function needs to be declared later)

#include <stdio.h>
#define ROW 3 	// that 's ok
#define COL 3 / / column
void Init(char board[ROW][COL], int row, int col);//Initialize chessboard

3. game.c file

#include "game.h"

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

Here #define ROW 3 and #define COL 3 are defined to facilitate us to improve the code. For example, when we want to print a Gobang board, we change 3 to 5.

4, Print chessboard

1. test.c file

void game() {

	char board[ROW][COL] = { 0 };	//To print a chessboard, a two-dimensional array needs to be initialized to 0
	Init(board, ROW, COL);	//Initialize the chessboard, that is, initialize all chessboards as spaces.
	//Print chessboard
	PrintBoard(board, ROW, COL);
}

2. game.c file

//Print chessboard
void PrintBoard(char board[ROW][COL], int row, int col) { 
	int i = 0;
	int j = 0;
	for (i = 0; i < row; i++) {		//Row loop (outer layer)
		for (j = 0; j < col; j++) {		//Column loop (inner layer)
			printf(" %c ", board[i][j]);
			if (j < col - 1) {
				printf("|");	//No printing is required after the last column|
			}
		}
		printf("\n");		    //Wrap after printing
		if (i < col - 1) {		//Do not print under the last line___
			for (j = 0; j < col; j++) {
				printf("___");
				if (j < col - 1) {  
					printf("|");
				}
			}
		}
		printf("\n");//Wrap after printing
	}
}

The results are shown in the figure below:

That is: here is a set of data

5, Players play chess

1.test.c file

void game() {

	char board[ROW][COL] = { 0 };	//To print a chessboard, a two-dimensional array needs to be initialized to 0
	Init(board, ROW, COL);	//Initialize the chessboard, that is, initialize all chessboards as spaces.
	//Print chessboard
	PrintBoard(board, ROW, COL);
	//Players play chess with computers' * 'represents players and' # 'represents computers.
	while (1) {
		player_move(board, ROW, COL);//Players play chess
		PrintBoard(board, ROW, COL);//Continue printing after downloading
	}
}

2. game.c file

//Players play chess
void player_move(char board[ROW][COL], int row, int col) {
	int x = 0;	//x axis
	int y = 0;	//y-axis
	printf("Player input: ");
	while (1) {
		scanf("%d %d", &x, &y);	//Enter coordinates
		if ((x >= 1 && x <= row) && (y >= 1 && y <= col)) {	//Limit input range
			if (board[x - 1][y - 1] == ' ') {	//It is necessary to judge whether characters have been entered in this coordinate, otherwise '*' will be printed
				board[x - 1][y - 1] = '*';
				break;
			}
			else {
				printf("The coordinates you entered have been set. Please re-enter\n");
				break;	
			}
		}
		else {
			printf("The coordinates you entered are invalid. Please re-enter\n");
			break;
		}
	}
}

if (board[x - 1][y - 1] = '') is used to prevent this coordinate from being set.
The reasons for using x-1 and y-1 here are:

Therefore, it is necessary to subtract 1, and the operation result is:

6, Computer chess

1. test.c file

void game() {

	char board[ROW][COL] = { 0 };	//To print a chessboard, a two-dimensional array needs to be initialized to 0
	Init(board, ROW, COL);	//Initialize the chessboard, that is, initialize all chessboards as spaces.
	//Print chessboard
	PrintBoard(board, ROW, COL);
	//Players play chess with computers' * 'represents players and' # 'represents computers.
	while (1) {
		player_move(board, ROW, COL);//Players play chess
		PrintBoard(board, ROW, COL);//Continue printing after downloading
		computer_move(board, ROW, COL);//Computer chess
		PrintBoard(board, ROW, COL);//Continue printing after next
	}
}

2. game.c file

//Computer chess
void computer_move(char board[ROW][COL], int row, int col) {
	printf("Computer chess: \n");
	while (1) {		//Use the loop until the computer meets the input.
		int x = rand() % row;	//Number of generated 0 ~ 2
		int y = rand() % col;	//0~2
		if (board[x][y] == ' ') {
			board[x][y] = '#';
			break;
		}
	}
}

Here, the computer generates random numbers, and the rand function is used. When generating random numbers, the srand() function is required. srand((unsigned int)time(NULL)) is added to the test function in the test.c file; This statement.

The operation result is:

7, Judge whether to win or lose

1. test.c file

void game() {

	char board[ROW][COL] = { 0 };	//To print a chessboard, a two-dimensional array needs to be initialized to 0
	Init(board, ROW, COL);	//Initialize the chessboard, that is, initialize all chessboards as spaces.
	//Print chessboard
	PrintBoard(board, ROW, COL);
	//Players play chess with computers' * 'represents players and' # 'represents computers.
	/*
		If the player wins, it returns' * '
		If the computer wins, it returns' # '
		'M 'is returned in a draw
		The return character C does not end
	*/
	//Judge whether to win or lose
	char ret = 0;
	while (1) {
		//Players play chess
		player_move(board, ROW, COL);
		PrintBoard(board, ROW, COL);//Continue printing after downloading
		ret = is_win(board, ROW, COL);//Judge whether to win or lose every time.
		if (ret != 'C') {
			break; //Not equal to the end of character C description
		}
		//Computer chess
		computer_move(board, ROW, COL);
		PrintBoard(board, ROW, COL);//Continue printing after next
		ret = is_win(board, ROW, COL);//Judge whether to win or lose every time.
		if (ret != 'C') {
			break;
		}
	}
	if (ret == '*') {
		printf("Player wins\n");
	}
	else if (ret == '#') {
		printf("Computer win\n");
	}
	else {
		printf("it ends in a draw");
	}
}

2. game.c file

//Judge whether to win or lose
int is_full(char board[ROW][COL], int row, int col) {//Judge whether the chessboard is full. When it is full, the draw returns 1, and when it is not full, it returns 0
	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;
}

char is_win(char board[ROW][COL], int row, int col) {
	int i = 0;
	//Judge whether the number of rows is connected (three rows in total)
	for (i = 0; i < row; i++) {
		if ((board[i][0] == board[i][1] && board[i][1] == board[i][2]) && board[i][1] != ' ') {	//Exclude spaces
			return board[i][0];//Return this number, which may be * or #.
		}
	}
	//Judge whether the number of columns is connected (three columns in total)
	for (i = 0; i < col; i++) {
		if ((board[0][i] == board[1][i] && board[1][i] == board[2][i]) && board[1][i] != ' ') {	//Exclude spaces
			return board[1][i];	//Return this number, which may be * or #.
		}
	}
	//Judge diagonal
	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];
	}
	//it ends in a draw
	if (is_full(board, row, col) == 1) {  
		return 'M';
	}
	return 'C';
}

It is worth noting that players here will enter this is next time_ The win function judges and returns a character. The next chess game of the computer also judges and returns a character until it is divided into win or loss and draw.
Operation results:
Player wins:
Computer win:
it ends in a draw:

general act

1. test.c

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

void game() {

	char board[ROW][COL] = { 0 };	//To print a chessboard, a two-dimensional array needs to be initialized to 0
	Init(board, ROW, COL);	//Initialize the chessboard, that is, initialize all chessboards as spaces.
	//Print chessboard
	PrintBoard(board, ROW, COL);
	//Players play chess with computers' * 'represents players and' # 'represents computers.
	/*
		If the player wins, it returns' * '
		If the computer wins, it returns' # '
		'M 'is returned in a draw
		The return character C does not end
	*/
	//Judge whether to win or lose
	char ret = 0;
	while (1) {
		//Players play chess
		player_move(board, ROW, COL);
		PrintBoard(board, ROW, COL);//Continue printing after downloading
		ret = is_win(board, ROW, COL);//Judge whether to win or lose every time.
		if (ret != 'C') {
			break; //Not equal to the end of character C description
		}
		//Computer chess
		computer_move(board, ROW, COL);
		PrintBoard(board, ROW, COL);//Continue printing after next
		ret = is_win(board, ROW, COL);//Judge whether to win or lose every time.
		if (ret != 'C') {
			break;
		}
	}
	if (ret == '*') {
		printf("Player wins\n");
	}
	else if (ret == '#') {
		printf("Computer win\n");
	}
	else if (ret == 'M') {
		printf("it ends in a draw\n");
	}
}
void test() {
	srand((unsigned int)time(NULL));//time stamp
	int input = 0;
	do {
		menu();	//Select menu
		printf("Please select input 1/0: ");	//Choose to continue the game or exit
		scanf("%d", &input);
		switch (input) {
		case 1:					//If it is 1, enter the game
			game();
			break;
		case 0:
			printf("Exit the game\n");
			break;
		default:
			printf("The number you entered is not in the range, please re-enter\n");
			break;
		}
		printf("\n");
	} while (input);	//If input is 1, continue, if 0, exit the game, and re-enter others
}

int main() {
	test();
	return 0;
}

2. game.h

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROW 3
#define COL 3
void Init(char board[ROW][COL], int row, int col);//Initialize chessboard
void PrintBoard(char board[ROW][COL], int row, int col);//Print chessboard
void player_move(char board[ROW][COL], int row, int col);//Players play chess
void computer_move(char board[ROW][COL], int row, int col);//Players play chess
char is_win(char board[ROW][COL], int row, int col);//Judge whether to win or lose

3. game.c

#include "game.h"
//Initialize chessboard
void Init(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] = ' ';
		}
	}
}
//Print chessboard
void PrintBoard(char board[ROW][COL], int row, int col) {
	int i = 0;
	int j = 0;
	for (i = 0; i < row; i++) {		//Row loop (outer layer)
		for (j = 0; j < col; j++) {		//Column loop (inner layer)
			printf(" %c ", board[i][j]);
			if (j < col - 1) {
				printf("|");	//No printing is required after the last column|
			}
		}
		printf("\n");		    //Wrap after printing
		if (i < col - 1) {		//Do not print under the last line---
			for (j = 0; j < col; j++) {
				printf("___");
				if (j < col - 1) {
					printf("|");
				}
			}
		}
		printf("\n");
	}
}

//Players play chess
void player_move(char board[ROW][COL], int row, int col) {
	int x = 0;	//x axis
	int y = 0;	//y-axis
	printf("Players play chess: ");
	
	while (1) {
		scanf("%d %d", &x, &y);	//Enter coordinates
		if ((x >= 1 && x <= row) && (y >= 1 && y <= col)) {	//Limit input range
			if (board[x - 1][y - 1] == ' ') {	//It is necessary to judge whether characters have been entered in this coordinate, otherwise '*' will be printed
				board[x - 1][y - 1] = '*';
				break;
			}
			else {
				printf("The coordinates you entered have been set. Please re-enter\n");
			}
		}
		else {
			printf("The coordinates you entered are invalid. Please re-enter\n");
		}
	}
}

//Computer chess
void computer_move(char board[ROW][COL], int row, int col) {
	printf("Computer chess: \n");
	while (1) {		//Use the loop until the computer meets the input.
		int x = rand() % row;	//Number of generated 0 ~ 2
		int y = rand() % col;	//0~2
		if (board[x][y] == ' ') {
			board[x][y] = '#';
			break;
		}
	}
}

//Judge whether to win or lose
int is_full(char board[ROW][COL], int row, int col) {//Judge whether the chessboard is full. When it is full, the draw returns 1, and when it is not full, it returns 0
	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;
}
char is_win(char board[ROW][COL], int row, int col) {
	int i = 0;
	//Judge whether the number of rows is connected (three rows in total)
	for (i = 0; i < row; i++) {
		if ((board[i][0] == board[i][1] && board[i][1] == board[i][2]) && board[i][1] != ' ') {	//Exclude spaces
			return board[i][0];//Return this number, which may be * or #.
		}
	}
	//Judge whether the number of columns is connected (three columns in total)
	for (i = 0; i < col; i++) {
		if ((board[0][i] == board[1][i] && board[1][i] == board[2][i]) && board[1][i] != ' ') {	//Exclude spaces
			return board[1][i];//Return this number, which may be * or #.
		}
	}
	//Judge diagonal
	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];
	}
	//it ends in a draw
	if (is_full(board, row, col) == 1) {  
		return 'M';
	}
	//continue
	return 'C';
}

Well, today's Sanzi chess is finished. If you like it, you can praise it. In addition, if there are deficiencies, please point out them in time. Thank you.

Tags: C

Posted on Mon, 08 Nov 2021 16:59:43 -0500 by dingus