[C language] three piece chess game and multi piece chess (implementation process of nanny level)

πŸš€write in frontπŸš€ Β Β 

πŸ”Ž Hello everyone, I'm Ze En. I hope you can help you after reading it. Please correct the deficiencies! Joint learning and exchange πŸ”Ž
πŸ… 2021 blog Star Internet of things and embedded development top 5 → weekly list 43 → total list 3343 πŸ…
πŸ†” This article is launched by the original CSDN of # Ze En # πŸ’ If you need to reprint, please inform ⚠
πŸ“ Personal homepage: Beat soy sauce desu_ Ze En_CSDN blog
🎁 Welcome → like πŸ‘ + Collection ⭐ Email + message πŸ“ ​
πŸ“£ Series column: [C] Series_ Desu CSDN blog
βœ‰οΈ We are not on the stage of our choice, and the performance is not the script of our choice πŸ“©

catalogue

πŸš€write in frontπŸš€ Β Β 

β‘  Foreword

β‘‘ Modular programming

β‘’ Game thinking & Logic

β‘£ Implement game steps / processes

I create color function

II menu interface (menu)

III realize multi player chess

β…£ chessboard initialization steps

β…€ implementation steps of printing checkerboard format

Vi. steps for players to play chess

VII. Implementation steps of computer chess

β…§ judge the result of the game to achieve win or lose

IX. implementation process of Isfull() function

β‘€ Result demonstration

1, Player victory

2, Computer victory

3, Game draw

β‘₯ Modular code implementation

1,test.c

2,game.h

3,game.cΒ 

β‘  Foreword

Sanzi chess must have been played by everyone. If you haven't finished, you can also try to play. In this way, you will have a good idea for the transformation of the small game of writing Sanzi chess. Then this blog will introduce the specific steps of how to realize the sanziqi game.

β‘‘ Modular programming

Let's talk about modular programming before we realize the logic idea of Sanzi chess?

Traditional programming: all functions are placed in main In C, if more modules are used, there will be a lot of code in a file, which is not conducive to the organization and management of the code, but also affects the thinking of programmers.

Modular programming: put the codes of each module in different places c file, in h file provides the declaration of external callable functions, others When you want to use the code in the c file, you only need to #include the "XXX. h" file. The use of modular programming can greatly improve the readability, maintainability and portability of the code.

Traditional programming: all functions are placed in main In C, if more modules are used, there will be a lot of code in a file, which is not conducive to the organization and management of the code, but also affects the thinking of programmers.

Modular programming: put the codes of each module in different places c file, in h file provides the declaration of external callable functions, others When you want to use the code in the c file, you only need to #include the "XXX. h" file. The programmability and maintainability of code can be greatly improved!

In general: when you have more code, you can use modular programming to complete the program.  

β‘’ Game thinking & Logic

  1. Create a menu function to choose to enter the game and exit the game.
  2. First, initialize the chessboard.
  3. Then, print the chessboard. Note: be sure to initialize before printing the chessboard.
  4. Players play chess and print out the chessboard (players enter row and column coordinates for placement, 'x' = player placement)
  5. Judge whether the player wins and whether to continue the game. (the character 'c' means to continue the game and the character 'q' means to draw the game)
  6. Computer play chess (random position play chess, 'o' = computer play chess)
  7. There are three ways to judge the outcome! They are: player win, computer win, and draw.
  8. Then, return to step β‘  to select whether to enter the game and exit the game.

β‘£ Implement game steps / processes

I create color function

Corresponding value of foreground color ↓

Note: this code uses a lot of color functions.

0=black                8=greyγ€€γ€€
1=blue                9=Light blue        hexadecimal        γ€€γ€€                        
2=green                10=Light green        A        γ€€γ€€
3=Lake blue              11=Light green      Bγ€€
4=gules                twelve=Light red        Cγ€€γ€€
5=purple                thirteen=lavender        D        γ€€γ€€
6=yellow                14=canary yellow        E       γ€€γ€€
7=white                fifteen=Bright white        F
void color(short x)	
{
	if (x >= 0 && x <= 15)
		SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), x);	 
	else
		SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7);
}

The advantage of using color function is to make the program run more beautiful and bright. In fact, it has no practical effect. This is what we need to know.  

STD here_ OUTPUT_ Handle requires header file #include < windows h> Can only be used.

II menu interface (menu)

The menu interface function is actually like our interface, like the interface directory of the game and the menu in the restaurant. The same thing. This is a library function. We just need to reference it directly. The example code is as follows ↓

void menu()
{
	color(0);//Black black
	system("cls");	//Clear the screen
	color(10);
	printf("|----------Gobang game------------|\n");
	printf("|********************************|\n");
	printf("|β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…|\n");
	printf("|β˜…β˜…   1.Start 0.sign out       β˜…β˜…|\n");
	printf("|β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…|\n");
	printf("|x = game player -------------- o = computer|\n");
	printf("|--------------------------------|\n");
}

