当前位置:网站首页>[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. .
边栏推荐
- Cglib create proxy
- DirectX修复工具下载(exagear模拟器数据包在哪里)
- Improvement 16 of yolov5: replace backbone network C3 with lightweight network pp-lcnet
- 无代码开发平台通讯录入门教程
- cannot resize variables that require grad
- Stm32f4 serial port burning [flymcu]
- Wheel 7: TCP client
- shell脚本基础——Shell运行原理+变量、数组定义
- Will Qualcomm and MediaTek chips soon be sold, and will they surpass Huawei to become the first in China?
- 【复制】互联网术语、简称、缩写
猜你喜欢
Simple es highlight practice
Torch.fft.fft 2. () error reporting problem solution
Yolov5 improvement 12: replace backbone network C3 with lightweight network shufflenetv2
Draem+sspcab [anomaly detection: block]
【C语言】三子棋小游戏实现
xshell7,xftp7个人免费版官方下载,无需破解,免激活,下载即可使用
Yolov5 improvement 15: network lightweight method deep separable convolution
Target detection notes - overview and common data sets
Xshell7, xftp7 personal free version official download, no need to crack, no activation, download and use
[3D target detection] 3dssd (I)
随机推荐
[3D target detection] 3dssd (II)
pgbench基准测试《postgresql》
Yolov5 improvement 7: loss function improvement
CS flow [abnormal detection: normalizing flow]
cnpm安装步骤
Simple es highlight practice
Is 1E3 a floating point number?
Use FFT, matrix multiplication and conv2d to calculate convolution based on pytorch
【三维目标检测】3DSSD(二)
Target detection notes - overview and common data sets
18张图,直观理解神经网络、流形和拓扑
ValueError: Using a target size (torch.Size([64])) that is different to the input size (torch.Size([
Servlet的使用手把手教学(一)
leetcode 199. 二叉树的右视图
It's settled! All products of Nezha s will be launched on July 31
Learning experience sharing 5: yolov5 dataset division and Yolo format conversion
The simple neural network model based on full connection layer MLP is changed to the model based on CNN convolutional neural network
无代码开发平台通讯录入门教程
定了!哪吒S全系产品将于7月31日上市发售
No code development platform management background tutorial