当前位置:网站首页>C language to achieve three chess (detailed explanation)

C language to achieve three chess (detailed explanation)

2022-06-21 14:55:00 Ceylan_

Catalog

What is Sanzi

Menu interface

️ Game menu

️ Realize the choice

Chessboard interface

️ Create a chessboard

️ Print chessboard

Chess playing interface

️ Players play chess

️ The computer plays chess

️ Random number function

Judge the outcome

️ Victory or defeat

️ It ends in a draw

Game functions

Code details

Daily golden sentence  

 

What is Sanzi

Sanzi chess is a traditional folk game , Also called Jiugong chess 、 Circle fork 、 A dragon 、 Tic tac toe chess, etc . Connect the diagonals of the square , Put three pieces on opposite sides in turn , Just walk your three pieces into a line , Even if the other party loses . however , There are many times when there is a draw . Now let's try to use C Language to realize the game .

Menu interface

️ Game menu

The game always needs an interface , Otherwise, I don't know what to do , adopt 【printf】 Function to realize the menu interface , Open the game and automatically jump out 1. Start the game 0. Quit the game .

void menu()
{
	printf("****************************\n");
	printf("*******  1. Start the game   *******\n");
	printf("*******  0. Quit the game   *******\n");
	printf("****************************\n");
}

️ Realize the choice

With the menu , The next step is to choose options , Here we need to consider the input error .

void choice()
{
	int num;
	do
	{
		menu();
		printf(" Please enter your options :");
		scanf("%d",&num);
		switch (num)
		{
			case(1):
				game(); break;
			case(0):
				printf(" Quit the game \n"); break;
			default:
				printf(" Input error , Little fool ~~\n");
			break;
		}
	}
	while(num);
}

Chessboard interface

️ Create a chessboard

Menu interface , The choices are complete , The most important board of Sanzi has not been established yet , We use a two-dimensional array to store chessboard information , And initialize the board of Sanzi chess , Initialize the chessboard to "  "( Space )

void InitBoard(char board[3][3])
{
    int i, j;
    for (i = 0; i < 3; i++)
    {
        for (j = 0; j < 3; j++)
        {
            board[i][j] = ' ';
        }
    }
}

️ Print chessboard

The information on the chessboard is not enough , The chessboard also needs boundaries , We know that the board of Sanzi chess is a nine palace grid , You can use ' | ' And ' --- ' To separate the nine palace chessboard .

void DisplayBoard(char board[3][3])
{
	int i = 0;
	int j = 0;
	for (i = 0; i < 3; i++)
	{
		for (j = 0; j < 3; j++)
		{
			printf(" %c ", board[i][j]);
			if (j < 2)
				printf("|");
		}
		printf("\n");
		if (i < 2 )
		{
			for (j = 0; j < 3; j++)
			{
				printf("---");
				if (j < 2)
					printf("|");
			}
		}
		printf("\n");
	}
}

Chess playing interface

️ Players play chess

With a chessboard , Next, it's time to realize the logic of playing chess , We need to enter a coordinate , Stored in a binary array . Array subscript is from 0 At the beginning , The subscript we enter is 1 At the beginning , therefore , Store information in advance -1, Ensure that the coordinate position is correct .

void Player_move(char board[3][3])
{
	int x, y;
	while (1)
	{
		printf(" Please select coordinates :\n");
		scanf("%d %d", &x, &y);
		if (x >= 1 && x <= 3 && y >= 1 && y <= 3)
		{
			if (board[x - 1][y - 1] == ' ')
			{
			board[x-1][y-1]='*'; break;
			}
			else
				printf(" Coordinates occupied , Lose again ~\n");
		}
		else
		{
			printf(" You entered it wrong ~ Cutie \n");
		}
	}
}

️ The computer plays chess

After we realize the logic of players playing chess , It's about to realize the logic of computer chess , The logic of the computer is to generate two random numbers , , respectively, %3, The result is two numbers that meet the requirements of two-dimensional array coordinates of Sanzi chess .

️ Random number function

Here we need two random numbers , have access to 【 rand() 】 function

Use rand() Function needs to reference 【#include<stdlib.h>】 The header file

By default 【 rand() 】 Function is not a true random function , It's a pseudo-random function . When in use, you need to call 【srand()】 function ,【srand()】 The function will be set for 【 rand() 】 The random number seed used by the function , Each seed corresponds to a set of random numbers generated in advance according to the algorithm ;

srand((unsigned) time(NULL));// Produce seeds

void ComputerMove(char board[3][3])
{
	int x = 0;
	int y = 0;
	printf(" The computer is here ~\n");
	
	while (1)
	{
		x = rand() % 3;
		y = rand() % 3;
		if (board[x][y] == ' ')
		{
			board[x][y] = 'o';
			break;
		}
	}
}

Judge the outcome

️ Victory or defeat

The next step is to judge the outcome , adopt for Loop through a two-dimensional array , If the characters in one line or one column are the same , Then return any of these characters , Diagonals are the same .

If the return is '*' The player wins , If the return is 'o' The computer wins , If the return is 'c' It's a draw .

char is_win(char board[3][3])
{
	int i = 0;
	for (i = 0; i < 3; i++)
	{
		if(board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][1] != ' ')
		return board[i][0];
	}
	// longitudinal 
	for (i = 0; i < 3; 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 a draw 
	if (1 == is_full(board))
	{
		return 'Q';
	}
	// continue 
	return 'C';
}

