Using C/C + + to realize Sanzi chess

catalogue

1. Required tools

2. Implementation ideas:

3. Function introduction

(1) . menu printing:

(2) . printing chessboard:

(3) players play chess

(4) Computer chess

(5) I. judge the winner or loser:

4. Game implementation process

5. Source code:

1. Required tools

Xiaobian uses the VS2019 version

2. Implementation ideas:

(1) First of all, we know that to realize Sanzi chess on the computer, we need a chessboard that can play chess.

(2) We realize the basic process of Sanzi chess game. After playing chess, players go to the computer to play chess in such a cycle, and finally judge whether they win or lose (the key point is cycle).

(3) Therefore, we can know that the functional parts of the code we have written are: printing the selection menu, printing the chessboard, players playing chess, computer playing chess, and judging whether to win or lose.

(4) Among them, we should pay attention to several aspects: the relevant judgment of chess board placement in the part of players playing chess and computer playing chess, judge whether it can be placed, and judge whether to win or lose after the placement is completed.

3. Function introduction

(1) . menu printing:

The realization of this function is to print a selection menu on the screen to let players choose to play the game or exit the game.

(2) . printing chessboard:

Usually when we play Sanzi, the specification of the chessboard is similar to the form of Jiugong grid

According to the above printing results, we can see that this is to use a two-dimensional array to print the symbols of ',' - 'and' | 'on the screen

We know the general idea, so next we need to initialize the chessboard and print out the size of the chessboard with '' (space) using a two-dimensional array

Here's an explanation. The character type two-dimensional array char checkerboard[ROW][COL] in the parameters we passed in defines the size of the chessboard. The row and col in the function parameters are defined in the header file of the code as follows:

be careful:

The #pragma once in the first line is a commonly used C/C + + preprocessing instruction. As long as this preprocessing instruction is added at the beginning of the header file, the header file can be compiled only once.

As long as it is defined in the header file, the code of the program in other files as long as it contains the header file.

We can understand #define as a simple text replacement (more than that, of course!). It is more convenient to change the size of the chessboard later. In this way, when the compiler encounters row and col after definition, it will be the value you define

Then we'll print out the chessboard

We should pay attention to the effect that we need is not printed on the peripheral line, so we need to increase the restrictions such as the code 30, 38, 43 lines in the above graph, and the main line changing function of the old fellow iron.

(3) players play chess

Game player chess old fellow should think of a symbol "*" in the space, because we initialize the checkerboard are all spaces, so we can choose to replace the space in the chessboard to represent our game player's symbol.

The player is not a computer (the array subscript starts from 0), so the position corresponding to the coordinates entered by the player should be computer plus 1. If the player enters 1, the position of the computer array is 0.

When playing chess, we should also consider several situations, such as whether the position has been settled or whether the coordinates entered by the player will exceed the range (you can use the judgment statement)

(4) Computer chess

When playing chess by computer, we should consider how to make the computer generate a random number. We can use the rand() function. (old fellow can search the usage of Rand)

(5) I. judge the winner or loser:

Old fellow game player, we will encounter the situation of three player chess game: players win, computer wins, draws.

Player wins, computer wins: three of the same symbols are in the same row, column and diagonal.

Draw: the chessboard is filled with symbols

Therefore, our implementation idea can be: if the function returns' * ', the player will win, if the function returns' #', the computer will win, if the function returns' Q ', the game will be drawn, and if the function returns' C', the game will continue, and the player and the computer will continue to play chess

The function to judge whether the chessboard is full is implemented as follows:

4. Game implementation process

The implementation function of the game is named game(). In game(), what we need to pay attention to most is the process of playing the game. In the three-dimensional chess game, we should consider whether each step of the screen will be printed on the screen. We can consider using the while() loop to implement it.

5. Source code:

test. Part C:

#define _CRT_SECURE_NO_WARNINGS

#include "game.h"

//Print menu
meau()
{
	printf("**********************************\n");
	printf("**********    1.play    **********\n");
	printf("**********    0.exit    **********\n");
	printf("**********************************\n");

}

void game()
{
	//Implementation of Sanzi chess game
	char checkerboard[ROW][COL];//Chessboard array

	//Initialize the chessboard. Since you haven't played chess at the beginning, print all checkerboard s into spaces
	InitBoard(checkerboard,ROW,COL);

	//Print chessboard
	PrintBoard(checkerboard,ROW,COL);//When printing a chessboard, the essence is to print the contents of the array

	//Players play chess

	char result = 0;

	while (1) 
	{
		Player(checkerboard, ROW, COL);
		PrintBoard(checkerboard, ROW, COL);
		result = Win(checkerboard, ROW, COL);
		if(result != 'C')
		{
			break;
		}
		ComputerMove(checkerboard, ROW, COL);
		PrintBoard(checkerboard, ROW, COL);
		result = Win(checkerboard, ROW, COL);
		if(result != 'C')
		{
			break;
		}

	}

	//Judge whether to win or lose

	if(result == '*')
	{
		printf("Player wins\n");
	}
	else if(result == '#')
	{
		printf("Computer win\n");
	}
	else
	{
		printf("it ends in a draw");
	}

}

