C language elementary three chess

insert image description here

initial file creation

First, we create three files: game.h, game.c, and test.c. As shown in the figure below,
insert image description here
in the game.h file, we refer to the header files, definition identifiers, and function definitions that need to be used. The other two files contain game.h The file is enough, that is, #include "game.h".
The game.h code is as follows:

#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define ROW 3
#define COL 3

void InitBoard(char board[ROW][COL]);//棋盘初始化
void DisplayBoard(char board[ROW][COL]);//打印棋盘
void PlayerMove(char board[ROW][COL]);//玩家下棋
void ComputerMove(char board[ROW][COL]);//电脑下棋
char IsWin(char board[ROW][COL]);//判断胜负

Among them, the two identifiers ROW and COL define the row and column size of the chessboard, which is convenient for us to reuse numbers when writing functions and using them, which has higher recognition and clearer expression.

main function file

code show as below:

#define _CRT_SECURE_NO_WARNINGS 1
#include"game.h"
void menu()
{
    
    
	printf("*****************************************\n");
	printf("********   1.play       0.exit   ********\n");
	printf("*****************************************\n");
}
void game()
{
    
    
	char board[ROW][COL] = {
    
     0 };
	InitBoard(board);
	DisplayBoard(board);
	char ret = 0;
	while (1)
	{
    
    
		PlayerMove(board);
		DisplayBoard(board);
		ret = IsWin(board);
		if (ret != 'c')
			break;
		printf("电脑下:\n");
		ComputerMove(board);
		DisplayBoard(board);
		ret = IsWin(board);
		if (ret != 'c')
			break;
	}
	if (ret == 'O')
		printf("玩家赢!!!\n");
	else if(ret == 'X')
		printf("电脑赢!!!\n");
	else
		printf("平局\n");
}
int main()
{
    
    
	int input = 0;
	srand((unsigned int)time(NULL));
	do
	{
    
    
		menu();
		printf("请选择:>");
		scanf("%d", &input);
		switch (input)
		{
    
    
		case 1:
			game();
			break;
		case 0:
			printf("退出游戏\n");
			break;
		default:
			printf("选择错误,重新选择!\n");
			break;
		}
	} while (input);
	return 0;
}

Specific ideas:
First of all, we look at the main function. The plastic input is created to allow players to choose game options later, and then the time seed of the random number is established, which will be used in the computer playing chess later. The following main body is the do...while loop. The first is the menu menu. This function contains the printing of the game options, and then the following scanf is used to record the input of the player’s game options, and then the statement is judged by the switch statement, enter 1 to enter the game, enter 0 to exit the game, Enter other to exit the game, let’s look at the game function again, first create a chessboard (its essence is a two-dimensional array), the value defaults to 0, it should be noted that when we play chess here, what is placed on the board, the board type is defined What, for example, here I put characters, then use the char type; then initialize, after initialization, the array is filled with spaces, then print the chessboard, create a character type ret, used to receive information for judging the outcome, and then about A loop of man-machine chess, as long as there is no result of victory or defeat, it will continue to loop; then the player plays chess, and then prints. At this time, there is a judgment. The 'c' here is the continuation information in the judgment function. That is to say, if the conditions for continuing to play are not met, it will jump out, and the computer is the same, the last paragraph is the judgment of the winner, if the received return value is 'O', then the player wins, if the received return value is 'X' ', then the computer wins, otherwise it is a draw, see the following function construction for specific implementation

Initialization of the chessboard (InitBoard)

From here, all the following functions are included in the game.c file code
as follows:

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

Specific ideas:
Here is to use two loops to initialize all elements in the chessboard to spaces

Print the chessboard (DisplayBoard)

code show as below:

void DisplayBoard(char board[ROW][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 < ROW - 1)
				printf("|");
		}
		printf("\n");
		if(i < ROW - 1)
		{
    
    
			for (j = 0; j < COL; j++)
			{
    
    
				printf("---");
				if (j < COL - 1)
					printf("|");
			}
			printf("\n");
		}
	}
}

