C Language Game - Chess

Through the browsing of these blogs, I believe that everyone's programming skills have reached a stage. We can not just write some mathematical games to practice programming ability. A lot of mathematical thinking and operations are really needed behind programming, but we still have to come out and face a real program, how to write it?

You must have played Gobang in everybody's life. No matter horizontal or vertical, if you win five pieces together, another player will guarantee his victory if he stops the other player from winning. Of course, our goal today is not to discuss how to play Gobang. Of course, what we learn to program is to do something related to programming. Our goal is to achieve this kind of small size.Game implementation, byC language, which is also the way every programmer must go in the training period. Through the continuous practice of these small programs to improve their logic and basic skills for some programs, Gobang, some tedious words, what we want to accomplish today is Gobang, if you can fully understand it, you can try the implementation of Gobang yourself, much the same, little the same, useless.Less to say, let's start.

We can all imagine that when you click into a game in the ordinary time, the first thing you see is the operation interface of the game. It prompts you to start or exit or some other settings for your own operation. Of course, this is also the same. We should design an operation interface at the beginning, not too beautiful. After all, we are not doing this, it can be understood.Because our game is so simple, we just need these: Start, quit. No other settings, no volume adjustment, but how do you do that? You can print these words directly using the printf function, but if you have a little bit of aesthetics, it might be better to add a few characters:

void game_interface()
{
    printf("******************************\n");
    printf("******1.play******0.exit******\n");
    printf("******************************\n");
    printf("Please select:");
}

This is just a demonstration. If you are a person who values the mainstay, you don't have to think about how to design better. Writing your code is your only task. Well, with the cover, according to the normal logic, we should go into the selection phase. You want to play or quit and give a choice. Then, anyway, you say to the computer that I want to play it without responding, type 1 runs the game, 0Exit the game, suppose you entered 1, what should you do after entering the game? Oh, yes, I need to receive this 1 first, you need an input variable, you need a scanf statement, then you can use a switch statement, and then branch up three case statements, corresponding to 1, 0, default, don't forget your friend, because we entered 1, so we want to enter the game, of course, swimThe cover of the game is a function we encapsulate, so can we encapsulate it as a function when you enter the game? Oak, first prompt the player that you have entered the game, then you can enter the function of your game. If you enter 0, you want to exit, first prompt that you have exited the game, then you can jump out with the break statement directly, exit the program, default
Used to receive numbers other than 1 and 0, if the input directly prompts for input errors, please re-enter, do you find this operation is actually a cycle, if I am an Internet addict, have no resistance to the game, have been wanting to play, or if I am illiterate, I do not recognize 1 and 0, I have been entering 2-9, the program can not run once and end right?So as long as the non-zero has to re-enter the selection, that is, to re-display the game cover for the player to choose, so this is a circular structure, we can use do while to achieve, remember its function, unlike the general cycle, whether the condition is true or not, it has to be executed once, just for our design, so it is roughly as follows:

void test()
{
    int input = 0;
    do
    {
        game_interface();
        scanf("%d\n", &input);
        switch (input)
        {
        case 1:
            printf("Game begins:\n");
            game_settings();
            break;
        case 0:
            printf("You have exited\n");
            break;
        default:
            printf("Error, please re-enter:");
            break;
        }
    } while (input);
}

Now you can run through your code to see if it works and exits properly after entering numbers. If you can, follow me. We see that case1 needs a function of the game. case0 and default don't need anything, because this is your choice. We just need to quit and let you choose again. Okay, now you have selected 1 to enter case1 and enterGame_settings()This has come to the core of our small game, 95% of which need to be completed by this function. Everyone usually plays chess on or off the board. Even if the conditions do not permit drawing strokes, they also need to draw a chess board. So, like drawing, a suitable paper can draw a surprising masterpiece, and a chess board is essential. Okay, let me ask you a question, such asWhat does a chess board look like if I cut it line by line? Chocolate? Put your imagination aside, even if it's really like chocolate, I'll say it's more like an array, a small grid together. Okay, now I don't cut it. There are a few words already in your mind: a two-dimensional array, yes, we finish the board by creating a two-dimensional array.
The size of the board can be specified by you. Of course, we are trios. We can also set 3*3. Of course, we do not recommend int board[3][3];This way of writing, because it is not dynamic, what is dynamic and what is static will be mentioned later, that is, one is alive and one is dead. If it is static and you want to change it later, you need to change all the numbers behind the board. Violent changes are not bad, not recommended. Don't forget the global variable, it will never come out and you will forget it.Two global variables, ROW COL, can be created to represent rows and columns, and the format is naturally changed to int board[ROW][COL];Another point is that the second time I put forward the concept of header file, you know stdio.h is a header file, stdlib.h is a header file, can I see this header file, where can you open your vs in disk, there is a file dedicated to the header file that has been specified in C language, for example, I want you toFind yours:

You can see that these files are all suffixed with.h. You can understand that these are headers. The purpose of headers is to tell vs that we need to use some of the functions in the header file to help me complete my code. Of course, these functions can also be specified by us, so we can also create headers, just like creating source files, by right-clicking on them.Header file, we can put the global variables, the header file we need and the declaration of some functions here, and then our test.c file just needs the header file we create to think everything we need is already there. Okay, let's continue with game_settings() Function, with the initial board, we need to initialize it, not make it all random values, right, so we can encapsulate an InitBoard() Functions, have you found that the previous functions have no design parameters, we just need them to help us get some tasks, so we don't need them, but when it comes to initializing the chess board, it will be different. At least we need to give the ingredients to others, so it can give us a chess board we want.
Pass the board and two global variables: void InitBoard(int board[ROW][COL],int ROW,int COL). Of course, don't forget to declare the function. Just declare the header file you created. Initialization is very simple. I first make it called the board of''before playing. I don't need to say you can also think that the initialization can be completed by nesting 20% for loops:

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

Initialization complete I want to see the effect of the board. In fact, this game board is meant to be displayed to players all the time, so we encapsulate a DispalyBoard ()Functions are used to display the board, of course, like the Initboard argument, the same statement we need is two for loops, but to make our board more like a board, some splitting lines are necessary, it's not like initializing the board''That way, affecting the board, it just prints to make the player look clearer. If only the split between each character works, we need to print'|'in rows and columns, i.e. when I and J <row-1 and <col-1, because the last line doesn't need to be printed, just split in the middle of the board.

void Displayboard(char board, int row, int col)
{
    int i = 0;
    int j = 0;
    for (i = 0; i < row; i++)
    {
        //Print a row of data
        printf(" %c ", board[i][j]);
        if (j < col - 1)
        {
            printf("|");
        }
        //Print Split Line
        if (i < row - 1)
        {
            for (j = 0; j < col; j++)
            {
                printf("---");
                if (j < col - 1)
                    printf("|");
            }
        }
    }
}


After that, we can see the whole look of the board. I can't wait to play on it. Let's design a function for both players to play chess. As a programmer, if you want to know that we are facing users, you can't design two real people to play chess in half a day. Of course, if you have a close friend who would like to play this game with you, please treasure it when I don't say so.It's a pity for him. Generally speaking, we design a live player and a computer player so that whenever you want your friend to play with it, you can have fun with it. We design PlayerMove() and ComputerMove(), which are familiar references and statements. (Because the game is spread around the board, the parameters only need these) Let's finish first.
Players go, first of all, to prompt the player how to go, enter the coordinates they want to play on the board, note that the sequence number of the array in the programmer's eyes is 1 less than normal, because the array starts from 0, of course, the player does not know, we can not tell him the knowledge of the array before he plays, so give up a bit. When the player enters the coordinates, if the coordinates are reasonable, that isThere are no chess pieces and the coordinates are in a reasonable range. Make sure to do -1 when you give a board, like this board[row-1][col-1]. If the coordinates are not legal, remind me in time. Note that this is not a cycle, it can't be played all the time. The computer player should hit the computer.

void PlayerMove(char board[ROW][COL], int row, int col)
{
    int x = 0;
    int y = 0;
    printf("Player Walks:\n");
    printf("Enter the coordinates of the piece you want to play:");
    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] = '*';
        }
        else
        {
            printf("Illegal coordinates\n");
        }
    }
    else
    {
        printf("Illegal coordinates, please re-enter\n");
    }
}