Note → a system("cls") is used here; A screen clearing effect is achieved. Only by adding this can you make all the interfaces in cmd black. Because we still have + color(0) on this clear screen command; This represents black.  

III realize multi player chess

#define ROW 3 / / line
#define COL 3 / / column

Benefits of using #define# macro definition here:

  1. It is convenient for the modification of the program. There is no need to modify the whole program, just modify the macro definition.
  2. Improve the operation efficiency of the program and make it more convenient for modularization.
  3. On the basis of Sanzi chess, the effect of multi player chess can be realized by changing the value of macro definition.

Our hypothesis: change the chessboard to row 4. as πŸ‘‡ As shown in:

 ​

β…£ chessboard initialization steps

At the beginning of the array, spaces are stored to achieve an implementation of initializing the chessboard in preparation for printing the chessboard.  

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

The row of real parameter group name can be omitted, but the column cannot be omitted. Lowercase (row, col) is the actual length of the received.  

β…€ implementation steps of printing checkerboard format

Printing a chessboard is essentially printing the contents of an array. As shown below πŸ‘‡:   

void Interface(char board[ROW][COL], int row, int col)
{
	int i = 0;
	for (i = 0; i < row; i++)
	{
		int j = 0;
		for (j = 0; j < col; j++)
		{

			printf(" %c ", board[i][j]);
			if (j < col-1)
			{
				printf("|");
			}
		}
		printf("\n");
		if (i < row - 1)
		{
			for (j = 0; j < col; j++)
			{
				printf("═══");
				if (j < col-1)
				{
					printf("|");
				}
			}
			printf("\n");
		}
	}
	printf("\n");
}

Print the effect picture of the chessboard, such as πŸ‘‡ As shown in:

​

Vi. steps for players to play chess

  1. Here, the player inputs the coordinates. When the player inputs the chess, it defines a static local variable when executing the code. When playing the game, you will be reminded once. Enter the first coordinate and remember to leave it blank! You can only enter the game once every time. Here, you mainly use static local variables to ensure that the last value will not be destroyed.
  2. From the player's point of view, rows and columns usually take 1 as the first, and our array subscript access starts from 0. Therefore, we want to print from 1 row and 1 column as the first one. In the program implementation, the value of the input coordinate is - 1.
  3. The player needs to set his son within the range of the chessboard. The player needs to set his son above the chessboard. If the entered coordinates are not satisfied, he needs to re-enter them.

  • 'x' = player drop.

void Player_play(char board[ROW][COL], int row, int col)
{
	printf("|--------|\n");
	printf("|Players play chess|\n");
	printf("|--------|\n");
	while (1)
	{
		int x = 0;
		int y = 0;
		static int j = 1;//Extend the life cycle,
		while (j)
		{
			color(8);
			printf("--------------------------\n");
			printf("[Enter the first coordinate and remember to leave it blank!]\n");
			printf("--------------------------\n");
			j--;
			break;
		}
		color(11);
		printf("<Please enter coordinates>:");
		scanf("%d %d", &x, &y);		
		//From the perspective of game players: rows and columns start with 1.
		if (x >= 1 && x <= row && y >= 1 && y <= col)
		{
			//However, the implementation process of the program starts with subscript 0.
			if (board[x - 1][y - 1] == ' ')
			{
				board[x - 1][y - 1] = 'x';
				break;
			}
			else
			{
				color(6);
				printf("|==============|\n");
				printf("|The coordinate is already occupied|\n");
				printf("|==============|\n");
			}
		}
		else
		{
			color(6);
			printf("|====================|\n");
			printf("|Illegal coordinates, please re-enter|\n");
			printf("|====================|\n");
		}
	}
}

VII. Implementation steps of computer chess

  1. srand((unsigned)time(NULL)); You can use it once in the main function!
  2. The random number generated by the rand() function is a pseudo-random number.
  3. The value under this computer is randomly placed on the chessboard. If you want a smart computer, you can write an algorithm to play with players.
  • 'o' = computer seat.

β…§ judge the result of the game to achieve win or lose

  • Player wins - 'x'
  • The computer won - 'o'
  • A draw - 'q'
  • Game continues - 'c'
  • Note: the value of the returned result is a character, so we need to use the string char to return
  • Idea: nothing more than judgment. Rows and columns are not equal to diagonals, but the spaces in front of them cannot be equal.  
