Three chess (super detailed explanation + complete code source)

foreword

The implementation of three-brows in C language is an investigation of everyone's arrays, functions, loops and branches . Through this article, you will learn how to make a three-moon game. After a period of review, I believe you will be able to master the three-moon game** (full code of the three-moon game is attached at the end of the article).**
insert image description here

1. Rules of the game

Before designing the game, understand the basic rules of backgammon, and implement them in C language around the rules

1. Both the man and the machine take turns to place chess pieces in the grid, and the first to form a line of three chess pieces is considered a victory

2. If the chessboard is full of chess pieces and there is still no winner, it will be regarded as a draw
insert image description here

Second, the required documents

Three chess is not an easy code, we need to write separate files.
What is sub-file writing?

It is to divide our program code into multiple files, so that we will not put all the code in main.c, adopt the programming idea of ​​sub-modules, divide the functions, and put each function with different functions in one c file, then write a header file to encapsulate it into a callable function, call this encapsulated function in the main function, and compile it together when compiling

benefit:

a. Division of functional responsibilities
b. Convenient debugging
c. Concise main program

Let us see the specific operation as follows:
Create game.h in the header file ---- used to declare the function
Create game.c in the source file - function implementation / test.c - theme process
insert image description here

Third, create a menu

First create a menu to show the function of entering and exiting the game:

void menu()
{
    
    
	printf("**********************\n");
	printf("******  1.play  ******\n");
	printf("******  0.exit  ******\n");
	printf("**********************\n");
}

Use the do...while loop to realize the menu use, and the switch statement to select the menu

int main()
{
    
    
	int input = 0;
	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;
}

Fourth, the realization of the core content of the game

Implement the entire game in the game() function, first array the board


char board[ROW][COL];

1. Board initialization

Define row and column as 3 in game.h

#define ROW 3
#define COL 3

Declare the initialization function Initboard in game.h

//初始化棋盘
void Initboard(char board[ROW][COL], int row, int col);

Implement the initialization function in game.c to create three rows and three columns of spaces

void Initboard(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] = ' ';
		}
	}
}

Look forward to the initialization complete.

1. Chessboard display

After initializing the chessboard, you need to print the chessboard on the keyboard.
Declare the printed chessboard in the game. file

//打印棋盘
void Displayboard(char board[ROW][COL], int row, int col);

Implement the checkerboard printing function in the game.c file

void DisplayBoard(char board[ROW][COL], int row, int col)
{
    
    
	int i = 0;
	int j = 0;
	for (i = 0; i < row; i++)
	{
    
    
		//先打印数据
		printf(" %c | %c | %c \n", board[i][0], board[i][1], board[i][2]);

		//再打印分割行
		if(i<row-1)
			printf("---|---|---\n");
	}
}

The chessboard is printed

3. Players play chess

Declare the player's chess function in game.h

//玩家下棋
void Playermove(char board[ROW][COL], int row, int col);

Implement the player's chess function in game.h. The player's chess piece cannot be placed on the board, otherwise the coordinates are illegal to re-play, and the chess piece must be in a grid with no chess pieces, otherwise the coordinates are occupied and re-play.

void PlayerMove(char board[ROW][COL], int row, int col)
{
    
    
	int x = 0;
	int y = 0;
	printf("玩家下棋\n");

	while (1)
	{
    
    
		printf("请输入要下棋的坐标:>");
		scanf("%d %d", &x, &y);
		if (x >= 1 && x <= row && y >= 1 && y <= col)
		{
    
    
			if (board[x-1][y-1] == ' ')//数组下标从0开始所以横纵坐标各减一
			{
    
    
				board[x - 1][y - 1] = '*';
				break;
			}
			else
			{
    
    
				printf("该坐标被占有,请输入其他坐标\n");
			}
		}
		else
		{
    
    
			printf("坐标非法,请重新输入\n");
		}
	}
}

