[C Language] Nanny-level backgammon tutorial

①Foreword

Backgammon, a traditional folk game, is also called Jiugong chess, circle chacha, one dragon and so on. Connect the diagonals of the squares, and place three chess pieces from both sides on the opposite sides. As long as your three chess pieces line up, the opponent loses. If two people have mastered the skills, then generally speaking, it is a draw. Its biggest advantage is that you can play this simple and interesting game anywhere you want.
Insert image description here

After knowing the rules of three-bang chess, how can we implement it in C language? Then take a look below!

② Game implementation steps

1. Create a menu interface and enter 1 or 0 to control "Start Game" or "End Game"
2. Initialize the chessboard
3. Print the chessboard
4. Players play chess and determine whether they need to continue playing chess (returning * means the player wins, Q means a draw, C means continue playing chess)
5. The computer plays chess , judge whether it is necessary to continue playing chess (return # means the computer wins, Q and C are the same as above)

1.menu menu interface


The menu interface is like the menu handed to you by the waiter in the restaurant. Choose 1 to start the game according to the content in the menu ; choose 0 to end the game

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

2. Implement multi-piece chess

If you only want the program to implement the function of three-piece chess, you can use 3 in the rows and columns of the board array in the figure below.
But if you want to implement multiple pieces of chess, such as backgammon, it is obviously not enough to just change the 3 in the rows and columns in the figure below.

	char board[3][3] = {
    
     0 };

Therefore, you might as well use the #define macro to define

#define ROW 3
#define COL 3

Benefits: It is convenient to modify the program. If you want to change the values ​​​​of ROW and COL, you only need to modify the values ​​​​of ROW and COL in the #define macro definition. There is no need to search and modify the full text.

3.Initialize the chessboard

Make the array store all spaces at the beginning , in preparation for printing the chessboard later

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

4. Print the chessboard

To print a 3*3 chessboard, you need to print 5 lines (in addition to the array stored in 3 lines, you also need two spacing lines, which are used as -|—|-), and print 5 columns (in addition to the array stored in 3 columns, you also need two Column separation column, use | separation)

Insert image description here

Print the columns first, regard 3 and 4 in the above picture as a group, and the number of columns separating the columns = COL-1

for (j = 0; j < col; j++)
		{
    
    
			printf(" %c ", board[i][j]);//%c两边有空格,更美观
			if (j < col - 1)
				printf("|");
		}

When printing a row, treat 1 and 2 as a group, and the number of rows divided = ROW-1

Complete code to print the chessboard :

void Display_board(char board[ROW][COL], int row, int col)
{
    
    
	int i, j;
	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");
	}
}

5. Players play chess

From the player's perspective, the rows and columns of the chessboard start from 1.
Therefore, the horizontal table x satisfies 1<=x<=row, and the vertical coordinate y satisfies 1<=y<=col.
But from the perspective of the array, the rows and rows start from 0
, so In the code implementation, the value of the input row and column should be subtracted by 1

Note:
If the input coordinates do not meet the above conditions or the input coordinates are already occupied, you will be prompted and you have to re-enter

void Player_move(char board[ROW][COL], int row, int col)
{
    
    
	int x, y;
	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");
	}
}

6. Computer chess

1. Computer chess does not require our manual input, but randomly generates a coordinate within a reasonable range (of course, you can also write an algorithm to let a smart computer play with you) 2. In order to generate a
random coordinate, we need two random Value, random value can be generated by rand() function
3. In order to use rand() function, use srand((unsighed int)time(NULL)) in the main function             . Note: srand() function only needs to be called once

void Computer_move(char board[ROW][COL], int row, int col)
{
    
    
	int x, y;
	while (1)
	{
    
    
		x = rand() % row;
		y = rand() % col;
		if (board[x][y] == ' ')
		{
    
    
			board[x][y] = '#';
			break;
		}
	}

}

7.Judge winning or losing

Player wins---- *
Computer wins---- #Tie
---- Q
continues---- C
Note : Because the return value is a character, char must be used to receive it