️ It ends in a draw

If the two-dimensional array is filled and none of the parties meets the winning conditions , That's a draw .

int is_full(char board[3][3])// Judgment of the draw 
{
	int i = 0;
	int j = 0;
	for (i = 0; i < 3; i++)
	{
		for (j = 0; j < 3; j++)
		{
 			if (board[i][j] == ' ')
			{
				return 0;
			}
		}
	}
	return 1;
}

Game functions

Now you have all the functions you need for the game , What we need to do is integrate them .

void game()
{
	InitBoard(board);
	// Print chessboard 
	DisplayBoard(board);
	// Players play chess 
	char ret = 0;
	while (1)
	{
		srand((unsigned)time(NULL));
		Player_move(board);
		DisplayBoard(board);
		ret = is_win(board);
		// Judgement of winning or losing 
		if (ret != 'C')
		{
			break;
		}
		ComputerMove(board);
		DisplayBoard(board);
		ret = is_win(board);
		if (ret != 'C')
		{
			break;
		}
	}
		 if (ret == '*')
		 {
			 printf(" You win !!!\n");
		 }
		 else if (ret == 'o')
		 {
			 printf(" The computer won !!!\n");
		 }
		 else
		 {
			 printf(" It ends in a draw !!!\n");
		 }
	
}

Code details

Here is the complete code , You can try to write it completely by yourself .

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
char board[3][3] = { 0 };
void game();
void choice();
void menu()
{
	printf("****************************\n");
	printf("*******  1. Start the game   *******\n");
	printf("*******  0. Quit the game   *******\n");
	printf("****************************\n");
}
void choice()
{
	int num;
	do
	{
		menu();
		printf(" Please enter start or exit :");
		scanf("%d",&num);
		switch (num)
		{
			case(1):
				game(); break;
			case(0):
				printf(" Quit the game \n"); break;
			default:
				printf(" Input error , Little fool ~~\n");
			break;
		}
	}
	while(num);
}

void InitBoard(char board[3][3])// Initialize array 
{
    int i, j;
    for (i = 0; i < 3; i++)
    {
        for (j = 0; j < 3; j++)
        {
            board[i][j] = ' ';
        }
    }
}
void DisplayBoard(char board[3][3])
{
	int i = 0;
	int j = 0;
	for (i = 0; i < 3; i++)
	{
		for (j = 0; j < 3; j++)
		{
			printf(" %c ", board[i][j]);
			if (j < 2)
				printf("|");
		}
		printf("\n");
		if (i < 2 )
		{
			for (j = 0; j < 3; j++)
			{
				printf("---");
				if (j < 2)
					printf("|");
			}
		}
		printf("\n");
	}
}
void Player_move(char board[3][3])
{
	int x, y;
	while (1)
	{
		printf(" Please select coordinates :\n");
		scanf("%d %d", &x, &y);
		if (x >= 1 && x <= 3 && y >= 1 && y <= 3)
		{
			if (board[x - 1][y - 1] == ' ')
			{
			board[x-1][y-1]='*'; break;
			}
			else
				printf(" Coordinates occupied , Enter it again ~\n");
		}
		else
		{
			printf(" You entered it wrong ~ Cutie \n");
		}
	}
}
void ComputerMove(char board[3][3])
{
	int x = 0;
	int y = 0;
	printf(" The computer is here ~\n");
	
	while (1)
	{
		x = rand() % 3;
		y = rand() % 3;
		if (board[x][y] == ' ')
		{
			board[x][y] = 'o';
			break;
		}
	}
}
int is_full(char board[3][3])// Judgment of the draw 
{
	int i = 0;
	int j = 0;
	for (i = 0; i < 3; i++)
	{
		for (j = 0; j < 3; j++)
		{
 			if (board[i][j] == ' ')
			{
				return 0;
			}
		}
	}
	return 1;
}
char is_win(char board[3][3])
{
	// When a player or computer has three lines 
	int i = 0;
	for (i = 0; i < 3; i++)
	{
		if(board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][1] != ' ')
		return board[i][0];
	}
	// longitudinal 
	for (i = 0; i < 3; 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 a draw 
	if (1 == is_full(board))
	{
		return 'Q';
	}
	// continue 
	return 'C';
}
void game()
{
	InitBoard(board);
	// Print chessboard 
	DisplayBoard(board);
	// Players play chess 
	char ret = 0;
	while (1)
	{
		srand((unsigned)time(NULL));
		Player_move(board);
		DisplayBoard(board);
		ret = is_win(board);
		// Judgement of winning or losing 
		if (ret != 'C')
		{
			break;
		}
		ComputerMove(board);
		DisplayBoard(board);
		ret = is_win(board);
		if (ret != 'C')
		{
			break;
		}
	}
		 if (ret == '*')
		 {
			 printf(" You win !!!\n");
		 }
		 else if (ret == 'o')
		 {
			 printf(" The computer won !!!\n");
		 }
		 else
		 {
			 printf(" It ends in a draw !!!\n");
		 }
	
}
int main()
{
	choice();
	return 0;
}

Daily golden sentence  

How hard do you work , How special it is , People only insist on making themselves better , It will really get better and better

I am not talented , Welcome to discuss in the comment area . If it helps you, please give the thumbs-up , Collection , Focus on Oh !

 

 

原网站

版权声明
本文为[Ceylan_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202221333592533.html