当前位置:网站首页>[C language] implementation of three piece chess games
[C language] implementation of three piece chess games
2022-07-28 23:04:00 【Attacking Xiaobai*】
List of articles
1. Explanation of the implementation steps of Sanzi chess
First of all, think about the necessary objects to realize Sanzi
1. The board 2. Two pieces
The chessboard can be used – and | Symbols to build , Players' chess pieces are used * Computer chess pieces are used @ Instead of , To build a 3*3 The array of is used to store chess pieces
Then the data in the array is a piece , The process of playing chess is the process of filling the array
1.1 Game menu
void Menu()
{
printf("\n");
printf("welcome to the three chess game\n");
printf("-------------------------------\n");
printf("----1.Start 2.out------\n");
printf("-------------------------------\n");
printf("\n");
}
Make a simple menu first
1.2 Getting to know the chessboard
void InitBoard(char board[ROW][COL], size_t row, size_t col)
{
for (size_t i = 0; i < row; i++)
{
for (size_t j = 0; j < col; j++)
{
board[i][j] = ' ';
}
}
}
The principle of recognizing checkerboard for the first time is to empty the data in the array , Set it to invisible ’ ‘, Easy to fill in data later
1.3 Print chessboard
void DisplayBoard(char board[ROW][COL], size_t row, size_t col)
{
for (size_t i = 0; i < row; i++)
{
printf(" ");// Adjust the position of the chessboard , At the center of the game
for (size_t j = 0; j < col; j++)
{
printf(" %c ", board[i][j]);
if (j < col -1) // Need to add ( Number of columns -1) Of |
{
printf("|");
}
}
printf("\n");
if (i < row -1)
{
printf(" ");
printf("-----------\n");
}
}
printf("\n\n");
}

