Nanny level implements three-piece chess through C language

Article directory

    • Game introduction and analysis
    • Game implementation
      • 1. Game interface
        • Enter and exit the game interface
        • Mode selection interface
      • 2.Initialization
      • 3. Print the chessboard
      • 4. Game process
        • Two player mode
        • computer mode
      • 5. Determine win, loss or draw
    • All code display
    • Summarize

Game introduction and analysis

Introduction: This game is played on a 3*3 grid. Both parties draw a pattern on a grid at a time. When three identical patterns are connected into a line, the party with the pattern wins. There is another situation where When all 9 grids have been played but there are still no three identical patterns connected into a line, it is a draw. Everyone should have played this little game when they were children.

like:

analyze:
1. The first step to enter the game is to create the interface.
2. If this small game wants to implement a 3*3 chessboard, does it need to use a two-dimensional array?
3. When we want to use a two-dimensional array to make a chessboard, we need to initialize the two-dimensional array to a blank space, so that it will not affect the look and feel of the chessboard. At the same time, we use ‘ | ‘ and ‘- – – -‘ to make the chessboard Each grid is separated, so that the chessboard is successfully created.
4. After creating the chessboard, it’s time to play chess. We can enter coordinates to change the elements of the two-dimensional array and play chess in this way.
5. We need to set up two-player and computer mode
Let’s first analyze the two-player mode: Assume that Xiaoshuai and Xiaomei are playing, then one of them will play first, then the other, and continue until all 3*3 grids are cleared or one party wins, then the chess move is In the process, do we need to set up a function to determine whether we win. If no one wins, the grid on the chessboard is cleared. By judging this, we can know whether it is a draw.
Computer mode: If we want the computer to play chess, we need to set 2 random numbers for it (details will be explained later for setting the random numbers) to replace the coordinates. In this way, you take one step and the computer takes another step, thus achieving a battle with the computer.
Okay, that’s it for the analysis. Next, let’s implement the game.

Game implementation

1. We divide the function into three parts through multiple files. The first main file is to put the main function and some interfaces, the second is to put some modules for the main function implementation, and the third is to put some header files, definitions and the like.
2. It is recommended that when you implement one step, you should verify whether there are any errors before implementing the next module. I will complete it in modules below.

1. Game interface

Here we have set up the interface for entering the game at the beginning and the interface for selecting the mode.

Enter and exit the game interface

Should a game have an exit and start interface? Let’s start implementing it now. The game interface is very simple and crude to make. We just print it out directly through our printing function printf.
Code display:

 void jiemian(void) {<!-- -->//Interface 1
printf("********************************************** ********\
");
printf("********************************************** ********\
");
printf("******** 1 - Start game ********\
");
printf("******** 0 - Exit game ********\
");
printf("********************************************** ********\
");
printf("********************************************** ********\
");
}

Isn’t it very unpretentious?

Let’s print the results and take a look

Mode selection interface

This mode selection interface is the same as the advance and retreat game interface. It is printed out through our simple printf.
Code display:

void xuanze(void) {<!-- -->//Interface 2
printf("********************************************** ********\
");
printf("********************************************** ********\
");
printf("******** 2 - Two-player battle ********\
");
printf("******** 3 - PC player ********\
");
printf("********************************************** ********\
");
printf("********************************************** ********\
");
}

Print results:

At this point our interface is done. Doesn’t it seem simple? The next step is initialization.

2.Initialization

I have set up a 4*4 chessboard here, because then we can make the coordinates 1~3, and this setting is also conducive to the printing of the chessboard later. Because it is a two-dimensional array, we directly use a < strong>Nested loops to assign values to two-dimensional arrays
Code display:

void chushihua(char arr[kuan][chang], int x, int y) {<!-- -->//Use a loop to initialize the array with x and y ranging from 1 to 3 to spaces
for (int i = 1; i < x; i + + ) {<!-- -->
for (int j = 1; j < y; j + + ) {<!-- -->
arr[i][j] = ' ';
}
}
}

Because we want to control the coordinates between 1 and 3, we start initialization from subscript 1.
Next is our printing

3. Print the chessboard

The chessboard we print should be as beautiful as possible, right? We try to print the coordinates as well, such as:

But we can’t enter a horizontal line like the picture above, so we try to make it as similar as possible, such as:

