当前位置:网站首页>C language games: sanziqi (simple version) implementation explanation
C language games: sanziqi (simple version) implementation explanation
2022-06-23 01:50:00 【Nobaya】
Catalog
The computer plays chess ( Key points )
Judgement of winning or losing
Combine functions to implement the game
Preface
This is an article to realize a simple C Language games 【 Sanzi 】 Explanation , If you have your own idea later, you can add some game items to the small game by yourself .
The final implementation style

Print menu
We first need to print a game menu for players to choose , Start the game or exit the game , Because the menu will be printed out for players to choose before the start of each game ,, And at least once . So we put the menu in do whlie Inside the loop . The following game code is the same .
void menu(void) // Since no return value is required and there are no parameters , So the return type and function parameters are void
{
printf("**********************\n");
printf("***** 1、 Start the game *****\n"); // You can adjust the format according to your preference
printf("***** 0、 Quit the game *****\n"); // The effect may be better in the middle of the screen ( I won't )
printf("**********************\n");
}Initialize chessboard
You can see that our chessboard was empty at the beginning , And there are rows and columns to determine the position , Then we can use a two-dimensional character array to store the contents of the chessboard , And initialized to spaces ' '.
// Here we use the form of function to initialize , First, create a two-dimensional character array in the main function
void star_board(char board[ROW][COL],int row,int col)
{
for (int i = 0; i < row; i++) // The two layers of loops represent rows and columns, respectively
{
for (int j = 0; j < col; j++)
{
board[i][j] = ' '; // Initialize to ' '.
}
}Print chessboard
The principle of printing chessboard is the same as that of initializing chessboard , It's a two-layer cycle . But you can control the printing format according to your desired effect .
void put_board(char board[ROW][COL],int row,int col)
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
printf(" %c ", board[i][j]);
if (j < col - 1)
printf("|"); // Print at the end of each column | By Region
}
if (i < row - 1)
{
printf("\n");
printf("------------"); // Print at the end of each line —————— Come to the District branch
printf("\n");
}
else
printf("\n");
}
}Players play chess
Players need to input their own coordinates when playing chess, so they need to set two variables to simulate the line (x) And column (y), And change the corresponding elements in the two-dimensional array to ' * ', Used to distinguish players 、 There is still room for the computer . And remind players when they input wrong coordinates .
// Little details : Shape parameter ch Is to change the elements in the array to the characters you want , In this way, you can avoid repeatedly defining functions
void player_move(char board[ROW][COL], int row, int col, char ch)
{
int x, y;
printf(" Players play chess , Please enter the coordinates :");
do {
scanf("%d%d", &x, &y);
if (x - 1 > row || y - 1 > col)
{
printf(" illegal input , Please enter the correct coordinates :"); // Give correct prompt when the correct coordinates are not entered
continue;
}
if (board[x - 1][y - 1] == ' ')
{
board[x - 1][y - 1] = ch; // Change the elements in the array to ch
break;
}
else
printf(" This coordinate is already occupied , Please re-enter the coordinates :"); // Give a prompt when you enter the coordinates that have been set
} while (1);
}The computer plays chess ( Key points )
This is the key and difficult point of the game . When the computer plays chess, it should be placed inside the chessboard , I still have to go where I haven't been , If we still need to implement various intelligent algorithms, it will be more complicated . We only play chess here ( So the difficulty of this game is to let the computer win ), The algorithm will not be studied in depth , Interested partners can do their own research .
When we let the computer play chess, we need to let the computer's chess pieces fall on the chessboard , And it must be something that hasn't been done before , In this case, you need to use the random number function rand 了 , In the use of rand Before we need to use srand To generate a range of random numbers , In the use of srand We also need to use a timestamp function time.【 You can click the function to view the specific function contents 】
void computer_move(char board[ROW][COL], int row, int col, char ch) // Control the chess piece style of the computer
{
printf(" The computer plays chess :\n");
while (1)
{
int x = rand() % 3; // Make the computer chess pieces fall on the chessboard
int y = rand() % 3;
if (board[x][y] == ' ') // Judge whether the chessboard has been played
{
board[x][y] = ch; // The computer plays chess
break;
}
}
}Judgement of winning or losing
Winning or losing in the game is nothing more than three pieces in a row , So we just need to judge whether this condition is met , If the computer wins, return to the computer's chess pieces , If the player wins, return to the player's chess pieces , If it's a draw ( That is, the chessboard is full, but there are no three pieces to practice ) When , Just go back to &.
char is_win(char board[ROW][COL], int row, int col)
{
int count = 0;
for (int i = 0; i < row; i++)
{
if (board[i][0] == '*' && board[i][1] == '*' && board[i][2] == '*')
return '*';
if (board[i][0] == '#' && board[i][1] == '#' && board[i][2] == '#')
return '#';
}
if ((board[0][0] == '*' && board[1][1] == '*' && board[2][2] == '*') || (board[0][2]
== '*' && board[1][1] == '*' && board[2][0] == '*'))
{
return '*';
}
if ((board[0][0] == '#' && board[1][1] == '#' && board[2][2] == '#') || (board[0][2]
== '#' && board[1][1] == '#' && board[2][0] == '#'))
{
return '#';
}
for (int i = 0; i < col; i++)
{
if (board[0][i] == '*' && board[1][i] == '*' && board[2][i] == '*')
return '*';
if (board[0][i] == '#' && board[1][i] == '#' && board[2][i] == '#')
return '#';
}
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
if (board[i][j] == ' ')
count++;
}
}
if (count == 0)
{
printf(" Game draw !!");
return '&';
}
}Combine functions to implement the game
After all the functions of the game are realized by functions , Just combine the functions together to implement the game .
void game()
{
char board[ROW][COL];
star_board(board, ROW, COL); // Initialize chessboard
put_board(board, ROW, COL); // Print chessboard
do {
player_move(board, ROW, COL, '*'); // Players play chess
put_board(board, ROW, COL); // Print chessboard
if (is_win(board, ROW, COL) == '*') // Judgement of winning or losing
{
printf(" Game player wins !!\n");
break;
}
if (is_win(board, ROW, COL) == '&') // Judge if it's a draw
{
printf(" Game draw !!\n");
break;
}
computer_move(board, ROW, COL, '#'); // The computer plays chess
put_board(board, ROW, COL); // Print chessboard
if (is_win(board, ROW, COL) == '#') // Judgement of winning or losing
{
printf(" Computers win !!\n");
break;
}
if (is_win(board, ROW, COL) == '&') // Judgement of winning or losing
{
printf(" Game draw !!\n");
break;
}
} while (1);
}Source code
If you don't understand anything when implementing this small game, you can view the source code through this address Gobang games : Sanzi chess source code
边栏推荐
- 6. const usage, combination of first and second level pointers
- [cmake command notes]find_ path
- Operator part
- fatal: refusing to merge unrelated histories
- Debian10 configuring rsyslog+loganalyzer log server
- Score and loop statements (including goto statements) -part3
- SQL programming task02 job - basic query and sorting
- C. Unstable String
- Data skew analysis of redis slice cluster
- JS to paste pictures into web pages
猜你喜欢