char Iswin(char board[ROW][COL], int row, int col)
{
	int a = 0;
	int b = 0;
	//Judge three lines
	for (a = 0; a < row; a++)
	{
		if (board[a][0] == board[a][1] && board[a][1] == board[a][2] && board[a][0] != ' ')
		{
			return board[a][0];//Return to the computer to win or the player to win.
		}
	}
	//Judge three columns
	for (b = 0; b < col; b++)
	{
		if (board[0][b] == board[1][b] && board[1][b] == board[2][b] && board[0][b] != ' ')
		{
			return board[1][b];
		}
	}
	//Judge diagonal
	if (board[0][0] == board[1][1] && board[0][0] == board[2][2] && board[0][0] != ' ')
	{
		return board[1][1];
	}
	if (board[0][2] == board[1][1] && board[0][2] == board[2][0] && board[0][2] != ' ')
	{
		return board[1][1];
	}
	//Judge a draw: in fact, it depends on whether your chessboard is full or not. When all the squares of your chessboard are finished and there is no result, it will naturally be a draw.
	if (1 == Isfull(board, ROW, COL))
	{
		return 'q';
	}
	return 'c';
}

IX. implementation process of Isfull() function

The above function Isfull() is used to judge whether the game result is a draw.

int Isfull(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;//Dissatisfaction, there are more squares on the chessboard.
			}
		}
	}
	return 1;//When the chessboard is full, it returns a value of 1, that is, return 'q' (draw)
}

β‘€ Result demonstration

1, Player victory

​

2, Computer victory

​

3, Game draw

​

β‘₯ Modular code implementation

1,test.c

Test the logic of the game.

#include"game.h"

void menu()
{
	color(0);//Black black
	system("cls");	//Clear the screen
	color(10);
	printf("|----------Gobang game------------|\n");
	printf("|********************************|\n");
	printf("|β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…|\n");
	printf("|β˜…β˜…   1.Start 0.sign out       β˜…β˜…|\n");
	printf("|β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…β˜…|\n");
	printf("|x = game player -------------- o = computer|\n");
	printf("|--------------------------------|\n");
}
void game()
{
	printf(" ---------\n");
	printf("|PLAY GAME|\n");
	printf(" ---------\n");
	printf("\n");
	//Create a 2D array
	char board[ROW][COL] = { 0 };
	//Initialize chessboard
	Initialization(board, ROW, COL);
	//Print chessboard
	Interface(board, ROW, COL);

	int ret = 0;
	while (1)
	{
		Player_play(board, ROW, COL);//Players play chess
		Interface(board, ROW, COL);	 //Print chessboard
		//Judge the player to win the game
		ret = Iswin(board, ROW, COL);

		if (ret != 'c')//Determine whether the game continues
		{
			break;	   
		}
		Computer_play(board, ROW, COL);//Computer chess
		Interface(board, ROW, COL);	   //Print chessboard

		//Judge whether the computer wins the game
		ret = Iswin(board, ROW, COL);

		if (ret != 'c')
		{
			break;	   
		}
	}
	if (ret == 'x')
	{
		printf("Player wins!\n");
		printf("|-----------------------|\n");
		printf("|Rest 5 s Doodle doodle(/*·ω·)/|\n");
		printf("|-----------------------|\n");
		Sleep(5000);
	}
	else if (ret == 'o')
	{
		printf("Computer win!\n");
		printf("|-----------------------|\n");
		printf("|Rest 5 s Doodle doodle(/*·ω·)/|\n");
		printf("|-----------------------|\n");
		Sleep(5000);
	}
	else
	{
		printf("it ends in a draw!\n");
		printf("|-----------------------|\n");
		printf("|Rest 5 s Doodle doodle(/*·ω·)/|\n");
		printf("|-----------------------|\n");
		Sleep(5000);
	}
}
void test()
{
	int input = 0;
	do
	{
		menu();
		srand((unsigned int)time(NULL));
		color(5);
		printf("|════════════════|");
		printf("\n Please enter the number above:");
		color(11);
		scanf("%d", &input);
		switch (input)
		{
		case 1:
			game();
			break;
		case 0:
			printf("|════════|");
			printf("|Exit the game|");
			printf("|════════|");
			break;
		default:
			printf("|═════════════════════════════|\n");
			printf("|You will be fined 5 for your wrong input s Can't play(β†’_β†’)|\n");
			printf("|═════════════════════════════|\n");
			Sleep(5000);
		}
	} while (input);
}

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

2,game.h

About the function declaration contained in the game, the inclusion of symbol declaration header file and macro definition.

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdlib.h>
#include<Windows.h>
#include<stdio.h>
//ranks
#define ROW 3
#define COL 3

void color(short x);
void Initialization(char board[ROW][COL], int row, int col);
void Interface(char board[ROW][COL], int row, int col);
void Player_play(char baord[ROW][COL], int row, int col);
void Computer_play(char board[ROW][COL], int row, int col);
char Iswin(char board[ROW][COL], int row, int col);