This picture is a bit abstract, so can it be realized like this?
Let’s analyze the code:

 void dayin(char arr[kuan][chang], int x, int y) {<!-- -->
for (int i = 0; i < x; i + + ) {<!-- -->
printf("%-2d", i);//When printing, print the x coordinate
for (int j = 1; j < y; j + + ) {<!-- -->
if (i == 0) {<!-- -->//The first line prints the y coordinate
printf("%-2d", j);
}
else {<!-- -->//
printf("%c", arr[i][j]);//Print spaces
if(j<y-1)//Control |’ to separate each grid and ensure that only the first two are printed
printf("|");
}
\t\t
}
\t\t
if (i != 0 & amp; & amp; i != x - 1) {<!-- -->//Print the following "-----" to separate each line, and control to print only the middle two OK
printf("\
");//New line and then print
printf(" - - - - ");
}
printf("\
");//Newline
}
}

First print out the coordinates of the column through i=0, and then print an i after each big loop, so that the rows are printed. We only need two ‘|’ for each column, so it is not necessary when j=3 Printed, printing will affect the appearance, and the same is true for lines. As long as there are two “- – – -“, there is no need to print when i=3. Another point to pay attention to in this code is the position of the line break. Be sure to put it in the right place

Let’s take a look at the results:

Printed out according to our ideas
The next step is the game process

4. Game process

Our idea here is that after one side has played, it will go to the other side until one side wins, or the number of grids on the chessboard is filled up and the result is a draw.

Add a library function here, system(“cls”), the header file is: #include//Clear screen function header file, its function is to clear the screen content, we will use this function during the game Putting it in the right position can improve the game experience. For example, after each step, clear the previous one and print out the current one until the next clearing.

Double mode

We first set a control variable te=3*3, and then implement it through a while loop. When te==0 or one side wins, the loop will be broken. The first step is to make a move for side A and then make a judgment (will be discussed below) Explain the judgment code), go to square B and then make a judgment. Every time te is subtracted by 1.
Code (already detailed comments):

void shuangren(char arr[kuan][chang]) {<!-- -->//Double mode
int te = (kuan-1) * (chang-1);//Find the number of all grids--9
while (te != 0) {<!-- -->//Tie when looping te=0
int x = 0,y=0;
printf("A( + ):");//A goes first
scanf("%d %d", & amp;x, & amp;y);
system("cls");
arr[x][y] = ' + ';//' + ' represents the flag
int r = panduan(arr);//make judgment
if (r == 1) {<!-- -->//return 1, success, break
printf("Congratulations to A on winning\
");
dayin(arr, kuan, chang);//Print the final chessboard to see
break;
}
else {<!-- -->
dayin(arr, kuan, chang);//Print the current board to continue the game
te--;//te minus 1
}
if (te >0) {<!-- -->//When te==0, it means the chessboard is full, stop
printf("B(-):");
scanf("%d %d", & amp;x, & amp;y);
system("cls");
arr[x][y] = '-';
r = panduan(arr);
if (r == 1) {<!-- -->//return 1, success, break
printf("Congratulations B on winning\
");
dayin(arr, kuan, chang);//Print the final chessboard to see
break;
}
else {<!-- -->
dayin(arr, kuan, chang);
te--;
}
}
}
if(te==0)//When te==0, it means there is a winner for each share
printf("It's a draw\
");
jiemian();//Print the game interface to see if the game is played
}

Here A>> + ’,B>>’ – ’

Computer mode

Before talking about the computer mode, let’s first understand how to set random numbers on the computer.
**Our range here is 1-100;** Three library functions are needed to implement random numbers:
The C language provides a function called rand. This function can generate random numbers. The function prototype is as follows:
1 int rand (void);
The rand function will return a pseudo-random number. The range of this random number is between 0 and RAND_MAX. The value of RAND_MAX is
It depends on the implementation of the compiler, but it is 32767 on some compilers.
The use of rand function needs to include the following header files: stdlib.h
Then we test the rand function, which is adjusted multiple times to produce 5 random numbers:

**#include <stdio.h>
#include <stdlib.h>
int main()
{<!-- -->
 printf("%d\
", rand());
 printf("%d\
", rand());
 printf("%d\
", rand());
 printf("%d\
", rand());
 printf("%d\
", rand());
 return 0;**
}


