当前位置:网站首页>C language to achieve three chess game (detailed explanation)
C language to achieve three chess game (detailed explanation)
2022-07-29 03:55:00 【yin_ Yin】
List of articles
One . Introduction to Sanzi chess game
I believe everyone has played sanziqi , Here is a brief introduction !
It's a kind of black and white chess . Sanzi chess is a traditional folk game , Also called Jiugong chess 、 Circle fork 、 A dragon 、 Tic tac toe chess, etc . Just walk your three pieces into a line , He won 
Two . Description of the game implementation process
Print menu , Prompt the player to make a choice , ad locum , What we set up is :
choice 1, Play a game
choice 0, Quit the game
Select another number , Prompt input error , Let the user re-enterPrint chessboard
Players play chess
The computer plays chess
Judgement of winning or losing
3、 ... and .C Language code implementation
1. Overview of the overall framework and code display
Finally realize the complete code of the game , We In three files , It is convenient to manage our code .
The three documents are :
(1)test.c
For testing game logic
(2)game.h
Function declaration related to game implementation , Symbol declaration , The header file contains
(3)game.c
The realization of game related functions
Then we will show all the codes in the three documents for your reference , Then I will explain it in detail :
(1)test.c
#include "game.h"
void menu()
{
printf("**********************************\n");
printf("****** 1. play *******\n");
printf("****** 0. exit *******\n");
printf("**********************************\n");
}
void play_game()
{
char ret = '0';
char board[ROW][COL] = {
0 };
init_board(board, ROW, COL);// Initialize array
print_board(board, ROW, COL);// Print chessboard
while (1)
{
player_move(board, ROW, COL);// Players play chess
print_board(board, ROW, COL);// Print chessboard
// Judgement of winning or losing
ret = is_win(board, ROW, COL);
if (ret != 'C')
break;
computer_move(board, ROW, COL);// The computer plays chess
print_board(board, ROW, COL);// Print chessboard
// Judgement of winning or losing
ret = is_win(board, ROW, COL);
if (ret != 'C')
break;
}
if (ret == '*')
printf(" You win \n");
else if (ret == '#')
printf(" Computers win \n");
else if (ret == 'Q')
printf(" It ends in a draw \n");
}
int main()
{
srand((unsigned int)time(NULL));// Set random number generator
int elect = 0;
do
{
menu();
printf(" Please select :");
scanf("%d", &elect);
switch (elect)
{
case 1:
play_game();
break;
case 0:
printf(" Quit the game !!!\n");
break;
default:
printf(" Wrong choice , Please reselect !!!\n");
break;
}
} while (elect);
return 0;
}
(2)game.h
#define _CRT_SECURE_NO_WARNINGS
#define ROW 3 //ROW—— That's ok
#define COL 3 //COL—— Column
#include <stdio.h>
#include <stdlib.h>//srand The required header file
#include <time.h>//time The header file required by the function
// Function declaration
void init_board(char board[ROW][COL], int row, int col);// Initialize array
void print_board(char board[ROW][COL], int row, int col);// Print chessboard
void player_move(char board[ROW][COL], int row, int col);// Players play chess
void computer_move(char board[ROW][COL], int row, int col);// The computer plays chess
char is_win(char board[ROW][COL], int row, int col);// Judgement of winning or losing
(3)game.c
#include "game.h"
// Initialize array
void init_board(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] = ' ';
}
}
}
// Print chessboard
void print_board(char board[ROW][COL], int row, int col)
{
int i = 0;
for (i = 0; i < row; i++)
{
// Print " | | "
int j = 0;
for (j = 0; j < col; j++)
{
printf(" %c ", board[i][j]);
if (j < col - 1)
printf("|");
}
printf("\n");
// Print ---|---|---, Notice that the last line does not
if (i < row - 1)
{
for (j = 0; j < col; j++)
{
printf("---");
if (j < col - 1)
printf("|");
}
printf("\n");
}
}
}
// Players play chess
void player_move(char board[ROW][COL], int row, int col)
{
printf(" Players play chess :\n");
int x = 0;
int y = 0;
while (1)
{
printf(" Please enter the coordinates to play chess :");
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] = '*';
break;
}
else
printf(" This coordinate is already occupied , Please re-enter :\n");
}
else
printf(" Illegal coordinates , Re input \n");
}
}
// The computer plays chess
void computer_move(char board[ROW][COL], int row, int col)
{
printf(" The computer plays chess :\n");
while (1)
{
int x = rand() % row;//rand The range of random numbers generated by the function is relatively large, so we give it % On 3
int y = rand() % col;// The range is exactly 0---2
if (board[x][y] == ' ')
{
board[x][y] = '#';
break;
}
}
}
// If the chessboard is full , return 1, Dissatisfaction returns 0;
static int is_full(char board[ROW][COL], int row, int col)
{
int i = 0;
for (i = 0; i < row; i++)
{
int j = 0;
for (j = 0; j < col; j++)
{
if (' ' == board[i][j])
return 0;
}
}
return 1;
}
// Judgement of winning or losing
char is_win(char board[ROW][COL], int row, int col)
{
// Judge that the rows are equal
int i = 0;
for (i = 0; i < row; i++)
{
if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != ' ')
{
return board[i][0];
}
}
// Judge whether the columns are equal
for (i = 0; i < col; i++)
{
if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[0][i] != ' ')
{
return board[0][i];
}
}
// Judge the main diagonal
if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[1][1] != ' ')
{
return board[1][1];
}
// Judge the sub diagonal
if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[1][1] != ' ')
{
return board[1][1];
}
// Judge a draw
if (is_full(board, row, col) == 1)
{
return 'Q';
}
// Keep playing
return 'C';
}
2. Implementation test of the overall logic of the game
We first in test.c The document implements the overall process of the Sanzi game , Test whether the logic is correct :
#include <stdio.h>
void menu()
{
printf("**********************************\n");
printf("****** 1. play *******\n");
printf("****** 0. exit *******\n");
printf("**********************************\n");
}
void play_game()
{
printf(" Play a game \n");
}
int main()
{
int elect = 0;
do
{
menu();
printf(" Please select :");
scanf("%d", &elect);
switch (elect)
{
case 1:
play_game();
break;
case 0:
printf(" Quit the game !!!\n");
break;
default:
printf(" Wrong choice , Please reselect !!!\n");
break;
}
} while (elect);
return 0;
}
Here we will not implement the functions of the game , Replace with a sentence , Because now I'm just testing the logic :

