当前位置:网站首页>Play Sanzi chess easily
Play Sanzi chess easily
2022-07-04 12:39:00 【Wake up after dark】
The interface for the final operation of Sanzi chess :
The thinking and steps of Sanzi chess :
First build game.h,game.c and test.c
game.h Declaration for function
game.c The realization of the game
test.c Test the logic of the game
Because playing games , Let players have a sense of experience , This is necessary do.....while Usage of
First write out the main function :
int main()
{
test();
return 0;
}
Again from test Nested in function :
Come up here do...while, The game has to have an interface , Can be directly used printf Print
void menu()
{
printf("***************************\n");
printf("****** 1.play ***********\n");
printf("****** 0.exit ***********\n");
printf("***************************\n");
}
Then enter , There are various options , It can be used switch Statement selection , choice 1 Start the game , choice 0 End the game , If other values are entered , It can be used default.
void test()
{
int input = 0;
do
{
menu();
printf(" Please select :");
scanf_s("%d", &input);
switch (input)
{
case 1:
game();
break;
case 0:
printf(" Quit the game \n");
break;
default:
printf(" Wrong choice , Please reselect \n");
break;
}
} while (input);
}
Simply running like this will result in an error ,, To be in game.c,test.c Must contain header files :
#include"game.h"
For the playability of the chessboard , If you want to play 10×10 perhaps 5×5 Of , that board[3][3] It can't be achieved , You can borrow global variables to complete , stay game.h In the definition of :
#define ROW 3 #define COL 3
First step : Initialize chessboard :
stay test.c Of game() Function
InitBoard(board, ROW, COL);
Secondly, in game.h Function declared in :
void InitBoard(char board[ROW][COL],int row,int col);
stay game.c Write the function of chessboard initialization in , It can be used for Circle to write :
void InitBoard(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++) { board[i][j] = ' '; } } }
Make the data on the chessboard blank , This print out is only blank , Nothing to see . Then go to the next step , Put the shape of the chessboard “ make ” come out .
The second print chessboard :
stay test.c Medium game() Input in function
Displayboard(board, ROW, COL);
stay game.h Function declared in :
void Displayboard(char board[ROW][COL], int row, int col);
And then game.c Write the function in
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++) { printf(" %c ", board[i][j]); if(j<col-1) printf("|"); } printf("\n"); if (i < row - 1) { for (j = 0; j < col; j++) { printf("---"); if (j < col - 1) printf("|"); } printf("\n"); } } }
To ensure that the chessboard is in this format
stay for In the internal circulation of Space %c Space ( %c ) As a whole, this writing is to relate to the following --- Corresponding , Achieve a sense of symmetry , Then print the vertical bar (|) But the internal circulation is j<col, It will lead to a vertical bar at the end of each line (|), Use at this time if Statement to resolve if(j<col-1) , After printing a line , To wrap printf("\n"); Print --- It's the same thing when I'm going to work , It's just if (i < row - 1) 了 .
The third step : Players play chess
stay test.c In the source file game() Input in function :
player_move(board, ROW, COL);
And then game.h Function declared in :
void player_move(char board[ROW][COL], int row, int col);
Last in game.c Write the function in :
void player_move(char board[ROW][COL], int row, int col) { int x = 0; int y = 0; printf(" Players play chess \n"); while (1) { printf(" Please enter the coordinates :"); scanf_s("%d %d", &x, &y); if (x >= 1 && x <=row && y >= 1 && y <=col) { // Playing chess if (board[x - 1][y - 1] == ' ') { board[x - 1][y - 1] = '*'; break; } else { printf(" The coordinates are occupied , Please re-enter \n"); } } else { printf(" The coordinates are illegal , Please re-enter \n"); } } }
Because it is to let players experience the game , Set up 2 A variable , For players to input , Players may not know that the subscript of the array is from 0 At the beginning , so
if (x >= 1 && x <=row && y >= 1 && y <=col)
Now write 3×3 Of , When inputting coordinates , The horizontal and vertical coordinates are from 1 To 3, But the subscript of the array is from 0 To 2, Difference between 1, so
board[x - 1][y - 1]
Because it's a three piece chess game , Before playing chess, you have to determine whether the entered coordinate position is a space , Otherwise, it will appear “ Repentance ” The phenomenon of , If it's still a space
board[x - 1][y - 1] = '*';
then break Jump out of , If occupied , Just else
else { printf(" The coordinates are occupied , Please re-enter \n"); }
Is that the end of it ???
No ! No ! No !
If the coordinates entered by the player are not or out of range , The program doesn't work , So again else
else { printf(" The coordinates are illegal , Please re-enter \n"); }
Step four : The computer plays chess
First, in the test.c Medium game() Function input :
Displayboard(board, ROW, COL);
And then game.h This function is declared in :
void computer_move(char board[ROW][COL], int row, int col);
Last in game.c Write functions in :
void computer_move(char board[ROW][COL], int row, int col) { int x = 0; int y = 0; printf(" The computer plays chess \n"); while (1) { x = rand() % row; y = rand() % col; if (board[x][y] = ' ') { board[x][y] = '#'; break; } } }
Because it's computer chess for simplicity , Let the computer input coordinates randomly .rand Remainder row What you get is row-1.rand The function is to give a random value .srand The argument type of the function is unsigned integer , Its purpose is to define rand Start of , Function header file stdlib.h. Time stamp function time() The return value of can be used as a parameter to increase the randomness , Function header file time.h.srand Use with timestamp , Only by defining it once can we guarantee the maximum randomness , So we define it in the main function srand. So in test In the function
srand((unsigned int)time(NULL));
stay game.h Add header file in
#include<stdlib.h> #include<time.h>
At this time, the functions of players and computers playing chess are written , Games come and go , Players have played , Under the computer , Under the computer , Player down ....... Cycle down , At this time test.c Used in the source file while Loop to execute
while (1) { // Players play chess player_move(board, ROW, COL); Displayboard(board, ROW, COL); // The computer plays chess computer_move(board, ROW, COL);// Random chess Displayboard(board, ROW, COL); }
Step five : Judgement of winning or losing
Game is a process , You have to win or lose in the end , There are : Game player wins , Computers win , It ends in a draw
Then output the result , For convenience :
Game player wins Output *
Computers win Output #
It ends in a draw Output Q
If you still want to play, output C
stay test.c in while Change in the cycle , After the initial game , The player will judge the next time , Judge whether the player has won , If you win, then break Jump out of , Output * ; If the player doesn't win , Computer next time , Judge whether the computer has won , If the computer wins , It's also break Jump out of , Output # . If it's full at last , Did not win the output Q . So write a function to judge whether you win or lose :
Again test.c in game() Function
ret=is_win(board,ROW,COL);
And then game.h Function declared in :( Because the output is characters , So the return type should be char)
char is_win(char board[ROW][COL], int row, int col);
Again game.c Write functions in functions :
char is_win(char board[ROW][COL], int row, int col)
{
int i = 0;
// Judgment line
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];
}
}
// Judgment 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];
}
}
// Judging diagonals
if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[1][1] != ' ')
{
return board[1][1];
}
if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[1][1] != ' ')
{
return board[1][1];
}
// Judge a draw
if (if_full(board, row, col) == 1)
{
return 'Q';
}
return 'C';
}
In order to decide whether to win or lose , There are no more than three ways to win a three piece chess game : One line is the same , One column is the same , The diagonals are the same
First look at the first one : One line is the same
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];
}
}
Ensure that adjacent ones are the same and not blank , At this time, players win , At this time, output * 了 , But if players don't want to use * play , Want to use other characters instead , This time back * It's not true , but , We can return one of our peers .
Then the second : One column is the same
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];
}
}
Ensure that adjacent ones are the same and not blank , At this time, the computer wins , At this time, output # 了 , But if the computer also has a temper , Don't want to use # play , Want to use other characters instead , This time back # It's not true , but , We can return one of our peers .
Finally, the third : The diagonals are the same
if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[1][1] != ' ')
{
return board[1][1];
}
if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[1][1] != ' ')
{
return board[1][1];
}
There are two diagonal lines , Two to write if sentence , Just make sure that the diagonals are the same .
There is also a draw
if (if_full(board, row, col) == 1)
{
return 'Q';
}
return 'C';
}
Is to judge whether the chessboard is no longer a space , At this time, we have to write a function to judge whether the chessboard is full . Because it's over , I don't want any more trouble , Can be directly in game.c Write functions in , Write a case that only belongs to it , At this time, you can use local variables static Usage of
static int if_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; // Not full
}
}
}
return 1; // Full of
}
If full, return 1, If not, return 2, If you still want to play, go back C.
The complete code is as follows :
test.c:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include"game.h"
void menu()
{
printf("***************************\n");
printf("****** 1.play ***********\n");
printf("****** 0.exit ***********\n");
printf("***************************\n");
}
void game()
{
char ret = 0;
// Store chess data
char board[ROW][COL]={0};
// Initialize the chessboard to space
InitBoard(board, ROW, COL);
// Print chessboard
Displayboard(board, ROW, COL);
while (1)
{
// Players play chess
player_move(board, ROW, COL);
Displayboard(board, ROW, COL);
// Judgement of winning or losing
ret=is_win(board,ROW,COL);
if (ret != 'C')
{
break;
}
// The computer plays chess
computer_move(board, ROW, COL);// Random chess
Displayboard(board, ROW, COL);
ret = is_win(board, ROW, COL);
if (ret != 'C')
{
break;
}
}
if (ret == '*')
{
printf(" The player won \n");
}
else if (ret == '#')
{
printf(" The computer won \n");
}
else
{
printf(" It ends in a draw \n");
}
}
// The ending
// Game player wins *
// Computers win #
// It ends in a draw Q
// continue C
void test()
{
int input = 0;
srand((unsigned int)time(NULL));
do
{
menu();
printf(" Please select :");
scanf_s("%d", &input);
switch (input)
{
case 1:
game();
break;
case 0:
printf(" Quit the game \n");
break;
default:
printf(" Wrong choice , Please reselect \n");
break;
}
} while (input);
}
int main()
{
test();
return 0;
}
game.c:
#define _CRT_SECURE_NO_WARNINGS 1
#include"game.h"
void InitBoard(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++)
{
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++)
{
printf(" %c ", board[i][j]);
if(j<col-1)
printf("|");
}
printf("\n");
if (i < row - 1)
{
for (j = 0; j < col; j++)
{
printf("---");
if (j < col - 1)
printf("|");
}
printf("\n");
}
}
}
void player_move(char board[ROW][COL], int row, int col)
{
int x = 0;
int y = 0;
printf(" Players play chess \n");
while (1)
{
printf(" Please enter the coordinates :");
scanf_s("%d %d", &x, &y);
if (x >= 1 && x <=row && y >= 1 && y <=col)
{
// Playing chess
if (board[x - 1][y - 1] == ' ')
{
board[x - 1][y - 1] = '*';
break;
}
else
{
printf(" The coordinates are occupied , Please re-enter \n");
}
}
else
{
printf(" The coordinates are illegal , Please re-enter \n");
}
}
}
void computer_move(char board[ROW][COL], int row, int col)
{
int x = 0;
int y = 0;
printf(" The computer plays chess \n");
while (1)
{
x = rand() % row;
y = rand() % col;
if (board[x][y] = ' ')
{
board[x][y] = '#';
break;
}
}
}
static int if_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; // Not full
}
}
}
return 1; // Full of
}
char is_win(char board[ROW][COL], int row, int col)
{
int i = 0;
// Judgment line
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];
}
}
// Judgment 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];
}
}
// Judging diagonals
if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[1][1] != ' ')
{
return board[1][1];
}
if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[1][1] != ' ')
{
return board[1][1];
}
// Judge a draw
if (if_full(board, row, col) == 1)
{
return 'Q';
}
return 'C';
}
game.h:
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define ROW 3
#define COL 3
// Initialize chessboard
void InitBoard(char board[ROW][COL],int row,int col);
// Print chessboard
void Displayboard(char board[ROW][COL], int row, int col);
// Players play chess
void player_move(char board[ROW][COL], int row, int col);
// The computer plays chess
void computer_move(char board[ROW][COL], int row, int col);
// Judgement of winning or losing
char is_win(char board[ROW][COL], int row, int col);
Welcome to try !
边栏推荐
- 2022, 6G is heating up
- Experiment 7. IPv6
- Entity framework calls Max on null on records - Entity Framework calling Max on null on records
- [Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 17
- Show recent errors only command /bin/sh failed with exit code 1
- Guava ImmutableSet. Builder source code analysis, shift original code, complement code, reverse code review
- Paper notes ACL 2020 improving event detection via open domain trigger knowledge
- [Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 14
- The latest idea activation cracking tutorial, idea permanent activation code, the strongest in history
- Article download address
猜你喜欢
It's hard to hear C language? Why don't you take a look at this (V) pointer
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 20
Experiment 7. IPv6
Ml and NLP are still developing rapidly in 2021. Deepmind scientists recently summarized 15 bright research directions in the past year. Come and see which direction is suitable for your new pit
Abnormal mode of ARM processor
Decrypt the advantages of low code and unlock efficient application development
Entitas learning [iv] other common knowledge points
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 7
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 6
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 16
随机推荐
Btrace tells you how to debug online without restarting the JVM
Classification and application of AI chips
Recommend a cool geospatial data visualization tool with low code
Global and Chinese market of dental elevators 2022-2028: Research Report on technology, participants, trends, market size and share
2022, 6G is heating up
[notes] in depth explanation of assets, resources and assetbundles
Global and Chinese market of piston rod 2022-2028: Research Report on technology, participants, trends, market size and share
Detailed explanation of NPM installation and caching mechanism
[notes] streamingassets
Snowflake won the 2021 annual database
[Android reverse] function interception instance (③ refresh CPU cache | ④ process interception function | ⑤ return specific results)
03_ Armv8 instruction set introduction load and store instructions
C语言:求字符串的长度
17. Memory partition and paging
Tableau makes data summary after linking the database, and summary exceptions occasionally occur.
Openssl3.0 learning 20 provider KDF
13、 C window form technology and basic controls (3)
Haproxy cluster
Kivy教程之 08 倒计时App实现timer调用(教程含源码)
Entitas learning [3] multi context system