int main()
{
	int n = 0;//Option input
	srand((unsigned int)time(NULL));//srand() should be called before rand() is used, otherwise the random number generated by rand() is the same as the previous one every time
	do
	{
		meau();
		printf("Please select:");//Let users select options
		scanf("%d", &n);
		
		//Use the switch statement to control options
		switch (n)
		{
		case 1:
			game();
			break;
		case 0:
			printf("game over!\n");
			break;
		default:
			printf("Selection error\n");
			break;
		}
	} while (n);//n as a condition, when 0 is entered, the program will automatically jump out of the loop

	return 0;
}


Implementation of game() function:

#define _CRT_SECURE_NO_WARNINGS
#include "game.h"

//Initialize chessboard
void InitBoard(char checkerboard[ROW][COL], int row, int col)
{
	int i = 0;
	for(i = 0;i < row;i++)
	{
		int j = 0;
		for(j = 0;j < col;j++)
		{
			checkerboard[i][j] = ' ';
		}
	}

}

//Print chessboard
void PrintBoard(char checkerboard[ROW][COL], int row, int col)
{
	int i = 0;
	for(i = 0;i < row;i++)
	{
		//print data
		int j = 0;
		for (j = 0; j < col; j++)
		{
			printf(" %c ", checkerboard[i][j]);
			if (j < col - 1)
			{
				printf("|");//Print split rows for each column
			}
		}
		printf("\n");

			//Print split lines
			if(i < row - 1)
			{
				for (j = 0; j < col; j++) 
				{
					printf("---");
					if (j < col - 1)
					{
						printf("|");
					}
				}
			}
			printf("\n");
		
	}
}

//Players play chess
void Player(char checkerboard[ROW][COL], int row, int col)
{
	printf("Player walk:");
	int x = 0;
	int y = 0;
	while (1) 
	{
		printf("Please enter the coordinates:");
		scanf("%d %d", &x, &y);//Because the player starts from 1 and the player is not a computer, the subscript of x = 1 -- > array is 0
		if(x >= 1 && x <= row && y >= 1 && y <= col)
		{
			//We also need to consider whether the position of playing chess has been played
			if(checkerboard[x - 1][y - 1] == ' ')//In Boolean context, constant assignment should consider using "= ="
			{
				checkerboard[x - 1][y - 1] = '*';
				break;
			}
			else
			{
				printf("The coordinates are occupied. Please re-enter the new coordinates\n");
			}

		}
		else
		{
			printf("The coordinates entered by the player are out of range. Please re-enter the coordinates");
		}
	}
}

//Computer chess
void ComputerMove(char checkerboard[ROW][COL], int row, int col)
{
	int x = 0;
	int y = 0;
	printf("Computer walk:\n");

	while(1)
	{
		x = rand() % row;//Generate the x coordinate, use the random value module 3 generated by rand, and its value range is between 0-2
		y = rand() % col;//Generate y coordinate
		if (checkerboard[x][y] == ' ')
		{
			checkerboard[x][y] = '#';
			break;
		}
	}
}

//Judge whether the chessboard is full
int IsFull(char checkerboard[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(checkerboard[i][j] == ' ')
			{
				return 0;
			}
		}
	}
	return 1;
}
char Win(char checkerboard[ROW][COL], int row,int col)
{
	//that 's ok
	int i = 0;
	for(i = 0;i < row;i++)
	{
		if(checkerboard[i][0] == checkerboard[i][1] && checkerboard[i][1] == checkerboard[i][2] && checkerboard[i][1] != ' ')
		{
			return checkerboard[i][0];
		}
	}
	//column
	for(i = 0;i < col;i++)
	{
		if(checkerboard[0][i] == checkerboard[1][i] && checkerboard[1][i] == checkerboard[2][i] && checkerboard[1][i] != ' ')
		{
			return checkerboard[0][i];
		}
	}
	//diagonal
	if(checkerboard[0][0] == checkerboard[1][1] && checkerboard[1][1] == checkerboard[2][2] && checkerboard[1][1] != ' ')
	{
		return checkerboard[1][1];
	}
	if(checkerboard[0][2] == checkerboard[1][1] && checkerboard[1][1] == checkerboard[2][0] && checkerboard[1][1] != ' ')
	{
		return checkerboard[1][1];
	}
	//Judge the draw
	if(IsFull(checkerboard,row,col))
	{
		return 'Q';
	}
	//The game continues
	return 'C';
}

game.h header file contains:

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


#define ROW 3
#define COL 3

//Initialize chessboard
void InitBoard(char checkerboard[ROW][COL],int row,int col);//ROW can be omitted, but COL cannot

//Print chessboard
void PrintBoard(char checkerboard[ROW][COL], int row, int col);

//Players play chess
void Player(char checkerboard[ROW][COL], int row, int col);

//Computer chess
void ComputerMove(char checkerboard[ROW][COL], int row, int col);

//Judge whether to win or lose
char Win(char checkerboard[ROW][COL], int row, int col);

//Judge whether the chessboard is full
int Is_Full(char checkerboard[ROW][COL], int row, int col);

Added by beselabios on Sat, 01 Jan 2022 19:44:05 +0200