char Is_win(char board[ROW][COL], int row, int col)
{
    
    
	int i;
	//赢
	for (i = 0; i < row; i++)
	{
    
    
		//三横行
		if (board[i][0] == board[i][1] && board[i][0] == board[i][2] && board[i][0] != ' ')
			return board[i][0];
		//三竖列
		if (board[0][i] == board[1][i] && board[0][i] == board[2][i] && board[0][i] != ' ')
			return board[0][i];
	}

	//正对角线
	if (board[0][0] == board[1][1] && board[0][0] == board[2][2] && board[1][1] != ' ')
		return board[1][1];
	//反对角线
	if (board[2][0] == board[1][1] && board[2][0] == board[0][2] && board[1][1] != ' ')
		return board[1][1];

	//平局
	if (Is_full(board, ROW, COL))
		return 'Q';

	//继续
	return 'C';

}

8.Is full function implementation

Determine whether the chessboard is full, because the return value is 1 or 0, so use int to receive it.
If there are still spaces (that is, not full), return 0;
if it is full, return 1

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

③Result demonstration

1. Player wins

Insert image description here

2. Computer wins

Insert image description here

3. draw

Insert image description here

④Modular code implementation

1.text.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()
{
    
    
	char ret;
	char board[ROW][COL] = {
    
     0 };
	//棋盘初始化
	Initiate_board(board, ROW, COL);
	//打印棋盘
	Display_board(board, ROW, COL);
	//下棋
	while (1)
	{
    
    
		//玩家下棋
		Player_move(board, ROW, COL);
		Display_board(board, ROW, COL);
		ret = Is_win(board, ROW, COL);
		if (ret != 'C')
			break;
		//电脑下
		Computer_move(board, ROW, COL);
		Display_board(board, ROW, COL);
		ret = Is_win(board, ROW, COL);
		if (ret != 'C')
			break;
	}
	if (ret == '*')
		printf("玩家赢\n");
	else if (ret == '#')
		printf("电脑赢\n");
	else
		printf("平局\n");


}

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

2.game.h

#pragma once

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

#define ROW 3
#define COL 3

//棋盘初始化
void Initiate_board(char board[ROW][COL], int row, int col);
//打印棋盘
void Display_board(char board[ROW][COL], int row, int col);
//玩家下棋
void Player_move(char board[ROW][COL], int row, int col);
//电脑下
void Computer_move(char board[ROW][COL], int row, int col);
//判断输赢
char Is_win(char board[ROW][COL], int row, int col);

3.game.c

#define _CRT_SECURE_NO_WARNINGS 1

#include"game.h"

void Initiate_board(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 Display_board(char board[ROW][COL], int row, int col)
{
    
    
	int i, j;
	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 Player_move(char board[ROW][COL], int row, int col)
{
    
    
	int x, y;
	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 Computer_move(char board[ROW][COL], int row, int col)
{
    
    
	int x, y;
	while (1)
	{
    
    
		x = rand() % row;
		y = rand() % col;
		if (board[x][y] == ' ')
		{
    
    
			board[x][y] = '#';
			break;
		}
	}

}


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

//玩家赢:*
//电脑赢:#
//平局:  Q
//继续:  C
char Is_win(char board[ROW][COL], int row, int col)
{
    
    
	int i;
	//赢
	for (i = 0; i < row; i++)
	{
    
    
		//三横行
		if (board[i][0] == board[i][1] && board[i][0] == board[i][2] && board[i][0] != ' ')
			return board[i][0];
		//三竖列
		if (board[0][i] == board[1][i] && board[0][i] == board[2][i] && board[0][i] != ' ')
			return board[0][i];
	}

	//正对角线
	if (board[0][0] == board[1][1] && board[0][0] == board[2][2] && board[1][1] != ' ')
		return board[1][1];
	//反对角线
	if (board[2][0] == board[1][1] && board[2][0] == board[0][2] && board[1][1] != ' ')
		return board[1][1];

	//平局
	if (Is_full(board, ROW, COL))
		return 'Q';

	//继续
	return 'C';

}

Guess you like

Origin blog.csdn.net/qq_75000174/article/details/132008363