The results of running this twice are the same (you can try it yourself, no matter how many times, the results are the same)
We can see that although the 5 numbers produced in this operation are relatively random, the result of the next operation program is different from the previous one.
It looks like this, which means there is something wrong.
If we understand it more deeply, it is not difficult to find that in fact, the random numbers generated by the rand function are pseudo-random. The pseudo-random numbers are not real random numbers, but random numbers generated through a certain algorithm. A true random number means that there is no way to predict what the next value will be. The rand function is a random number generated by calculating a reference value called “seed”.
The reason why the sequence of random numbers produced by the previous program is the same is because the default type of random numbers generated by the rand function is 1.
If you want to generate different random numbers, you must make the seeds change.
1.2 srand
C language provides a function called srand to initialize the random number generator. The prototype of srand is as follows:
1 void srand (unsigned int seed);
In the program, adjust the srand function beforethe rand function. Set the seed when the rand function generates random numbers through the parameter seed of the srand function. As long as the seed is changing, The random number sequence generated changes each time.
That is to say, if the seed given to srand is random, rand can generate random numbers; when generating random numbers, two random numbers are needed, which is contradictory.
1.3 time
In programs, we generally use the time when the program is running as a seed, because time is changing all the time.
In C language, there is a function called time, which can obtain this time. The time function prototype is as follows:
1 time_t time (time_t timer);*
The time function will return the current calendar time. In fact, it returns the time between 1:10:00:00:00 in 1970 and the current program running time.
Difference, unit is seconds. The returned type is time_t type. The time_t type is essentially a 32-bit or 64-bit integer type.
type.
If the parameter timer of the time function is a ?NULL pointer, the function will also put the returned difference value in the memory pointed to by timer.
Take it back.
If timer is NULL, only the difference in time is returned. The time difference returned by the time function is also called: timestamp.
When using the time function, you need to include the header file: time.h
If we just want the time function to return the timestamp, we can write like this:
1 time(NULL);//Calling the time function to return the timestamp, this does not receive the return value
Then we can rewrite the code that generates random numbers as follows:

**#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{<!-- -->
`

``
 //Make the return value of the time function set?
 //Because the parameter of srand is of unsigned int type, we cast the return value of the time function to type conversion



 srand((unsigned int)time(NULL));
 printf("%d\
", rand());
 printf("%d\
", rand());
 printf("%d\
", rand());
 printf("%d\
", rand());
 printf("%d\
", rand());
 return 0;**

Run it several times and see if your luck is different each time.
The result of the first operation

The result of the first operation

(Note: The screenshot is just the result of the program running at that time, your running result may not be the same as this)
The srand function does not need to be adjusted frequently. It is enough to adjust it once in each running program.
The range we need here is 1~3. Think about it, is the remainder of any number divided by 3 in the range 0~2? Then if we add 1 on this basis, it will be realized.
Analysis of the computer mode: The process is the same as that of the two-player mode, but the computer plays chess unconsciously. If we input the coordinates through the random number setting method above, it may result in playing the same position twice or more, so we have to Improvements in the two-player mode. If the computer is playing chess, it will make a judgment. If it is a space, it can be played. If it is not, the random number will be reset.
Code display:

void diannao(char arr[kuan][chang]) {<!-- -->//Computer battle
int te = (kuan - 1) * (chang - 1);//Find the number of all grids--9
while (te != 0) {<!-- -->//I play first, the process is the same as for two people
int x = 0, y = 0;
printf("A( + ):");
scanf("%d %d", & amp;x, & amp;y);
system("cls");
arr[x][y] = ' + ';
int r = panduan(arr);
if (r == 1) {<!-- -->
printf("Congratulations to A on winning\
");
dayin(arr, kuan, chang);
break;
}
else {<!-- -->
dayin(arr, kuan, chang);
te--;
}
if (te > 0) {<!-- -->
printf("B(-):");
do {<!-- -->//Control the computer to play chess in the space
x = rand() % 3 + 1;//Random number (%3 + 1 controls this number between 1 and 3)
y = rand() % 3 + 1;
} while (arr[x][y] != ' ');//The place under control is a space
system("cls");//The following process is the same as the above
arr[x][y] = '-';
r = panduan(arr);
if (r == 1) {<!-- -->
printf("Congratulations B on winning\
");
dayin(arr, kuan, chang);
break;
}
else {<!-- -->
dayin(arr, kuan, chang);
te--;
}
}
}
if (te == 0)
printf("It's a draw\
");
jiemian();
}

Okay, now comes the last step, how to judge whether it’s victory or not?

5. Determine win, loss or draw

We observe that the chessboard can be divided into three categories: rows, columns, and diagonals.
For rows, use a loop to control the rows, and then list the columns (1, 2, 3) to see if they are equal and not spaces.
For columns, use a loop to control the rows, and then list the rows (1, 2, 3) to see if they are equal and not spaces.
Then just list the remaining two diagonals directly.
Look directly at the code:

int panduan(char arr[kuan][chang]) {<!-- -->
//Return 1 for success
\t//OK
for (int i = 1; i < kuan; i + + ) {<!-- -->//Control x unchanged, traverse y, if they are all the same and not spaces
if (arr[i][1] == arr[i][2] & amp; & amp; arr[i][2] == arr[i][3] & amp; & amp; arr[i] [1] != ' ')
return 1;
}
\t//List
for (int i = 1; i < chang; i + + ) {<!-- -->//Control y unchanged, traverse x, if they are the same and not spaces
if (arr[1][i] == arr[2][i] & amp; & amp; arr[2][i] == arr[3][i] & amp; & amp; arr[1] [i] != ' ')
return 1;
}
\t//Diagonal
if (arr[1][1] == arr[2][2] & amp; & amp; arr[2][2] == arr[3][3] & amp; & amp; arr[1] [1] != ' ')//List them all directly
return 1;
if (arr[3][1] == arr[2][2] & amp; & amp; arr[2][2] == arr[1][3] & amp; & amp; arr[2] [2] != ' ')
return 1;
//If neither returns, -1 is returned, which means it has not been successful yet.
return -1;
}

Here, 1 is returned for success, and -1 is returned for failure.

See how it goes

The game process is fine

All code display

fu.h

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<windows.h>//Clear screen function header file
#include<stdlib.h>//Function header file for random numbers
#include<time.h>//time() header file
#define chang 4//Expand the chessboard a little so that the range of x and y is 1~3
#define kuan 4//
void jiemian(void);//Interface 1
void xuanze(void);//Interface 2
void chushihua(char arr[kuan][chang], int x, int y);//Initialization
void dayin(char arr[kuan][chang], int x, int y);//print
void shuangren(char arr[kuan][chang]);//Double mode
int panduan(char arr[kuan][chang]);//Judgement
void diannao(char arr[kuan][chang]);//Computer battle

zhu.c

#define _CRT_SECURE_NO_WARNINGS
#include"fu.h"
void jiemian(void) {//Interface 1
printf("********************************************** ********\
");
printf("********************************************** ********\
");
printf("******** 1 - Start game ********\
");
printf("******** 0 - Exit game ********\
");
printf("********************************************** ********\
");
printf("********************************************** ********\
");
}
void xuanze(void) {<!-- -->//Interface 2
printf("********************************************** ********\
");
printf("********************************************** ********\
");
printf("******** 2 - Two-player battle ********\
");
printf("******** 3 - PC player ********\
");
printf("********************************************** ********\
");
printf("********************************************** ********\
");
}
void geme(void) {
char arr[kuan][chang];//two-dimensional array
chushihua(arr,kuan,chang);//Initialize the array
int n=0;
xuanze();
printf("Please enter:");
scanf("%d", & amp;n);//Select
while (n > 3 || n < 2) {
printf("Input error, please re-enter:");
scanf("%d", & amp;n);//Select
}
system("cls");//clear screen
if (n == 2) {//Double mode
dayin(arr, kuan, chang);//Print the initialized chessboard first
shuangren(arr);//Start the game
}
else if (n == 3)//Computer mode
{
dayin(arr, kuan, chang); //Print the initialized chessboard first
diannao(arr);//Start the game
}
}
int main() {
int i;
srand((unsigned int)time(NULL));//Set the seed of random number
jiemian();//Print interface 1
do {//Select
printf("Please enter:");
scanf("%d", & amp;i);
system("cls");
switch (i) {
case 1: geme();
break;
case 0:
printf("Exit successfully\
");
break;
default:printf("Input error, please re-enter:");
break;
}
} while (i);

return 0;
}

fu.c

#define _CRT_SECURE_NO_WARNINGS
#include"fu.h"
void chushihua(char arr[kuan][chang], int x, int y) {//Use a loop to initialize the array where x and y are 1~3 to spaces
for (int i = 1; i < x; i + + ) {
for (int j = 1; j < y; j + + ) {
arr[i][j] = ' ';
}
}
}
 void dayin(char arr[kuan][chang], int x, int y) {
for (int i = 0; i < x; i + + ) {
printf("%-2d", i);//When printing, print the x coordinate
for (int j = 1; j < y; j + + ) {
if (i == 0) {//The first line prints the y coordinate
printf("%-2d", j);
}
else {//
printf("%c", arr[i][j]);//Print spaces
if(j//Print the following "-----" to separate each line, and control to print only the middle two OK
printf("\
");
printf(" - - - - ");
}
printf("\
");
}
}

int panduan(char arr[kuan][chang]) {<!-- -->
//Return 1 for success
\t//OK
for (int i = 1; i < kuan; i + + ) {<!-- -->//Control x unchanged, traverse y, if they are all the same and not spaces
if (arr[i][1] == arr[i][2] & amp; & amp; arr[i][2] == arr[i][3] & amp; & amp; arr[i] [1] != ' ')
return 1;
}
\t//List
for (int i = 1; i < chang; i + + ) {<!-- -->//Control y unchanged, traverse x, if they are the same and not spaces
if (arr[1][i] == arr[2][i] & amp; & amp; arr[2][i] == arr[3][i] & amp; & amp; arr[1] [i] != ' ')
return 1;
}
\t//Diagonal
if (arr[1][1] == arr[2][2] & amp; & amp; arr[2][2] == arr[3][3] & amp; & amp; arr[1] [1] != ' ')//List them all directly
return 1;
if (arr[3][1] == arr[2][2] & amp; & amp; arr[2][2] == arr[1][3] & amp; & amp; arr[2] [2] != ' ')
return 1;
//If neither returns, -1 is returned, which means it has not been successful yet.
return -1;
}

void shuangren(char arr[kuan][chang]) {<!-- -->//Double mode
int te = (kuan-1) * (chang-1);//Find the number of all grids--9
while (te != 0) {<!-- -->//Tie when looping te=0
int x = 0,y=0;
printf("A( + ):");//A goes first
scanf("%d %d", & amp;x, & amp;y);
system("cls");
arr[x][y] = ' + ';//' + ' represents the flag
int r = panduan(arr);//make judgment
if (r == 1) {<!-- -->//return 1, success, break
printf("Congratulations to A on winning\
");
dayin(arr, kuan, chang);//Print the final chessboard to see
break;
}
else {<!-- -->
dayin(arr, kuan, chang);//Print the current board to continue the game
te--;//te minus 1
}
if (te >0) {<!-- -->//When te==0, it means the chessboard is full, stop
printf("B(-):");
scanf("%d %d", & amp;x, & amp;y);
system("cls");
arr[x][y] = '-';
r = panduan(arr);
if (r == 1) {<!-- -->//return 1, success, break
printf("Congratulations B on winning\
");
dayin(arr, kuan, chang);//Print the final chessboard to see
break;
}
else {<!-- -->
dayin(arr, kuan, chang);
te--;
}
}
}
if(te==0)//When te==0, it means there is a winner for each share
printf("It's a draw\
");
jiemian();//Print the game interface to see if the game is played
}
void diannao(char arr[kuan][chang]) {//Computer battle
int te = (kuan - 1) * (chang - 1);//Find the number of all grids--9
while (te != 0) {//I play first, the process is the same as for two people
int x = 0, y = 0;
printf("A( + ):");
scanf("%d %d", & amp;x, & amp;y);
system("cls");
arr[x][y] = ' + ';
int r = panduan(arr);
if (r == 1) {
printf("Congratulations to A on winning\
");
dayin(arr, kuan, chang);
break;
}
else {
dayin(arr, kuan, chang);
te--;
}
if (te > 0) {
printf("B(-):");
do {//Control the computer to play chess in the space
x = rand() % 3 + 1;//Random number (%3 + 1 controls this number between 1 and 3)
y = rand() % 3 + 1;
} while (arr[x][y] != ' ');//The following process is the same as the above
system("cls");
arr[x][y] = '-';
r = panduan(arr);
if (r == 1) {
printf("Congratulations B on winning\
");
dayin(arr, kuan, chang);
break;
}
else {
dayin(arr, kuan, chang);
te--;
}
}
}
if (te == 0)
printf("It's a draw\
");
jiemian();
}

The above is all the code

Summary

1. During the implementation process, you should do it module by module, and don’t check it at the end (this was the case when I wrote Minesweeper last time, a bloody lesson)
2. Think about it first and then implement it
3. Minesweeper is similar to this. Friends who are interested can try it.

Finally, thank you everyone for watching. If it helps you, please remember to follow it three times (three times in a row will definitely return)

syntaxbug.com © 2021 All Rights Reserved.