Take a look at the results :
Logical correctness , Next, implement each function step by step .
3. The specific process of the game is realized
(1) Print chessboard
Let's see what the chessboard looks like first :
Look at the , Can we Use a two-dimensional array to simulate the chessboard , Each element is initialized as a space ‘ ’, But we see that , There are separation lines between each chessboard , So we have to print the separation line .
to glance at Finally, the chessboard of our code printing :
The size of the general chessboard 3X3 Of , however , If one day we feel 3X3 Your chessboard is too small , Playing is not enjoyable , Want to change the size of the chessboard , What shall I do? , Is it right to put all 3 They are all changed into 5 Well , in order to It is convenient to change the size of the chessboard , Let's just put it in the header file game.h of use #define Define an identifier constant , such , It will be convenient to modify the size of the chessboard in the future .
stay The header file game.h in :
#define ROW 3 //ROW—— That's ok
#define COL 3 //COL—— Column
Of course, we want to be in test.c or game.c Used in , You need to include the header change file , But notice , contain Header file defined by ourselves , Need to use ” “ instead of < >:
I want to change the size of the chessboard in the future , Just modify these two numbers .
Since we want to use a two-dimensional array , First of all, we need to Define a 3X3 And then pass it as a parameter :
Implement the initialization array function init_board():
Next we're going to Realize the function of printing chessboard print_board():

