当前位置:网站首页>Using C language to realize three piece chess games
Using C language to realize three piece chess games
2022-07-28 06:45:00 【HandsomeDog_ L】
Catalog
4. Judging rules or game rules Judge()
Preface
This article is suitable for c Language foundation partner , If the foundation is slightly weak, it may seem a little difficult , But it will not affect the grasp of ideas . This type of program requires some foundation , It can reflect your overall mastery of the knowledge you have learned Before reading this article , I hope you have mastered the following knowledge
Include The header file Source file definition and function Function and function parameter transfer function parameter transfer loop Array ( Two dimensional array )
This article will show the idea of writing programs , And code implementation
Text
introduce
What elements should Sanzi have ? Or you want to design a small game , What function do you want it to have ?
Take Sanzi chess as an example , I think it should have the following functions
1. menu
2. The board
3. Players and computers play chess
4. Rule of judgement
ok, The function has been figured out , Then start writing them out in a program
Code programming
1. menu menu()
The code is as follows :
void menu()
{
printf("************ Three chess game ************\n");
printf("****** 1. play *** 0. exit ******\n");
printf("*********************************\n");
} Menus can be designed by yourself , Just look good to you
2. The board Board()
What functions do you think the chessboard should have ?
I think it should have initialization function InitializeBoard() and Display function DisplayBoard()
So we have the following code
// Use an array to store the pieces we want to play char Board[ROW][COL] = { 0 };// Board initialization The elements in the array are spaces , Visually, the chessboard looks empty void InitializeBoard(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] = ' '; } } } void DisplayBoard(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++)// Print page i The content of the line { // Print data lines printf(" %c ", Board[i][j]);// Corresponding to 1 Green rounded square if (j < col - 1)// The last column does not need to be printed "|" { printf("|"); } } printf("\n");// Line feed ready to print split lines // Print split lines if (i < row - 1)// There is no need to split the last line { for (j = 0; j < col; j++) { printf("---"); if (j < col - 1) { printf("|"); } } printf("\n"); } } }There may be some friends here who will be right DisplayBoard() There is a little doubt about the way of writing , I hope the following picture can dispel your doubts

