Entry-level C language game——implementing three-piece chess (detailed explanations with pictures and texts, the code can be copied)

I believe everyone has had the experience of playing back-and-forth with classmates in class. Have you ever thought about writing a back-and-forth game on a computer? Welcome to this blog, and let’s work with the blogger to implement a simple version of three-piece chess in C language!

1. Problem description

Use the learned C language knowledge to implement a simple three-piece chess game

2. Basic implementation process

Before we start typing code, let’s first clarify the basic logic of our coding:

1. Create a menu interface where you can choose to start or exit the game.
2. Create a three-piece chess board and initialize an empty chess board.
3. Print the chessboard.
4. The player makes a move (the player enters the row and column coordinates to make a move) and prints it. 'x' means the player makes a move.
5. The computer makes a move (a random position) and prints it. 'o' means the computer makes a move.
6. Determine the outcome (lose, win, draw), 'q' means draw.
7. Return to step 2 to continue execution.

3. Main implementation steps

3.1 Menu interface

int menu(){
    
    
	printf("-------------------------\n");
	printf("--------1.开始游戏--------\n");
	printf("--------0.退出游戏--------\n");
	printf("-------------------------\n");
	int input = 0;
	printf("请输入你的选择:");
	scanf("%d", &input);
	return input;
}

3.2 Create a chessboard

Because what we are implementing is three-piece chess, we print a 3*3 chessboard and use the char type to implement it.

#define MAX_ROW 3
#define MAX_COL 3
char chessBoard[MAX_ROW][MAX_COL] = {
    
     0 };

Note: 使用宏定义的原因:

1. Improve code readability, and make it easier to understand the meaning MAX_ROWwhen encountered in subsequent codes MAX_COL.
2. Improve scalability. If you want to modify the chessboard size in the future, code modification will be very convenient.

3.3 Chessboard initialization

We can just leave it blank

void init(char chessBoard[MAX_ROW][MAX_COL])
{
    
    
	for (int row = 0; row < MAX_ROW; row++)
	{
    
    
		for (int col = 0; col < MAX_COL; col++)
		{
    
    
			chessBoard[row][col] = ' ';
		}
	}
}

3.4 Print the chessboard

Note: We use the blank area to print the chessboard, so the chessboard we see can only be black with no clear dividing lines, so we need to add some appropriate symbols when printing the chessboard to make our pattern more beautiful (of course, Competent veterans can try to use the easyx() function to get rid of the black window in our little game), so we choose a more beautiful method to print. The specific implementation is as follows:

void print_chessBoard(char chessBoard[MAX_ROW][MAX_COL])
{
    
    
	printf("+---+---+---+\n");
	for (int row = 0; row <MAX_ROW; row++) 
	{
    
    
		printf("| %c | %c | %c |\n", chessBoard[row][0],
			chessBoard[row][1], chessBoard[row][2]);
		printf("+---+---+---+\n");
	}
}

Let’s look at the renderings. Isn’t it relatively beautiful?
Insert image description here
The chessboard is also ready, it’s time for us to play chess –>

3.5. Player moves

The player enters the row and column coordinates to indicate the coordinates of the move, and uses 'x' to indicate the player's move.

Notice:

1. The player's move needs to be within the scope of the chessboard.
2. Players must place stones in the empty space above the chessboard.
3. If the entered coordinates are not satisfactory, re-enter them.

void playerMove(char chessBoard[MAX_ROW][MAX_COL]){
    
    
	while (1)
	{
    
    
		int row = 0;
		int col = 0;
		printf("请输入坐标(row col):");
		scanf("%d %d", &row, &col);
		if (row < 1 || row >= MAX_ROW+1 || col < 1 || col >= MAX_COL+1)
		{
    
    
			printf("您的坐标不在合法范围内 [0, 2],请重新输入:\n");
			continue;
		}
		if (chessBoard[row][col] != ' ')
		{
    
    
			printf("您的坐标位置已经有子了!\n");
			continue;
		}
		chessBoard[row-1][col-1] = 'x';
		break;
	}
}

3.6 Computer moves (random)

We cannot complete AI intelligent chess playing just by getting started with C language knowledge. We can only complete our simple three-piece chess game through random moves.
The computer randomly generates row and column coordinates, and 'o' represents the computer's move.
Notice:

1. Use the time header file in the main function to use time as a random number seed to ensure that the obtained row and column coordinates are truly random.
2. The rest of the chess game is similar to how players play chess.