The player is finished playing chess.

4. Computer chess

Declare the computer chess function in game.h

//电脑下棋
void Computermove(char board[ROW][COL], int row, int col);

Realize computer chess function in game.c file. The random coordinate header file #include <stdlib.h> is required for the computer to play chess randomly, and the header file #include <time.h> is required for random number generation. Control the chess played by the computer on the chessboard and then judge whether the chess is played on an empty chessboard, or re-play, while realizes that the player plays the wrong chess piece and re-plays it until it is correct and exits the loop

void Computermove(char board[ROW][COL], int row, int col)
{
    
    
	printf("电脑开始下棋>\n");
	int x = 0;
	int y = 0;
	while (1)
	{
    
    
		x = rand() % row;
		y = rand() % col;
		if (board[x][y] == ' ')
		{
    
    
			board[x][y] = '#';
			break;
		}
	}
}

5. Judging the outcome of the game

Declare the outcome judgment function in game.h.

//判断输赢
>char IsWin(char board[ROW], int row, int col);

Realize the outcome judgment function in game.c. There are four types of results for each chess game: 1. The player wins 2. The computer wins 3. A draw 4. Continue the game,
the for loop realizes that the three points in the row and column are in a straight line, and if it is judged that the three points in the player or the computer are in a straight line, print '*' or '#'

char IsWin(char board[ROW][COL], int row, int 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] == board[i][0] && board[i][2] != ' ')//行连成线
		{
    
    
			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] == board[2][i] && board[0][i] != ' ')//列连成线
		{
    
    
			return board[i][0];
		}
	}
	if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] == board[2][2] && board[0][0] != ' ')//斜方连成线
	{
    
    
		return board[0][0];
	}
	if (board[2][0] == board[1][1] && board[1][1] == board[0][2] && board[0][2] == board[2][0] && board[1][1] != ' ')//斜方连成线
	{
    
    
		return board[1][1];
	}
	if (isFull(board, ROW, COL))
	{
    
    
		return 'Q';
	}
	return 'C';
}

The nested draw function is in game.h. If all the coordinates are occupied (the coordinates are not empty), the draw function returns true, and the winning function returns Q draw. If the coordinates are free, the draw function returns false, and returns C in the judgment function to continue the game

static 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;
		}
	}
	return 1;
}

6. The internal implementation of the game() function

