当前位置:网站首页>(C language) implementation of Sanzi chess

(C language) implementation of Sanzi chess

2021-11-25 17:06:43 Xiangyanga

Preface : Unknowingly, I have learned C Language for a month , A lot of knowledge , In particular, I am very excited to learn how to write a small Sanzi game , Let's meet it today , Don't talk much , We officially start .

One . Sanzi

The Sanzi chess written this time is divided into three documents , They work on the same project , Respectively test.c、game.h、game.c,test.c File is mainly used to enter the game 、 Quit the game 、 Judgement of winning or losing 、 Print menu and other logic , and game.c Is used to write the main implementation method of the game ,game.h Then save the header file and function declaration .

The specific implementation of Sanzi chess is shown in the figure .
 Insert picture description here

Two . The logic of entering or exiting the game

1. test.c file

#include "game.h"
void menu() {
    
	printf("----------------------------------\n");
	printf("----------- 1.play -----------\n");
	printf("----------- 0.exit -----------\n");
	printf("----------------------------------\n");
}
void test() {
    
	int input = 0;
	do {
    
		menu();	// menu 
		printf(" Please select input 1/0: ");	// Choose to continue the game or exit 
		scanf("%d", &input);
		switch (input) {
    
		case 1:					// by 1 Then enter the game 
			printf(" Sanzi \n");
			break;
		case 0 :
			printf(" Quit the game \n");
			break;
		default:
			printf(" The number you entered is out of range , Please re-enter \n");
			break;
		}
		printf("\n");
	} while (input);	//input by 1 Continued to , by 0 Quit the game , For others, re-enter 
}

int main() {
    
	test();
	return 0;
}

Here you can put the header file to be referenced into game.h, So when game.c and test.c When the source file needs to reference the same header file, just reference game.h File can , This will be much more convenient . If both source files need to be referenced #include <stdio.h> Just put game.h I quote game.h file . Next, let's take a look at the above running results :

 Insert picture description here When the code runs without problems , I can put printf(“ Sanzi ”); Replace with game Function .

3、 ... and . Initialize chessboard

 Insert picture description here