void computerMove(char chessBoard[MAX_ROW][MAX_COL])
{
    
    
	while (1)
	{
    
    
		int row = rand() % MAX_ROW;
		int col = rand() % MAX_COL;
		if (chessBoard[row][col] != ' ')
		{
    
    
			continue;
		}
		chessBoard[row][col] = 'o';
		break;
	}
}

At this time, both sides have already played chess, and we should judge whether there is a win or loss, or a draw.

3.7 Judgment of victory or defeat is a draw

We know that four situations will occur after each move, namely: the player wins, the computer wins, a draw, or continues.
The determination of victory or defeat is as follows:

1. Determine all rows
2. Determine all columns
3. Determine two diagonals

The determination of a tie is:

1. If any element in the array is ' ', then it is not full. If none of the elements are ' ', then it is full.
2. If the chessboard is full and there is no winner, it will be a draw.

int isFull(char chessBoard[MAX_ROW][MAX_COL])
{
    
    
	for (int row = 0; row < MAX_ROW; row++)
	{
    
    
		for (int col = 0; col < MAX_COL; col++)
		{
    
    
			if (chessBoard[row][col] == ' ')
			{
    
    
				return 0;
			}

		}
	}
	return 1;
}

char isWin(char chessBoard[MAX_ROW][MAX_COL])
{
    
    
	for (int row = 0; row < MAX_ROW; row++)
	 {
    
    
		if (chessBoard[row][0] != ' '
			&& chessBoard[row][0] == chessBoard[row][1]
			&& chessBoard[row][0] == chessBoard[row][2]) 
		{
    
    
			return chessBoard[row][0];
		}
	}
	for (int col = 0; col < MAX_COL; col++) 
	{
    
    
		if (chessBoard[0][col] != ' '
			&& chessBoard[0][col] == chessBoard[1][col]
			&& chessBoard[0][col] == chessBoard[2][col]) 
		{
    
    
			return chessBoard[0][col];
		}
	}
	
	if (chessBoard[0][0] != ' '
		&& chessBoard[0][0] == chessBoard[1][1]
		&& chessBoard[0][0] == chessBoard[2][2]) 
	{
    
    
		return chessBoard[0][0];
	}
	
	if (chessBoard[2][0] != ' '
		&& chessBoard[2][0] == chessBoard[1][1]
		&& chessBoard[2][0] == chessBoard[0][2]) 
	{
    
    
		return chessBoard[2][0];
	}
	
	if (isFull(chessBoard)) 
	{
    
    
		return 'q';
	}
	
	return ' ';
}

3.8 Game main function

We use a function to call other functions we need, as follows:

void game() {
    
    
	char chessBoard[MAX_ROW][MAX_COL] = {
    
     0 };
	init(chessBoard);
	char winner = ' ';
	while (1) {
    
    
		system("cls");
		print_chessBoard(chessBoard);
		playerMove(chessBoard);
		winner = isWin(chessBoard);
		if (winner != ' ') {
    
    
			break;
		}
		computerMove(chessBoard);
		winner = isWin(chessBoard);
		if (winner != ' ') {
    
    
			break;
		}
	}
	print_chessBoard(chessBoard);
	if (winner == 'x') {
    
    
		printf("恭喜您, 您赢了!\n");
	}
	else if (winner == 'o') {
    
    
		printf("哈哈,您连人工智障都下不过!\n");
	}
	else {
    
    
		printf("您只能和人工智障打平手!!\n");
	}
}

4. Result Demonstration

We do a set of random demonstrations, and the results are as follows:
Insert image description here

5. Overall code implementation

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_ROW 3
#define MAX_COL 3

//主菜单
int menu() {
    
    
	printf("-------------------------\n");
	printf("--------1.开始游戏--------\n");
	printf("--------0.退出游戏--------\n");
	printf("-------------------------\n");
	int input = 0;
	printf("请输入你的选择:");
	scanf("%d", &input);
	return input;
}

//初始化棋盘
void init(char chessBoard[MAX_ROW][MAX_COL])
{
    
    
	for (int row = 0; row < MAX_ROW; row++)
	{
    
    
		for (int col = 0; col < MAX_COL; col++)
		{
    
    
			chessBoard[row][col] = ' ';
		}
	}
}

//打印棋盘
void print_chessBoard(char chessBoard[MAX_ROW][MAX_COL])
{
    
    
	printf("+---+---+---+\n");
	for (int row = 0; row < MAX_ROW; row++)
	{
    
    
		printf("| %c | %c | %c |\n", chessBoard[row][0],
			chessBoard[row][1], chessBoard[row][2]);
		printf("+---+---+---+\n");
	}
}