Create an array char board[ROW][COL];, call the functions of initializing the board (Initboard(board, ROW, COL)) and printing the board (Displayboard(board, ROW, COL)), and the while loop realizes that the computer and the player play chess with each other ret accepts the result of winning or losing, and jumps out of the loop if it is not to continue the game (C). If the result is a player (*), the player wins, if the result is a computer (#), the computer wins, otherwise the result is a draw.

void game()
{
    
    
	int ret = 0;
	char board[ROW][COL];
	Initboard(board, ROW, COL);
	Displayboard(board, ROW, COL);
	while (1)
	{
    
    
		Playermove(board, ROW, COL);
		Displayboard(board, ROW, COL);
		ret = IsWin(board, ROW, COL);
		if (ret != 'C')
		{
    
    
			break;
		}
		Computermove(board, ROW, COL);
		Displayboard(board, ROW, COL);
		ret = IsWin(board, ROW, COL);
		if (ret != 'C')
		{
    
    
			break;
		}
	}
	if (ret == '*')
	{
    
    
		printf("玩家嬴\n");
	}
	else if (ret == '#')
	{
    
    
		printf("电脑嬴\n");
	}
	else
	{
    
    
		printf("平局\n");
	}
}

Fourth, the actual operation of the game

1. Run the program, the menu appears
insert image description here
1. Select 1 to start playing the game, and the chessboard appears
insert image description here
2. Enter the chess position and start playing chess:
insert image description here
3. If the chess piece does not fall on the empty position, play chess again
insert image description here
4. Three points in a straight line appear and win
insert image description here
5 if If the board is full, there will be a draw.
insert image description here
6. Choose 0 and exit the game
insert image description here

Full code:

game.h

#pragma once

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

#define ROW 3
#define COL 3


//初始化棋盘
void Initboard(char board[ROW][COL], int row, int col);
//打印棋盘
void Displayboard(char board[ROW][COL], int row, int col);
//玩家下棋
void Playermove(char board[ROW][COL], int row, int col);
//电脑下棋
void Computermove(char board[ROW][COL], int row, int col);
//判断输赢
char IsWin(char board[ROW], int row, int col);

game.c

#define _CRT_SECURE_NO_WARNINGS 1
#include"game.h"

void Initboard(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] = ' ';
		}
	}
}
void Displayboard(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++)
		{
    
    
			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");
	}
}
void Playermove(char board[ROW][COL], int row, int col)
{
    
    
	int x = 0;
	int y = 0;
	printf("玩家要下棋:\n");
	while (1)
	{
    
    
		printf("请输入下棋位置:");
		scanf("%d %d", &x, &y);
		if (x >= 1 && x <= row && y>=1 && y <= col)
		{
    
    
			if (board[x - 1][y - 1] == ' ')
			{
    
    
				board[x - 1][y - 1] = '*';
				break;//跳出循环
			}
			else
			{
    
    
				printf("所输入位置被占用,请输入其他坐标\n");
			}
		}
		else
		{
    
    
			printf("输错位置,请重新输入>\n");
		}
	}
}
void Computermove(char board[ROW][COL], int row, int col)
{
    
    
	printf("电脑开始下棋>\n");
	int x = 0;
	int y = 0;
	while (1)
	{
    
    
		x = rand() % row;
		y = rand() % col;
		if (board[x][y] == ' ')
		{
    
    
			board[x][y] = '#';
			break;
		}
	}
}
static 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;
		}
	}
	return 1;
}
char IsWin(char board[ROW][COL], int row, int 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] == board[i][0] && board[i][2] != ' ')
		{
    
    
			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] == board[2][i] && board[0][i] != ' ')
		{
    
    
			return board[i][0];
		}
	}
	if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] == board[2][2] && board[0][0] != ' ')
	{
    
    
		return board[0][0];
	}
	if (board[2][0] == board[1][1] && board[1][1] == board[0][2] && board[0][2] == board[2][0] && board[1][1] != ' ')
	{
    
    
		return board[1][1];
	}
	if (isFull(board, ROW, COL))
	{
    
    
		return 'Q';
	}
	return 'C';
}

test.c

#define _CRT_SECURE_NO_WARNINGS 1
#include"game.h"
//创建菜单
void menu()
{
    
    
	printf("**********************\n");
	printf("******  1.play  ******\n");
	printf("******  0.exit  ******\n");
	printf("**********************\n");
}
//创建游戏
void game()
{
    
    
	int ret = 0;
	char board[ROW][COL];
	Initboard(board, ROW, COL);
	Displayboard(board, ROW, COL);
	while (1)
	{
    
    
		Playermove(board, ROW, COL);
		Displayboard(board, ROW, COL);
		ret = IsWin(board, ROW, COL);
		if (ret != 'C')
		{
    
    
			break;
		}
		Computermove(board, ROW, COL);
		Displayboard(board, ROW, COL);
		ret = IsWin(board, ROW, COL);
		if (ret != 'C')
		{
    
    
			break;
		}
	}
	if (ret == '*')
	{
    
    
		printf("玩家嬴\n");
	}
	else if (ret == '#')
	{
    
    
		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;
}

This round of three-moon chess learning has come to an end. Detailed three-moon chess + complete code, read repeatedly, and keep coding. I believe you will win three-moon chess in the near future to expand more advanced codes. Looking forward to seeing you next time! ! !

Guess you like

Origin blog.csdn.net/2201_75642960/article/details/131946106