The red ellipse on the left represents Board[i][j], Dexter 1 The green rounded box No. represents " Board[i][j] " Corresponding to the code " %c "( Notice that the middle space is a space ) 2 The No. box represents the vertical dividing line Corresponding to "|" , that 3 You should know what the box represents , you 're right , It's in the code "---"
Why do you want to set it like this ? That's because this is the smallest thing to print out the chessboard " Cycle unit " I won't elaborate on the reasons here , After all, this is not the point of the code . If you have doubts, you can confide in me
3. Playing chess Move()
There are two players ( Players and computers ) Naturally, there are two functions
Players play chess PlayerMove() and The computer plays chess ComputerMove()
Because we have initialized the elements of the chessboard as spaces above, if you want to play chess Replace the space of the corresponding coordinate on the chessboard with the character representing the player's chess pieces "*" "#" Just do it , Here we use "*" Pieces representing players ,"#" Chess pieces representing computers , Of course, you can use whatever you want to express , As long as it's a character .
void PlayerMove(char Board[ROW][COL], int row, int col)
{
// Use coordinates to represent the position
int x = 0;
int y = 0;
printf(" Players go \n");
while (1)// Considering that players may accidentally enter wrong coordinates ,so Should design while loop
{
printf(" Please enter the coordinates you want to enter : ");
scanf_s("%d%d", &x, &y);
// Judge x,y The validity of coordinates
if (x >= 1 && x <= row && y >= 1 && y <= col)
{
if (Board[x - 1][y - 1] == ' ')// user friendly design , There is no guarantee that every player knows the meaning of array subscript, so it is necessary to subtract one
{
Board[x - 1][y - 1] = '*';
break;
}
else
{
printf(" The coordinates are occupied \n");
}
}
else
{
printf(" Illegal coordinates , Please re-enter !\n");
}
}
}// Computer chess is simple , Go wherever there is a blank space
void ComputerMove(char Board[ROW][COL], int row, int col)
{
int x = 0;
int y = 0;
printf(" Computer go \n");
while (1)
{
// utilize rand Function constantly generates random numbers
x = rand() % row;
y = rand() % col;
if (Board[x][y] == ' ')// The computer knows the definition of array ,so There is no one minus here
{
Board[x][y] = '#';
break;
}
}
}
4. Judging rules or game rules Judge()
Three piece chess three piece chess , As the name suggests, it is a three piece chess ( Your boy is lying !) To make fun of
There are only four rules to judge whether you win or lose Three rows, three columns, two diagonals , As long as the chess pieces on these four lines are consistent, you will win
Of course, there should also be a function IsFull() Together to judge the current game state Is it a draw , Players win , Computer wins , Or should we continue the game
The code is as follows
int IsFull(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++)
{
if (Board[i][j] == ' ')
{
return 0;// Not full
}
}
}
return 1;// Full of
}char Judge(char Board[ROW][COL], int row, int col)
{
int i = 0;
// Three horizontal lines
for (i = 0; i < row; i++)
{
if (Board[i][0] == Board[i][1] && Board[i][1] == Board[i][2] && Board[i][1] != ' ')
{
return Board[i][1];
}
}
// Vertical three column
for (i = 0; i < col; i++)
{
if (Board[0][i] == Board[1][i] && Board[1][i] == Board[2][i] && Board[1][i] != ' ')
{
return Board[1][i];
}
}
// Two diagonals
if (Board[0][0] == Board[1][1] && Board[1][1] == Board[2][2] && Board[1][1] != ' ')
return Board[1][1];
if (Board[2][0] == Board[1][1] && Board[1][1] == Board[0][2] && Board[1][1] != ' ')
return Board[1][1];
// Judge if it's a draw
if (1 == IsFull(Board, ROW, COL))
{
return "Q";
}
// continue
return 'C';
}In terms of three lines and three columns, I think the code we write should be similar
But in the writing of the two diagonals, some friends will say , Since three lines and three columns can be expressed in cycles , Then the two diagonals should also be ok
for (i = 0; i < row; i++)// Top left - The lower right
{
if (Board[i][i] == Board[i + 1][i + 1])
continue;
else
break;
}
for (i = 0; i < row; i++)// The lower left - The upper right
{
if (Board[i][row-1-i] == Board[i + 1][row -2-i])// When i=2 The array will cross the boundary when
continue;
else
break;
}Yes , No problem in thinking , It will just cross the border , Can it be avoided ? The answer is yes . Just define ROW and COL When , Add more 2, such as , This program is a three piece chess ,ROW,COL by 3, Just define them as 5, Let the whole chessboard circle more , We are in the Board[][] When an array is operated, only the 1-3 That's it . Here is only the idea , If you are interested, you can try it yourself , I believe if you can try, you can find out n The writing method of Ziqi .
The global code is as follows
There are three plates , A header file game.h, Two source files test.c game.c
game.h
// Function declaration part
#define ROW 3
#define COL 3
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Statement
void InitializeBoard(char Board[ROW][COL], int row, int col);
void DisplayBoard(char Board[ROW][COL], int row, int col);
void PlayerMove(char Board[ROW][COL], int row, int col);
void ComputerMove(char Board[ROW][COL], int row, int col);
// Tell us about four game states
// Game player wins - '*'
// Computers win - '#'
// It ends in a draw - 'Q' Use a single character to express ow , Don't use strings to show your high English level , The more concise the better
// continue - 'C'
char Judge(char Board[ROW][COL], int row, int col);game.c
// Game module Function definition
#include<stdio.h>
#include "game.h"
void InitializeBoard(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] = ' ';
}
}
}
void DisplayBoard(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++)// Print page i The content of the line
{
// Print data lines
printf(" %c ", Board[i][j]);// Corresponding to 1 Green rounded square
if (j < col - 1)// The last column does not need to be printed "|"
{
printf("|");
}
}
printf("\n");// Line feed ready to print split lines
// Print split lines
if (i < row - 1)// There is no need to split the last line
{
for (j = 0; j < col; j++)
{
printf("---");
if (j < col - 1)
{
printf("|");
}
}
printf("\n");
}
}
}
void PlayerMove(char Board[ROW][COL], int row, int col)
{
// Use coordinates to represent the position
int x = 0;
int y = 0;
printf(" Players go \n");
while (1)// Considering that players may accidentally enter wrong coordinates ,so Should design while loop
{
printf(" Please enter the coordinates you want to enter : ");
scanf_s("%d%d", &x, &y);
// Judge x,y The validity of coordinates
if (x >= 1 && x <= row && y >= 1 && y <= col)
{
if (Board[x - 1][y - 1] == ' ')// user friendly design , There is no guarantee that every player knows the meaning of array subscript, so it is necessary to subtract one
{
Board[x - 1][y - 1] = '*';
break;
}
else
{
printf(" The coordinates are occupied \n");
}
}
else
{
printf(" Illegal coordinates , Please re-enter !\n");
}
}
}
// Computer chess is simple , Go wherever there is a blank space
void ComputerMove(char Board[ROW][COL], int row, int col)
{
int x = 0;
int y = 0;
printf(" Computer go \n");
while (1)
{
// utilize rand Function constantly generates random numbers
x = rand() % row;
y = rand() % col;
if (Board[x][y] == ' ')// The computer knows the definition of array ,so There is no one minus here
{
Board[x][y] = '#';
break;
}
}
}
// Judge whether the chessboard is full
// return 1 The chessboard is full
// return 0, The chessboard is not full
int IsFull(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++)
{
if (Board[i][j] == ' ')
{
return 0;// Not full
}
}
}
return 1;// Full of
}
// Three rows, three columns, two diagonals
char Judge(char Board[ROW][COL], int row, int col)
{
int i = 0;
// Three horizontal lines
for (i = 0; i < row; i++)
{
if (Board[i][0] == Board[i][1] && Board[i][1] == Board[i][2] && Board[i][1] != ' ')
{
return Board[i][1];
}
}
// Vertical three column
for (i = 0; i < col; i++)
{
if (Board[0][i] == Board[1][i] && Board[1][i] == Board[2][i] && Board[1][i] != ' ')
{
return Board[1][i];
}
}
// Two diagonals
if (Board[0][0] == Board[1][1] && Board[1][1] == Board[2][2] && Board[1][1] != ' ')
return Board[1][1];
if (Board[2][0] == Board[1][1] && Board[1][1] == Board[0][2] && Board[1][1] != ' ')
return Board[1][1];
// Judge if it's a draw
if (1 == IsFull(Board, ROW, COL))
{
return "Q";
}
// continue
return 'C';
}
test.c
// To test our three piece chess program Test module
#include "game.h"
void menu()
{
printf("************ Three chess game ***********\n");
printf("****** 1. play *** 0. exit ******\n");
printf("*********************************\n");
}
void game()
{
// Deposit Judge() The return value of the function
char ret = 0;
// Use an array to store the pieces we want to play
char Board[ROW][COL] = { 0 };
// Board initialization The elements in the array are spaces , Visually, the chessboard looks empty
InitializeBoard(Board,ROW,COL);// Because you want to use this initialization function , You have to declare , The initialization function is game Part of the function , So we should game.h This header file declares it
// Print chessboard
DisplayBoard(Board, ROW, COL);
// Playing chess , That is to say " Fill in the blanks ", Put the... On the initialized chessboard ' ' Replace with the chess pieces that players and computers want to go
while (1)
{
// Players go
PlayerMove(Board, ROW, COL);
DisplayBoard(Board, ROW, COL);
ret=Judge(Board, ROW, COL);
// Judge whether the player wins
if (ret != 'C')
{
break;
}
// Computer go
ComputerMove(Board,ROW,COL);
DisplayBoard(Board, ROW, COL);
// Judge whether the computer wins
ret = Judge(Board, ROW, COL);
if (ret != 'C')
{
break;
}
}
// Judge the remaining three situations
if (ret == '*')
{
printf(" Game player wins \n");
}
else if (ret == '#')
{
printf(" Computers win \n");
}
else
{
printf(" It ends in a draw \n");
}
}
void test()
{
int choice;
srand((unsigned int)time(NULL));// Time stamp , coordination rand function
do
{
menu();
printf(" Please select :\n");
scanf_s("%d", &choice);
switch (choice)
{
case 1:
printf(" Start the game \n");//system clc
game();
break;
case 0:
printf(" Quit the game ");
break;
default:
printf(" The input is invalid , Please re-enter \n");
}
} while (choice);
}
int main()
{
test();
return 0;
}
This is the sub child after three files are created