Specific ideas:
First of all, let’s look at the picture below. In order to print the effect of the chessboard
insert image description here
, we divide the chessboard into two types and print it by row. The above writing method can change the size of the chessboard when needed without changing the function. First Let's see that the first line contains space pieces and vertical bars, there are 3 in total, and the last one has no vertical bars, so the printing cycle of the first line type is written out, and then the second line contains three horizontal bars plus a vertical bar Bar, the last one is not added, and it should be noted that the last line does not print this, so the second line type print cycle is also written, the principle of the entire print cycle is like this

Player Moves (PlayerMove)

code show as below:

void PlayerMove(char board[ROW][COL])
{
    
    
	int x = 0, y = 0;
	printf("玩家下棋:>\n");
	while (1)
	{
    
    
		printf("请输入下棋坐标,中间用空格隔开:>");
		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] = 'O';
				break;
			}
			else
				printf("此处被占用,请重新落子\n");
		}
		else
		{
    
    
			printf("坐标非法,请重新落子\n");
		}
	}
}

Specific ideas:
First, we create two xy variables to receive the coordinates that the player wants to place. The while loop here is established to prevent the player from entering the wrong coordinates. If the input is correct, it will jump out of the loop. The judgment condition here is based on ranks The standard of 1-3, so you need to subtract 1 from the two-dimensional array to find the correct position. The following judgment condition is empty to place the ball. If it is occupied or input illegal coordinates, it will re-enter the cycle and enter the coordinates. The player's move is the letter O.
As shown in the picture:
insert image description here

ComputerMove

code show as below:

void ComputerMove(char board[ROW][COL])
{
    
    

	while (1)
	{
    
    
		int x = rand()%ROW, y = rand()%COL;
			if (board[x][y] == ' ')
			{
    
    
				board[x][y] = 'X';
				break;
			}
	}
}

Specific ideas:
This random number with time as the seed is used here, and it is modeled on the row and column to get a random value of 0-2, and the judgment condition is also to drop if it is not empty. The computer moves the letter X.
As shown in the picture:
insert image description here

determine the outcome

code show as below:

char IsWin(char board[ROW][COL])
{
    
    
	int i = 0;
	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][0];
		}
	}
	for (i = 0; i < COL; i++)
	{
    
    
		if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[0][i] != ' ')//列
		{
    
    
			return board[0][i];
		}
	}
	if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != ' ')//对边
		return board[0][0];
	if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] != ' ')//对边
		return board[0][2];
	if (IsFull(board) == 1)
		return 'q';
	return 'c';
}

Specific ideas:
There are only three situations for the outcome of three-piece chess, that is, the same row, the same column, and the same diagonal. According to these situations, write a conditional statement that judges that you want to wait and is not empty, and then return any of the conditions. Just one element. Finally, determine whether it is full. If the board is full, return any value (not equal to 'c', 'c' is the condition for continuing), and finally the above conditions are not satisfied, then continue.
Here is another function code to determine whether the board is full or not
:

int IsFull(char board[ROW][COL])
{
    
    
	int i = 0,j = 0;
	for (i = 0; i < ROW; i++)
	{
    
    
		for (j = 0; j < COL; j++)
		{
    
    
			if (board[i][j] == ' ')
				return 0;
		}
	}
	return 1;
}

It is the traversal matching of the two-dimensional array. If there is an empty position, it returns 0, and if it does not match, it returns 1.
The outcome is judged as shown in the figure:
the draw
insert image description here
player wins and
insert image description here
the computer wins
insert image description here
. Because of the random number, it is actually very easy to win, but it is very difficult to lose, so the ultimate goal of this code to achieve the game is to let the computer win (manually funny)

all codes

game.h

#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define ROW 3
#define COL 3

void InitBoard(char board[ROW][COL]);
void DisplayBoard(char board[ROW][COL]);
void PlayerMove(char board[ROW][COL]);
void ComputerMove(char board[ROW][COL]);
char IsWin(char board[ROW][COL]);