office2016+visio2016

Function part

3D打印微组织

MySQL -- how to access the database of a computer in the same LAN (prenatal education level teaching)

Muduo simple usage

Campus network AC authentication failed

1. Mx6u bare metal program (1) - Lighting master

Unique in Pimpl_ PTR compilation errors and Solutions

ERROR { err: YAMLException: end of the stream or a document separator is expected at line 6, colum

Zabbix5 series - use temperature and humidity sensor to monitor the temperature and humidity of the machine room (XX)
随机推荐
[learning notes] roll back Mo team
Openvino CPU acceleration survey
LeetCode 206. Reverse linked list (iteration + recursion)
Pat a - 1010 radical (thinking + two points)
There is no corresponding change on the page after the code runs at the Chrome browser break point
3. compilation and linking principle
On AI and its future trend | community essay solicitation
[cmake command notes]target_ compile_ options
[hdu] P7079 Pty loves lines
崔鹏团队:万字长文梳理「稳定学习」全景图
Debian10 installing zabbix5.4
Function part
Debian10 LVM logical volumes
Uint8 serializing and deserializing pits using stringstream
//1.14 comma operator and comma expression
Cmake simple usage
Ch340 and PL2303 installation (with link)
//1.10 initial value of variable
[cmake command notes]find_ path
Unit of RMB in words