1. test.c file ( I won't show you all later , Show only game The contents of the function )

#include "game.h"
void menu() {
    
	printf("----------------------------------\n");
	printf("----------- 1.play -----------\n");
	printf("----------- 0.exit -----------\n");
	printf("----------------------------------\n");
}

void game() {
    

	char board[ROW][COL] = {
     0 };	// To print a chessboard, you need to initialize a two-dimensional array to 0
	Init(board, ROW, COL);	// Initialize chessboard , That is, initialize the chessboard as a space .
}
void test() {
    
	int input = 0;
	do {
    
		menu();	// Menu selection 
		printf(" Please select input 1/0: ");	// Choose to continue the game or exit 
		scanf("%d", &input);
		switch (input) {
    
		case 1:					// by 1 Then enter the game 
			game();
			break;
		case 0 :
			printf(" Quit the game \n");
			break;
		default:
			printf(" The number you entered is out of range , Please re-enter \n");
			break;
		}
		printf("\n");
	} while (input);	//input by 1 Continued to , by 0 Quit the game , For others, re-enter 
}

int main() {
    
	test();
	return 0;
}

2. game.h file ( When you need to declare the function later, it will not be shown )


#include <stdio.h>
#define ROW 3 // That's ok 
#define COL 3 // Column 
void Init(char board[ROW][COL], int row, int col);// Initialize chessboard 

3. game.c file

#include "game.h"

void Init(char board[ROW][COL], int row, int col) {
      // Initialize chessboard 
	int i = 0;
	int j = 0;
	for (i = 0; i < row; i++) {
    
		for (j = 0; j < col; j++) {
    
			board[i][j] = ' ';
		}
	}
}

Defined here #define ROW 3 and #define COL 3 To make it easier for us to improve the code , For example, when we want to print a Gobang board, we put 3 Change it to 5.

Four . Print chessboard

1. test.c file

void game() {
    

	char board[ROW][COL] = {
     0 };	// To print a chessboard, you need to initialize a two-dimensional array to 0
	Init(board, ROW, COL);	// Initialize chessboard , That is, initialize the chessboard as a space .
	// Print chessboard 
	PrintBoard(board, ROW, COL);
}

2. game.c file

// Print chessboard 
void PrintBoard(char board[ROW][COL], int row, int col) {
     
	int i = 0;
	int j = 0;
	for (i = 0; i < row; i++) {
    		// Row cycle ( Outer layer )
		for (j = 0; j < col; j++) {
    		// Column loop ( Inner layer )
			printf(" %c ", board[i][j]);
			if (j < col - 1) {
    
				printf("|");	// There is no need to print after the last column |
			}
		}
		printf("\n");		    // Wrap after printing 
		if (i < col - 1) {
    		// Don't print under the last line ___
			for (j = 0; j < col; j++) {
    
				printf("___");
				if (j < col - 1) {
      
					printf("|");
				}
			}
		}
		printf("\n");// Wrap after printing 
	}
}

The result is shown in Fig. :
 Insert picture description here
 Insert picture description here

namely : Here is a set of data

 Insert picture description here

5、 ... and . Players play chess

1.test.c file

void game() {
    

	char board[ROW][COL] = {
     0 };	// To print a chessboard, you need to initialize a two-dimensional array to 0
	Init(board, ROW, COL);	// Initialize chessboard , That is, initialize the chessboard as a space .
	// Print chessboard 
	PrintBoard(board, ROW, COL);
	// Players and computers play chess '*' Representing game player ,'#' For computers .
	while (1) {
    
		player_move(board, ROW, COL);// Players play chess 
		PrintBoard(board, ROW, COL);// Continue printing after downloading 
	}
}

2. game.c file

// Players play chess 
void player_move(char board[ROW][COL], int row, int col) {
    
	int x = 0;	//x Axis 
	int y = 0;	//y Axis 
	printf(" Players enter : ");
	while (1) {
    
		scanf("%d %d", &x, &y);	// Enter coordinates 
		if ((x >= 1 && x <= row) && (y >= 1 && y <= col)) {
    	// Limit input range 
			if (board[x - 1][y - 1] == ' ') {
    	// It is necessary to judge whether characters have been entered in this coordinate , If not, print '*'
				board[x - 1][y - 1] = '*';
				break;
			}
			else {
    
				printf(" The coordinates you entered have been set , Please re-enter \n");
				break;	
			}
		}
		else {
    
			printf(" The coordinates you entered are invalid , Please re-enter \n");
			break;
		}
	}
}

use if (board[x - 1][y - 1] == ’ ') This statement is to prevent this coordinate from being set .
The use here is x-1、y-1 The reason is that :

 Insert picture description here

So you have to subtract 1, The operation result is :

 Insert picture description here

6、 ... and . The computer plays chess

1. test.c file

void game() {
    

	char board[ROW][COL] = {
     0 };	// To print a chessboard, you need to initialize a two-dimensional array to 0
	Init(board, ROW, COL);	// Initialize chessboard , That is, initialize the chessboard as a space .
	// Print chessboard 
	PrintBoard(board, ROW, COL);
	// Players and computers play chess '*' Representing game player ,'#' For computers .
	while (1) {
    
		player_move(board, ROW, COL);// Players play chess 
		PrintBoard(board, ROW, COL);// Continue printing after downloading 
		computer_move(board, ROW, COL);// The computer plays chess 
		PrintBoard(board, ROW, COL);// Continue printing after next 
	}
}

2. game.c file

// The computer plays chess 
void computer_move(char board[ROW][COL], int row, int col) {
    
	printf(" The computer plays chess : \n");
	while (1) {
    		// Use the loop until the computer meets the input .
		int x = rand() % row;	// Generate 0~2 Number of numbers 
		int y = rand() % col;	//0~2
		if (board[x][y] == ' ') {
    
			board[x][y] = '#';
			break;
		}
	}
}

Here the computer generates random numbers , utilize rand function , When generating random numbers, you need srand() Function assist , stay test.c In the document test Add... To the function srand((unsigned int)time(NULL)); This statement .

The running result is :
 Insert picture description here

7、 ... and . Judgement of winning or losing

1. test.c file

void game() {
    

	char board[ROW][COL] = {
     0 };	// To print a chessboard, you need to initialize a two-dimensional array to 0
	Init(board, ROW, COL);	// Initialize chessboard , That is, initialize the chessboard as a space .
	// Print chessboard 
	PrintBoard(board, ROW, COL);
	// Players and computers play chess '*' Representing game player ,'#' For computers .
	/*  If the player wins, he returns '*'  If the computer wins, it returns '#'  A draw returns to 'M'  Return character C It's not over  */
	// Judgement of winning or losing 
	char ret = 0;
	while (1) {
    
		// Players play chess 
		player_move(board, ROW, COL);
		PrintBoard(board, ROW, COL);// Continue printing after downloading 
		ret = is_win(board, ROW, COL);// Every time you finish, judge whether you win or lose .
		if (ret != 'C') {
    
			break; // Not equal to character C End of description 
		}
		// The computer plays chess 
		computer_move(board, ROW, COL);
		PrintBoard(board, ROW, COL);// Continue printing after next 
		ret = is_win(board, ROW, COL);// Every time you finish, judge whether you win or lose .
		if (ret != 'C') {
    
			break;
		}
	}
	if (ret == '*') {
    
		printf(" Game player wins \n");
	}
	else if (ret == '#') {
    
		printf(" Computers win \n");
	}
	else {
    
		printf(" It ends in a draw ");
	}
}

2. game.c file

// Judgement of winning or losing 
int is_full(char board[ROW][COL], int row, int col) {
    // Judge whether the chessboard is full , When it's full, it's a draw back 1, Not full return 0
	int i = 0;
	int j = 0;
	for (i = 0; i < row; i++) {
    
		for (j = 0; j < col; j++) {
    
			if (board[i][j] == ' '){
    
				return 0;
			}
		}
	}
	return 1;
}

char is_win(char board[ROW][COL], int row, int col) {
    
	int i = 0;
	// Determine whether the number of rows is connected ( There are three lines )
	for (i = 0; i < row; i++) {
    
		if ((board[i][0] == board[i][1] && board[i][1] == board[i][2]) && board[i][1] != ' ') {
    	// Exclude spaces 
			return board[i][0];// Return this number , May be * It could be #.
		}
	}
	// Determine whether the number of columns is connected ( Three columns in total )
	for (i = 0; i < col; i++) {
    
		if ((board[0][i] == board[1][i] && board[1][i] == board[2][i]) && board[1][i] != ' ') {
    	// Exclude spaces 
			return board[1][i];	// Return this number , May be * It could be #.
		}
	}
	// 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];
	}
	// It ends in a draw 
	if (is_full(board, row, col) == 1) {
      
		return 'M';
	}
	return 'C';
}

It is worth noting that players here will enter here next time is_win Function to determine and return a character , The computer judges a chess game once , Returns one character , Until we've got a win or a lose 、 It ends in a draw .
Running results :
Game player wins :
 Insert picture description here Computers win :
 Insert picture description here It ends in a draw :
 Insert picture description here

general act

1. test.c

#include "game.h"
void menu() {
    
	printf("----------------------------------\n");
	printf("----------- 1.play -----------\n");
	printf("----------- 0.exit -----------\n");
	printf("----------------------------------\n");
}

void game() {
    

	char board[ROW][COL] = {
     0 };	// To print a chessboard, you need to initialize a two-dimensional array to 0
	Init(board, ROW, COL);	// Initialize chessboard , That is, initialize the chessboard as a space .
	// Print chessboard 
	PrintBoard(board, ROW, COL);
	// Players and computers play chess '*' Representing game player ,'#' For computers .
	/*  If the player wins, he returns '*'  If the computer wins, it returns '#'  A draw returns to 'M'  Return character C It's not over  */
	// Judgement of winning or losing 
	char ret = 0;
	while (1) {
    
		// Players play chess 
		player_move(board, ROW, COL);
		PrintBoard(board, ROW, COL);// Continue printing after downloading 
		ret = is_win(board, ROW, COL);// Every time you finish, judge whether you win or lose .
		if (ret != 'C') {
    
			break; // Not equal to character C End of description 
		}
		// The computer plays chess 
		computer_move(board, ROW, COL);
		PrintBoard(board, ROW, COL);// Continue printing after next 
		ret = is_win(board, ROW, COL);// Every time you finish, judge whether you win or lose .
		if (ret != 'C') {
    
			break;
		}
	}
	if (ret == '*') {
    
		printf(" Game player wins \n");
	}
	else if (ret == '#') {
    
		printf(" Computers win \n");
	}
	else if (ret == 'M') {
    
		printf(" It ends in a draw \n");
	}
}
void test() {
    
	srand((unsigned int)time(NULL));// Time stamp 
	int input = 0;
	do {
    
		menu();	// Menu selection 
		printf(" Please select input 1/0: ");	// Choose to continue the game or exit 
		scanf("%d", &input);
		switch (input) {
    
		case 1:					// by 1 Then enter the game 
			game();
			break;
		case 0:
			printf(" Quit the game \n");
			break;
		default:
			printf(" The number you entered is out of range , Please re-enter \n");
			break;
		}
		printf("\n");
	} while (input);	//input by 1 Continued to , by 0 Quit the game , For others, re-enter 
}

int main() {
    
	test();
	return 0;
}

2. game.h

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROW 3
#define COL 3
void Init(char board[ROW][COL], int row, int col);// Initialize chessboard 
void PrintBoard(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);// Players play chess 
char is_win(char board[ROW][COL], int row, int col);// Judgement of winning or losing 

3. game.c

#include "game.h"
// Initialize chessboard 
void Init(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 PrintBoard(char board[ROW][COL], int row, int col) {
    
	int i = 0;
	int j = 0;
	for (i = 0; i < row; i++) {
    		// Row cycle ( Outer layer )
		for (j = 0; j < col; j++) {
    		// Column loop ( Inner layer )
			printf(" %c ", board[i][j]);
			if (j < col - 1) {
    
				printf("|");	// There is no need to print after the last column |
			}
		}
		printf("\n");		    // Wrap after printing 
		if (i < col - 1) {
    		// Don't print under the last line ---
			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) {
    
	int x = 0;	//x Axis 
	int y = 0;	//y Axis 
	printf(" Players play chess : ");
	
	while (1) {
    
		scanf("%d %d", &x, &y);	// Enter coordinates 
		if ((x >= 1 && x <= row) && (y >= 1 && y <= col)) {
    	// Limit input range 
			if (board[x - 1][y - 1] == ' ') {
    	// It is necessary to judge whether characters have been entered in this coordinate , If not, print '*'
				board[x - 1][y - 1] = '*';
				break;
			}
			else {
    
				printf(" The coordinates you entered have been set , Please re-enter \n");
			}
		}
		else {
    
			printf(" The coordinates you entered are invalid , Please re-enter \n");
		}
	}
}

// The computer plays chess 
void computer_move(char board[ROW][COL], int row, int col) {
    
	printf(" The computer plays chess : \n");
	while (1) {
    		// Use the loop until the computer meets the input .
		int x = rand() % row;	// Generate 0~2 Number of numbers 
		int y = rand() % col;	//0~2
		if (board[x][y] == ' ') {
    
			board[x][y] = '#';
			break;
		}
	}
}

// Judgement of winning or losing 
int is_full(char board[ROW][COL], int row, int col) {
    // Judge whether the chessboard is full , When it's full, it's a draw back 1, Not full return 0
	int i = 0;
	int j = 0;
	for (i = 0; i < row; i++) {
    
		for (j = 0; j < col; j++) {
    
			if (board[i][j] == ' ') {
    
				return 0;
			}
		}
	}
	return 1;
}
char is_win(char board[ROW][COL], int row, int col) {
    
	int i = 0;
	// Determine whether the number of rows is connected ( There are three lines )
	for (i = 0; i < row; i++) {
    
		if ((board[i][0] == board[i][1] && board[i][1] == board[i][2]) && board[i][1] != ' ') {
    	// Exclude spaces 
			return board[i][0];// Return this number , May be * It could be #.
		}
	}
	// Determine whether the number of columns is connected ( Three columns in total )
	for (i = 0; i < col; i++) {
    
		if ((board[0][i] == board[1][i] && board[1][i] == board[2][i]) && board[1][i] != ' ') {
    	// Exclude spaces 
			return board[1][i];// Return this number , May be * It could be #.
		}
	}
	// 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];
	}
	// It ends in a draw 
	if (is_full(board, row, col) == 1) {
      
		return 'M';
	}
	// continue 
	return 'C';
}

Well, today's three gobang is finished , If you like, you can like it , In addition, if there are any deficiencies, please point out in time . Thank you .

版权声明
本文为[Xiangyanga]所创,转载请带上原文链接,感谢
https://chowdera.com/2021/11/20211109073628514v.html

随机推荐