After writing these two steps, you can write a small test to verify the correctness of the code , You can fine tune the code, and the chessboard is more beautiful
1.4 The player is down
Called function
size_t Celebrate(char board[ROW][COL], size_t row, size_t col); // Celebrate the victory
size_t IsFull(char board[ROW][COL], size_t row, size_t col) // Determine whether the lattice has sub
void PlayerMove(char board[ROW][COL], size_t row, size_t col)
56 {
57 size_t my_row, my_col;
58 printf(" Please enter rows before columns :>");
59 scanf("%lu%lu", &my_row, &my_col);
60 while (my_row > row || my_col > col || !IsFull(board, my_row, my_col)) // Verify that the coordinates are legal
61 {
62 printf(" Wrong position or position full , Please re-enter \n");
63 printf(" Please enter rows before columns :>");
64 scanf("%lu%lu", &my_row, &my_col); // Move later
65 }
66 board[my_row][my_col] = '*';
67 DisplayBoard(board, row, col); // Print chessboard
68 Celebrate(board, row, col); // Test win or lose
69 }
Here we need to think about several phenomena that players will appear when playing chess .
Check the coordinates : First of all, entering coordinates may lead to out of bounds , So we should judge the legitimacy of coordinates , And there may already be chess in the coordinates .
Print chessboard : After the player plays chess, the opponent ( The computer ) I must want to see the opponent take that step , So print the chessboard
Judge the match : The player may have three children connected after falling , So we should judge whether the match will be won or lost 、
1.5 Computer move later
size_t IsFull(char board[ROW][COL], size_t row, size_t col) // Determine whether the lattice has sub
void ComputerMove(char board[ROW][COL], size_t row, size_t col)
72 {
73 size_t c_row, c_col;
74 c_row = rand() % 3;
75 c_col = rand() % 3;
76 while (!IsFull(board, c_row, c_col)) // Check whether the coordinates have chess
77 {
78 c_row = rand() % 3;
79 c_col = rand() % 3;
80 }
81 board[c_row][c_col] = '@';
82 DisplayBoard(board, row, col);
83 }
We can use random numbers to help the computer settle ,rand() Function returns a random value
Coordinates are legal : Although random numbers %3 It ensures that the coordinates will not cross the boundary , But there may be chess in the random coordinate position, so it needs to be tested
Be careful : Use rand() The function needs to be called in advance strand() function , And use timestamp to act as strand The parameters of the function
We don't use it here Celebrate Function is because we put it in while In the judgment statement
1.6 Judge to win
Sanzi has three endings , Plus the continuous match, there are four states . Players win , The computer wins , It ends in a draw , The match continues
The state is a little more realized by two functions
Function one :
char IsWin(char board[ROW][COL], size_t row, size_t col)
{
for (size_t i = 0; i < row; i++) // Three o'clock line wins judgment
{
size_t count_p = 0; // Counter . Judge how many pieces each player has in each line
size_t count_c = 0;
for (size_t j = 0; j < col; j++)
{
if (board[i][j] == '*') // Player wins and returns p character
{
count_p++;
}
if (board[i][j] == '@')
{
count_c++; // The computer returns in line c character
}
}
if (count_p == 3)
{
return 'p';
}
if (count_c == 3)
{
return 'c';
}
}
for (size_t i = 0; i < row; i++) // Three point judgment
{
size_t count_p = 0;
size_t count_c = 0;
for (size_t j = 0; j < col; j++)
{
if (board[j][i] == '*')
{
count_p++;
}
if (board[j][i] == '@')
{
count_c++;
}
}
if (count_p == 3)
{
return 'p';
}
if (count_c == 3)
{
return 'c';
}
}
if (board[0][0] == '*' && board[1][1] == '*' && board[2][2] == '*') // Three points form a diagonal judgment
return 'p';
if (board[0][2] == '*' && board[1][1] == '*' && board[2][0] == '*')
return 'p';
if (board[0][0] == '@' && board[1][1] == '@' && board[2][2] == '@')
return 'c';
if (board[0][2] == '*' && board[1][1] == '*' && board[2][0] == '*')
return 'c';
size_t count = 0; // At this time, there is no connection between any party and three children , Maybe the chessboard grid has been laid , Make a draw judgement
for (size_t i = 0; i < row; i++)
{
for(size_t j = 0; j < col; j++)
{
if (board[i][j] != ' ')
{
count++;
}
}
}
if (count == (row * col))
{
return 'o'; // Draw back o character
}
return 'v'; // The match is not over , Continue the match and return v character
}
IsWin Function returns four different characters to represent the match state , Next, we will use function 2 to receive the return value of function 1 for celebration judgment
Function two :
size_t Celebrate(char board[ROW][COL], size_t row, size_t col)
{
char ch = IsWin(board, row, col); // receive IsWin Return value , There is no need to continue to win or draw
if (ch == 'p') // return 0 You can leave it to the judgment statement to judge , End the game
{
printf("Player win\n");
return 0;
}
if (ch == 'c')
{
printf("Computer win\n");
return 0;
}
if (ch == 'o')
{
printf("if ends in a draw\n");
return 0;
}
return 1; // The end state above didn't go in , Explain that the match continues , return 1
}
Receive a return value of the function to judge the local state , return 0 and 1 Decide whether to end the game or continue the game
1.7 Game implementation
void game()
{
char board[ROW][COL];
InitBoard(board, ROW, COL);
DisplayBoard(board, ROW, COL);
while (Celebrate(board, ROW, COL)) // Our computer winning conditions are here , There is no need to judge in the computer
{
PlayerMove(board, ROW, COL);
ComputerMove(board, ROW, COL);
}
}
void game_test()
{
size_t chess = 0;
do
{
Menu();
printf(" Please choose whether to start the game :>");
scanf("%lu", &chess);
if (chess == 0)
{
break; // Exit loop
}
else if (chess == 1)
{
printf("game start\n");
game();
}
else
{
printf(" Input error, please input again \n");
}
}while(1);
}
int main()
{
srand((unsigned int)time(NULL)); // Use rand() The premise of a function
game_test();
return 0;
}
There is basically no problem here , There are some points that need to be noted in the code .
2. Gobang source code
2.1Makefile
test:test.o game.o
gcc -o [email protected] $^ -std=c99
test.o:test.c
gcc -c $< -std=c99
game.o:game.c
gcc -c $< -std=c99
.PHONY:clean
clean:
rm -f ./*.o test 2.2game.h
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define COL 3
#define ROW 3
void Menu();
void InitBoard(char board[ROW][COL], size_t row, size_t col); // Initialize chessboard
void DisplayBoard(char board[ROW][COL], size_t row, size_t col); // Print chessboard
size_t IsFull(char board[ROW][COL], size_t row, size_t col) // Determine whether the lattice has sub
void PlayerMove(char board[ROW][COL], size_t row, size_t col); // The player is down
void ComputerMove(char board[ROW][COL], size_t row, size_t col); // Computer move later
char IsWin(char board[ROW][COL], size_t row, size_t col); // Judge the match
size_t Celebrate(char board[ROW][COL], size_t row, size_t col); // Celebrate the victory
2.3game.c
#include "game.h"
void Menu()
{
printf("\n");
printf("welcome to the three chess game\n");
printf("-------------------------------\n");
printf("----1.Start 2.out------\n");
printf("-------------------------------\n");
printf("\n");
}
void InitBoard(char board[ROW][COL], size_t row, size_t col)
{
for (size_t i = 0; i < row; i++)
{
for (size_t j = 0; j < col; j++)
{
board[i][j] = ' ';
}
}
}
void DisplayBoard(char board[ROW][COL], size_t row, size_t col)
{
for (size_t i = 0; i < row; i++)
{
printf(" ");
for (size_t j = 0; j < col; j++)
{
printf(" %c ", board[i][j]);
if (j < col -1)
{
printf("|");
}
}
printf("\n");
if (i < row -1)
{
printf(" ");
printf("-----------\n");
}
}
printf("\n\n");
}
size_t IsFull(char board[ROW][COL], size_t row, size_t col)
{
if (board[row][col] == ' ')
{
return 1;
}
else
{
return 0;
}
}
void PlayerMove(char board[ROW][COL], size_t row, size_t col)
{
size_t my_row, my_col;
printf(" Please enter rows before columns :>");
scanf("%lu%lu", &my_row, &my_col);
while (my_row > row || my_col > col || !IsFull(board, my_row, my_col))
{
printf(" Wrong position or position full , Please re-enter \n");
printf(" Please enter rows before columns :>");
scanf("%lu%lu", &my_row, &my_col);
}
board[my_row][my_col] = '*';
DisplayBoard(board, row, col);
Celebrate(board, row, col);
}
void ComputerMove(char board[ROW][COL], size_t row, size_t col)
{
size_t c_row, c_col;
c_row = rand() % 3;
c_col = rand() % 3;
while (!IsFull(board, c_row, c_col))
{
c_row = rand() % 3;
c_col = rand() % 3;
}
board[c_row][c_col] = '@';
DisplayBoard(board, row, col);
}
char IsWin(char board[ROW][COL], size_t row, size_t col)
{
for (size_t i = 0; i < row; i++)
{
size_t count_p = 0;
size_t count_c = 0;
for (size_t j = 0; j < col; j++)
{
if (board[i][j] == '*')
{
count_p++;
}
if (board[i][j] == '@')
{
count_c++;
}
}
if (count_p == 3)
{
return 'p';
}
if (count_c == 3)
{
return 'c';
}
}
for (size_t i = 0; i < row; i++)
{
size_t count_p = 0;
size_t count_c = 0;
for (size_t j = 0; j < col; j++)
{
if (board[j][i] == '*')
{
count_p++;
}
if (board[j][i] == '@')
{
count_c++;
}
}
if (count_p == 3)
{
return 'p';
}
if (count_c == 3)
{
return 'c';
}
}
if (board[0][0] == '*' && board[1][1] == '*' && board[2][2] == '*')
return 'p';
if (board[0][2] == '*' && board[1][1] == '*' && board[2][0] == '*')
return 'p';
if (board[0][0] == '@' && board[1][1] == '@' && board[2][2] == '@')
return 'c';
if (board[0][2] == '*' && board[1][1] == '*' && board[2][0] == '*')
return 'c';
size_t count = 0;
for (size_t i = 0; i < row; i++)
{
for(size_t j = 0; j < col; j++)
{
if (board[i][j] != ' ')
{
count++;
}
}
}
if (count == (row * col))
{
return 'o';
}
return 'v';
}
size_t Celebrate(char board[ROW][COL], size_t row, size_t col)
{
char ch = IsWin(board, row, col);
if (ch == 'p')
{
printf("Player win\n");
return 0;
}
if (ch == 'c')
{
printf("Computer win\n");
return 0;
}
if (ch == 'o')
{
printf("if ends in a draw\n");
return 0;
}
return 1;
}
2.4test.c
void test_1()
{
char board[ROW][COL];
Menu();
InitBoard(board, ROW, COL);
DisplayBoard(board, ROW, COL);
PlayerMove(board, ROW, COL);
ComputerMove(board, ROW, COL);
PlayerMove(board, ROW, COL);
PlayerMove(board, ROW, COL);
PlayerMove(board, ROW, COL);
}
void game()
{
char board[ROW][COL];
InitBoard(board, ROW, COL);
DisplayBoard(board, ROW, COL);
while (Celebrate(board, ROW, COL))
{
PlayerMove(board, ROW, COL);
ComputerMove(board, ROW, COL);
}
}
void game_test()
{
size_t chess = 0;
do
{
Menu();
printf(" Please choose whether to start the game :>");
scanf("%lu", &chess);
if (chess == 0)
{
break;
}
else if (chess == 1)
{
printf("game start\n");
game();
}
else
{
printf(" Input error, please input again \n");
}
}while(1);
}
int main()
{
srand((unsigned int)time(NULL));
game_test();
return 0;
}
That is 【C Language 】 Three chess game to achieve all the content , Thank you for watching. .
边栏推荐
- Wheel 6: qserialport serial port data transceiver
- Torch.fft.fft 2. () error reporting problem solution
- Invest 145billion euros! EU 17 countries announce joint development of semiconductor technology
- 从 IPv4 向 IPv6 的迁移
- pgbench基准测试《postgresql》
- Yolov5 improvement 6: add small target detection layer
- 定了!哪吒S全系产品将于7月31日上市发售
- NPM run dev, automatically open the browser after running the project
- Simple es highlight practice
- [copy] Internet terms, abbreviations, abbreviations
猜你喜欢

Yolov5 improvement 4: add ECA channel attention mechanism

18张图,直观理解神经网络、流形和拓扑

Multi activity disaster recovery construction after 713 failure of station B | takintalks share

sql优化常用的几种方法

Annaconda installs pytoch and switches environments

简单的es高亮实战

Simple es highlight practice
![[3D target detection] 3dssd (II)](/img/8a/e8927cd868eb99d8880d4f199d8918.png)
[3D target detection] 3dssd (II)

Learning experience sharing 4: learning experience of yolov7

No code development platform management background tutorial
随机推荐
轮子六:QSerialPort 串口数据 收发
Target detection notes SSD
OSV-q grd_ x=grd_ x[:, :, 0:-1, :]-data_ in[:, :, 1:, :]IndexError: too many indices for tensor of d
投资500亿元!中芯京城正式注册成立!
Submission records of frontiers Publishing House (with status changes)
Xshell7, xftp7 personal free version official download, no need to crack, no activation, download and use
Stm32f4 serial port burning [flymcu]
[database]
HP ProLiant DL380 boot from USB flash drive, press which key
Use FFT, matrix multiplication and conv2d to calculate convolution based on pytorch
Configuration and official document of Freia library [tips]
Anaconda environment installation skimage package
C语言学习内容总结
赋能中国芯创业者!看摩尔精英如何破解中小芯片企业发展难题
Es personal arrangement of relevant interview questions
TypeError: can‘t convert cuda:0 device type tensor to numpy. Use Tensor. cpu() to copy the tensor to
Wheel 7: TCP client
Record a question about the order of trigonometric function exchange integrals
Sqlilabs-1 (breakthrough record)
Summary of C language learning content