Then the settings of the computer player are also the same reference. If the same statement (don't want to say all) is made by the computer player, you don't have to enter it by yourself. You really want the computer to lose. Just auto-generate two random outputs, how to generate them? Introduce a new function: rand, show you its introduction

 

It doesn't matter if you don't understand it. I'm just using a time stamp to randomly generate a number, which is used in conjunction with the srand function. You can see that the return value of the srand function is void and the parameter is an unsigned, reshaped seed. If we want to use the time stamp to randomly generate numbers for us, we need a time function, that is, based on the current timeTo convert to a hexadecimal number, let's look at the passing of the time function and its return value

You can see that time returns a variable of type time_t, and the parameter is also a pointer to time_t. We do not pass a parameter, so we pass a NULL, because the null pointer is also a pointer, which is equivalent to 0 initialized by an integer variable, and then cast the return value of time to unsigned int.

srand((unsigned int)time(NULL));
//This sentence is added before the do while function in the test function

Of course, don't forget the header file, there are, remember to quote it in the header file that you created. According to the example below the picture of rand function that I sent above, you can use rand to generate random numbers, but how can you make it just within the acceptable range of my board? If it is a 10*10 board, the coordinates must be 0~9, if it is a 100*100, the coordinates must be 0~99Yes, we can use the generated numbers to redeem our ROW and COL, and get the numbers that are acceptable to the board. Then we can do something similar to LayerMove to judge, input, but the coordinates under the computer player are legal. If not legal, it only means that our programmer has written incorrectly, so we don't have to judge the range.

void ComputerMove(char board[ROW][COL], int row, int col)
{
	int x = 0;
	int y = 0;
	printf("Computer walk:\n");
	x = rand() % ROW;
	y = rand() % COL;
	while (1)
	{
		if (board[x][y] == ' ')
		{
			board[x][y] = '#';
			break;
		}
	}
}

The real person and the computer are finished, so we should decide which wins or loses. So we design another IsWin function with the same parameters. If the two diagonals are the same in the three horizontal and vertical lines, one side wins, so we need to end the game and declare one side wins. If the three lines are full but the characters are different, we will return to the first word of the line.Characters, columns are the same. If the diagonal is full, return the characters of [1][1]. If Q is full and C is not, then we need a function to determine if IsFull is full. If IsFull is full and needs to return 1 and 0, then we can judge if board[x][y] is equal to'#''*' one by one in the for loop.

int 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;
			else if (board[i][j] != ' ')
				return 1;
		}
	}
}
char Iswin(char board[ROW][COL], int row, int col)
{
	int i = 0;
	//Horizontal three lines
	for (i = 0; i < row; i++)
	{
		if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][1] != ' ')
		{
			return board[i][1];
		}
	}
	//Vertical Three Columns
	for (i = 0; i < col; i++)
	{
		if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[1][i] != ' ')
		{
			return board[1][i];
		}
	}
	//diagonal
	if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[1][1] != ' ')
		return board[1][1];
	if (board[2][0] == board[1][1] && board[1][1] == board[0][2] && board[1][1] != ' ')
		return board[1][1];
	//Is it a draw
	if (1 == Isfull(board, ROW, COL));
	{
		return 'Q';
	}
	return 'C';
}

Well, back to our game_settings() function

void game_settings()
{
	int ret = 0;
	//Define an array to hold some board information
	char board[ROW][COL] = { 0 };
	//Initialize the board
	Initboard(board, ROW, COL);
	//Print board
	Displayboard(board, ROW, COL);
	//Play chess
	while (1)
	{
		//Players play chess
		PlayerMove(board, ROW, COL);
		Displayboard(board, ROW, COL);
		//Determine whether a player wins
		ret = Iswin(board, ROW, COL);
		if (ret != 'C')
		{
			break;
		}
		//Computer Chess
		ComputerMove(board, ROW, COL);
		Displayboard(board, ROW, COL);
		//Judging whether a computer wins
		ret = Iswin(board, ROW, COL);
		if (ret != 'C')
		{
			break;
		}
	}
	if (ret == '*')
	{
		printf("Player wins");
	}
	else if (ret == '#')
	{
		printf("Computer wins");
	}
	else if (ret == 'Q')
	{
		printf("It ends in a draw");
	}
}

A simple Trio Game is almost here. You can comb your ideas and test them on the compiler. See you next time.

Keywords: C C++

Added by sgaron on Mon, 20 Sep 2021 01:38:05 +0300