game.c

#define _CRT_SECURE_NO_WARNINGS 1
#include"game.h"
void InitBoard(char board[ROW][COL])
{
    
    
	int i = 0;
	for (i = 0; i < ROW; i++)
	{
    
    
		int j = 0;
		for (j = 0; j < COL; j++)
		{
    
    
			board[i][j] = ' ';
		}
	}
}
void DisplayBoard(char board[ROW][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 < ROW - 1)
				printf("|");
		}
		printf("\n");
		if(i < ROW - 1)
		{
    
    
			for (j = 0; j < COL; j++)
			{
    
    
				printf("---");
				if (j < COL - 1)
					printf("|");
			}
			printf("\n");
		}
	}
}
void PlayerMove(char board[ROW][COL])
{
    
    
	int x = 0, y = 0;
	printf("玩家下棋:>\n");
	while (1)
	{
    
    
		printf("请输入下棋坐标,中间用空格隔开:>");
		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] = 'O';
				break;
			}
			else
				printf("此处被占用,请重新落子\n");
		}
		else
		{
    
    
			printf("坐标非法,请重新落子\n");
		}
	}
}
void ComputerMove(char board[ROW][COL])
{
    
    

	while (1)
	{
    
    
		int x = rand()%ROW, y = rand()%COL;
			if (board[x][y] == ' ')
			{
    
    
				board[x][y] = 'X';
				break;
			}
	}
}

int IsFull(char board[ROW][COL])
{
    
    
	int i = 0,j = 0;
	for (i = 0; i < ROW; i++)
	{
    
    
		for (j = 0; j < COL; j++)
		{
    
    
			if (board[i][j] == ' ')
				return 0;
		}
	}
	return 1;
}


char IsWin(char board[ROW][COL])
{
    
    
	int i = 0;
	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][0];
		}
	}
	for (i = 0; i < COL; i++)
	{
    
    
		if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[0][i] != ' ')
		{
    
    
			return board[0][i];
		}
	}
	if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != ' ')
		return board[0][0];
	if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] != ' ')
		return board[0][2];
	if (IsFull(board) == 1)
		return 'q';
	return 'c';
}

test.c

#define _CRT_SECURE_NO_WARNINGS 1
#include"game.h"
void menu()
{
    
    
	printf("*****************************************\n");
	printf("********   1.play       0.exit   ********\n");
	printf("*****************************************\n");
}
void game()
{
    
    
	char board[ROW][COL] = {
    
     0 };
	InitBoard(board);
	DisplayBoard(board);
	char ret = 0;
	while (1)
	{
    
    
		PlayerMove(board);
		DisplayBoard(board);
		ret = IsWin(board);
		if (ret != 'c')
			break;
		printf("电脑下:\n");
		ComputerMove(board);
		DisplayBoard(board);
		ret = IsWin(board);
		if (ret != 'c')
			break;
	}
	if (ret == 'O')
		printf("玩家赢!!!\n");
	else if(ret == 'X')
		printf("电脑赢!!!\n");
	else
		printf("平局\n");
}
int main()
{
    
    
	int input = 0;
	srand((unsigned int)time(NULL));
	do
	{
    
    
		menu();
		printf("请选择:>");
		scanf("%d", &input);
		switch (input)
		{
    
    
		case 1:
			game();
			break;
		case 0:
			printf("退出游戏\n");
			break;
		default:
			printf("选择错误,重新选择!\n");
			break;
		}
	} while (input);
	return 0;
}

epilogue

A large number of C language blogs have been updated recently, and I hope everyone will support them! ! !

Interested friends can pay attention to the author, if you think the content is good, please give a one-click triple link, you crab crab! ! !
It is not easy to make, please point out if there are any inaccuracies
Thank you for your visit, UU watching is the motivation for me to persevere.
With the catalyst of time, let us all become better people from each other! ! !
insert image description here

Guess you like

Origin blog.csdn.net/kingxzq/article/details/130551749