Look at the effect :
We use multi file management , Remember to The function declaration is placed in game.h in 
function print_board(),init_board() Put the implementation in game.c in .
(2) Design a function to realize that players play chess
First of all, let's stipulate , The player's pieces use ” * “ Express , The computer's chess pieces are used ” # “ Express .
How can players play chess , We let The player enters a coordinate , Then put a chess piece on this coordinate .
If you use coordinates , We have to consider several issues :
1. Whether the coordinates entered by the player are out of bounds ?
2. The player outputs whether the coordinates have been used ?
3. For players , He may not know that the subscript of the array is from 0 At the beginning , So player input (1,1), We need to help him put it into the array subscript (0,0) In the right place .
resolvent :
When coordinate , Cross the border or have been occupied , Let the user re-enter ;
Coordinates entered by the user (x,y), Subtract both numbers 1 That's it
Implementation function :
Of course , Don't forget to game.h Make a statement in .
See the effect :
Okay , The player's task of playing chess is completed .
(3) Design functions to achieve computer chess
How to let the computer play chess ?
We can use rand Function generates two random numbers , Indicates the coordinates of the computer to play chess , If the coordinates are right , Put one in this position ” # “.
Pay attention to rand The function needs to call before generating random numbers srand Set up a random number generator , About rand You can go down to learn about the detailed usage of function .
Design function :
Let's see the effect :
Okay , The computer chess function is completed .
(4) Design a function to judge whether you win or lose
To judge whether you win or lose , We can stipulate this , If A function of winning or losing is——win
return “ * ”, Then the player wins ,
return “ # ”, Computers win ,
return “ C ”, The game goes on ;
return “ Q ”, It ends in a draw .
// Judgement of winning or losing
char is_win(char board[ROW][COL], int row, int col)
{
// Judge that the rows are equal
int i = 0;
for (i = 0; i < row; i++)
{
if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != ' ')
{
return board[i][0];
}
}
// Judge whether the columns are equal
for (i = 0; i < col; i++)
{
if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[0][i] != ' ')
{
return board[0][i];
}
}
// Judge the main diagonal
if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[1][1] != ' ')
{
return board[1][1];
}
// Judge the sub diagonal
if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[1][1] != ' ')
{
return board[1][1];
}
// Judge a draw
if (is_full(board, row, col) == 1)
{
return 'Q';
}
// Keep playing
return 'C';
}
Here we use another function to judge whether the chessboard is full :
// If the chessboard is full , return 1, Dissatisfaction returns 0;
static int is_full(char board[ROW][COL], int row, int col)
{
int i = 0;
for (i = 0; i < row; i++)
{
int j = 0;
for (j = 0; j < col; j++)
{
if (' ' == board[i][j])
return 0;
}
}
return 1;
}
Come here , All the functions are finished , Let's play :
Of course, there are still many improvements in this code , If you are interested, you can try it yourself !!!
If there's something wrong with it , Welcome to correct !!!
边栏推荐
- I.MX6U-驱动开发-2-LED驱动
- sql
- Big manufacturers finally can't stand "adding one second", and companies such as Microsoft, Google meta propose to abolish leap seconds
- Typescript from entry to mastery (XXI) generic types in classes
- Kotlin companion object vs global function
- Opensql quick learning
- 谁能详细说下mysqlRC下的半一致读和怎么样减少死锁概率?
- Why BGP server is used in sunflower remote control? Automatic optimal route and high-speed transmission across operators
- Why does the 20 bit address bus determine the storage space of 1MB
- Deep into C language (3) -- input and output stream of C
猜你喜欢

实例搭建Flask服务(简易版)

新零售O2O 电商模式解析

Inclusion exclusion principle

BGP的基础配置---建立对等体、路由宣告

Alibaba Font Icon Library Usage and update methods

Vs code must know and know 20 shortcut keys!

(2022 Hangdian multi school III) 1011 link is as bear (thinking + linear basis)

Malloc C language

(newcoder 15079) irrelevant (inclusion exclusion principle)

Shutter start white screen
随机推荐
Meeting notice of OA project (Query & whether to attend the meeting & feedback details)
The data type of symbol, a new feature of ES6
Shopify卖家:EDM营销就要搭配SaleSmartly,轻松搞定转化率
How to understand clock cycle and formula CPU execution time = number of CPU clock cycles / dominant frequency
Why is continuous integration and deployment important in development?
(2022 Hangdian multi school III) 1011 link is as bear (thinking + linear basis)
Data too long for column 'xxx' at row 1 solution
内连接和左连接简单案例
【redis系列】字符串数据结构
Lucifer 98 life record ing
RHCE的at,crontab的基本操作,chrony服务和对称加密和非对称加密
Excel拼接数据库语句
Deep understanding of Base64 underlying principles
Inclusion exclusion principle
Is the browser multi process or single process?
I. creation and constraint of MySQL table
SQL语句 关于字段转换怎么写
Extended operator of new features in ES6
CUB_200鸟类数据集关键点可视化
无法一次粘贴多张图片