//玩家落子
void playerMove(char chessBoard[MAX_ROW][MAX_COL]) {
    
    
	while (1) {
    
    
		int row = 0;
		int col = 0;
		printf("请输入坐标(row col):");
		scanf("%d %d", &row, &col);
		if (row < 1 || row >= MAX_ROW+1 || col < 1 || col >= MAX_COL+1) {
    
    
			printf("您的坐标不在合法范围内 [0, 2],请重新输入:\n");
			continue;
		}
		if (chessBoard[row-1][col-1] != ' ') {
    
    
			printf("您的坐标位置已经有子了!\n");
			continue;
		}
		chessBoard[row-1][col-1] = 'x';
		break;
	}
}

//电脑随机落子
void computerMove(char chessBoard[MAX_ROW][MAX_COL]) 
{
    
    
	while (1) 
	{
    
    
		int row = rand() % MAX_ROW;
		int col = rand() % MAX_COL;
		if (chessBoard[row][col] != ' ') 
		{
    
    
			continue;
		}
		chessBoard[row][col] = 'o';
		break;
	}
}

//判断落子后的四种情况
int isFull(char chessBoard[MAX_ROW][MAX_COL])
{
    
    
	for (int row = 0; row < MAX_ROW; row++)
	{
    
    
		for (int col = 0; col < MAX_COL; col++)
		{
    
    
			if (chessBoard[row][col] == ' ')
			{
    
    
				return 0;
			}

		}
	}
	return 1;
}
char isWin(char chessBoard[MAX_ROW][MAX_COL])
{
    
    
	for (int row = 0; row < MAX_ROW; row++)
	{
    
    
		if (chessBoard[row][0] != ' '
			&& chessBoard[row][0] == chessBoard[row][1]
			&& chessBoard[row][0] == chessBoard[row][2])
		{
    
    
			return chessBoard[row][0];
		}
	}
	for (int col = 0; col < MAX_COL; col++)
	{
    
    
		if (chessBoard[0][col] != ' '
			&& chessBoard[0][col] == chessBoard[1][col]
			&& chessBoard[0][col] == chessBoard[2][col])
		{
    
    
			return chessBoard[0][col];
		}
	}

	if (chessBoard[0][0] != ' '
		&& chessBoard[0][0] == chessBoard[1][1]
		&& chessBoard[0][0] == chessBoard[2][2])
	{
    
    
		return chessBoard[0][0];
	}

	if (chessBoard[2][0] != ' '
		&& chessBoard[2][0] == chessBoard[1][1]
		&& chessBoard[2][0] == chessBoard[0][2])
	{
    
    
		return chessBoard[2][0];
	}

	if (isFull(chessBoard))
	{
    
    
		return 'q';
	}

	return ' ';
}

//游戏实现总函数
void game() {
    
    
	char chessBoard[MAX_ROW][MAX_COL] = {
    
     0 };
	init(chessBoard);
	char winner = ' ';
	while (1) {
    
    
		system("cls");
		print_chessBoard(chessBoard);
		playerMove(chessBoard);
		winner = isWin(chessBoard);
		if (winner != ' ') {
    
    
			break;
		}
		computerMove(chessBoard);
		winner = isWin(chessBoard);
		if (winner != ' ') {
    
    
			break;
		}
	}
	print_chessBoard(chessBoard);
	if (winner == 'x') {
    
    
		printf("恭喜您, 您赢了!\n");
	}
	else if (winner == 'o') {
    
    
		printf("哈哈,您连人工智障都下不过!\n");
	}
	else {
    
    
		printf("您只能和人工智障打平手!!\n");
	}
}


int main()
{
    
    
	srand((unsigned int)time(0));
	while (1) {
    
    
		int input = menu();
		if (input == 1) {
    
    
			game();
		}
		else if (input == 0) {
    
    
			printf("退出游戏,GOODBYE!!!!!\n");
			break;
		}
		else {
    
    
			printf("输入错误!请重新输入!\n");
			continue;
		}
	}
	system("pause");
	return 0;
}

Summarize

This is how simple three-piece chess is implemented. Go and challenge our "artificial retardation". The blogger will update the implementation of minesweeper in the future. If you are interested, don't forget to give the blogger a three-in-a-row!

Guess you like

Origin blog.csdn.net/m0_65038072/article/details/127479006