3,game.cΒ 

Game and related function implementation.

#include"game.h"
//The custom function changes the color according to the parameters 
void color(short x)	
{
	if (x >= 0 && x <= 15)//Parameter color in the range of 0-15
		SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), x);	//There is only one parameter to change the font color 
	else//The default color is white
		SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7);
}
//Implementation steps of chessboard initialization
void Initialization(char board[ROW][COL], int row, int col)
{
	int i = 0;
	for (i = 0; i < row; i++)
	{
		int j = 0;
		for (j = 0; j < col; j++)
		{
			board[i][j] = ' ';
		}
	}
}
//Implementation steps of printing checkerboard format
void Interface(char board[ROW][COL], int row, int col)
{
	int i = 0;
	for (i = 0; i < row; i++)
	{
		int j = 0;
		for (j = 0; j < col; j++)
		{

			printf(" %c ", board[i][j]);
			if (j < col-1)
			{
				printf("|");
			}
		}
		printf("\n");
		if (i < row - 1)
		{
			for (j = 0; j < col; j++)
			{
				printf("═══");
				if (j < col-1)
				{
					printf("|");
				}
			}
			printf("\n");
		}
	}
	printf("\n");
}
//Implementation steps of players playing chess
void Player_play(char board[ROW][COL], int row, int col)
{
	printf("|--------|\n");
	printf("|Players play chess|\n");
	printf("|--------|\n");
	while (1)
	{
		int x = 0;
		int y = 0;
		static int j = 1;//Extend the life cycle,
		while (j)
		{
			color(8);
			printf("--------------------------\n");
			printf("[Enter the first coordinate and remember to leave it blank!]\n");
			printf("--------------------------\n");
			j--;
			break;
		}
		color(11);
		printf("<Please enter coordinates>:");
		scanf("%d %d", &x, &y);		
		//From the perspective of the person who finished the game: rows and columns start with 1.
		if (x >= 1 && x <= row && y >= 1 && y <= col)
		{
			//However, the implementation process of the program starts with subscript 0.
			if (board[x - 1][y - 1] == ' ')
			{
				board[x - 1][y - 1] = 'x';
				break;
			}
			else
			{
				color(6);
				printf("|==============|\n");
				printf("|The coordinate is already occupied|\n");
				printf("|==============|\n");
			}
		}
		else
		{
			color(6);
			printf("|====================|\n");
			printf("|Illegal coordinates, please re-enter|\n");
			printf("|====================|\n");
		}
	}
}
//Computer chess implementation steps
void Computer_play(char board[ROW][COL], int row, int col)
{
	int x = 0;
	int y = 0;
	color(9);
	printf("Computer walk/: >: \n");
	while (1)
	{
		x = rand() % row;
		y = rand() % col;
		if (board[x][y] == ' ')
		{
			board[x][y] = 'o';
			break;
		}
	}
}

int Isfull(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;//Dissatisfaction, there are more squares on the chessboard.
			}
		}
	}
	return 1;//When the chessboard is full, it returns a value of 1, that is, return 'q' (draw)
}
//Judge whether the game results are achieved or not
//Player wins - 'x'
//The computer won - 'o'
//A draw - 'q'
//Game continues - 'c'
//Note: the value of the returned result is a character, so we need to use the string char to return
//Idea: nothing more than judgment. Rows and columns are not equal to diagonals, but the spaces in front of them cannot be equal.
char Iswin(char board[ROW][COL], int row, int col)
{
	int a = 0;
	int b = 0;
	//Judge three lines
	for (a = 0; a < row; a++)
	{
		if (board[a][0] == board[a][1] && board[a][1] == board[a][2] && board[a][0] != ' ')
		{
			return board[a][0];//Return to the computer to win or the player to win.
		}
	}
	//Judge three columns
	for (b = 0; b < col; b++)
	{
		if (board[0][b] == board[1][b] && board[1][b] == board[2][b] && board[0][b] != ' ')
		{
			return board[1][b];
		}
	}
	//Judge diagonal
	if (board[0][0] == board[1][1] && board[0][0] == board[2][2] && board[0][0] != ' ')
	{
		return board[1][1];
	}
	if (board[0][2] == board[1][1] && board[0][2] == board[2][0] && board[0][2] != ' ')
	{
		return board[1][1];
	}
	//Judge a draw: in fact, it depends on whether your chessboard is full or not. When all the squares of your chessboard are finished and there is no result, it will naturally be a draw.
	if (1 == Isfull(board, ROW, COL))
	{
		return 'q';
	}
	return 'c';
}

Keywords: C Back-end

Added by bala_god on Wed, 09 Mar 2022 15:45:18 +0200