Finally, I attach the between me and the computer " game "

The latter
Some people may say that if only you could click with the mouse , Where you click, you'll be there , After all, this is a small program , Not a positive
A real game , And the editor's level is limited , Just started learning , It's a little difficult to realize , Today is a foreshadowing , Wait for me
I've almost learned , I'll make it up
If you want to communicate, you can comment or send a private message
Finally, I hope you can draw a mind map when doing similar problems with high comprehensiveness , benefits have a lucid brain , Don't think about
Step by step , Always tell yourself what to do at this step , What I want to achieve
The full text is more than 8800 words , After watching the screen for so long, you should pay attention to protecting your eyes
toodles !
边栏推荐
- 准备开始写博客了
- OJ 1507 deletion problem
- InitializingBean接口及示例
- Mysql-8.0.17-winx64 (additional Navicat) manual configuration version installation
- C语言memcpy库函数与memmove的作用
- NiO example
- 【C语言】字符串库函数介绍及模拟
- Leetcode brush question diary sword finger offer II 055. binary search tree iterator
- C语言的动态内存管理函数
- ZOJ Problem 1005 jugs
猜你喜欢

AQS之ReentrantLock源码解析
![[dynamic planning -- the best period for buying and selling stocks Series 2]](/img/6c/887a026d3c1bcbd278bb7f3e0afd05.png)
[dynamic planning -- the best period for buying and selling stocks Series 2]

Project compilation nosuch*** error problem

AQS之semaphore源码分析

万字归纳总结并实现各大常用排序及性能对比

Mysql-8.0.17-winx64 (additional Navicat) manual configuration version installation

下雨场景效果(一)

【C语言】字符串库函数介绍及模拟

Bug experience related to IAP jump of stm32

做气传导耳机最好的是哪家、最好的气传导耳机盘点
随机推荐
Leetcode brush question diary sword finger offer II 053. Medium order successor in binary search tree
[PTA----输出全排列]
数组解法秘籍
[PTA----树的遍历]
江中ACM新生10月26日习题题解
OJ 1020 最小的回文数
浮点型数据在内存中如何存储
OJ 1089 春运
Redis cache design and performance optimization
OJ 1018 报数游戏
Battle plague Cup -- strange shape
[pta-- use queues to solve the problem of monkeys choosing kings]
Project compilation nosuch*** error problem
项目编译NoSuch***Error问题
Leetcode brush question diary sword finger offer II 055. binary search tree iterator
代码整洁之道(二)
【动态规划--买卖股票的最佳时期系列3】
Network communication and tcp/ip protocol
What is hash? (development of Quantitative Trading Robot System)
New Selenium