Elementary c language: Practical game three chess

foreword

Everyone has been studying with bloggers for a while, and today I will talk about an interesting practical project-three chess

Table of contents

foreword

make menu

Building a Game Selection Framework

Realize the game function

modular programming

Initialize the board

print checkerboard

 player playing chess

computer chess

Timestamp: Recommend an article

Method of generating random numbers in C language_c language random numbers_Cup shallow blog-CSDN blog

judge win or lose

game logic implementation


make menu

   When playing games, we will have menu options when we enter the game, choose to start the game, launch the game and other instructions. When it comes to selection, then we can first complete the design of the basic framework based on the loop and branch statements we have learned .

First of all, when we enter the game, we will first display the options, make a choice, and play a game while playing the game. What should we do if we want to play again (think about the structure of our previous knowledge that meets the requirement of entering the game first and then recirculating the menu) ) That must be the loop structure of do...while is more suitable, then we first use the function to print out a menu option

void menu()
{
	printf("*****************************\n");
	printf("*****************************\n");
	printf("**********1.play^************\n");
	printf("**********0.exit^************\n");//菜单
	printf("*****************************\n");
	printf("*****************************\n");
}

int main()
{int a = 0;
    do
 {
  menu();
  printf("请选择:");
  scanf("%d",&a);

 
 }while();  
return 0;
}

Building a Game Selection Framework

The game menu has been displayed on the screen, now you need to complete the selection, and play a game while playing the game, what should you do if you want to play.

At this time, it is necessary to apply the switch statement explained by the blogger before :

int main()
{
	int input = 0;
	do
	{
		menu();
		printf("PLEASE SELECT:");
		scanf("%d", &input);
		switch(input)
		{
		case 1:
			game();    //以上为界面的选择
			break;
		case 0:
			printf("Exit\n");
			break;
		default:
			printf("ERRO,PLEASE CHOOSE AGAIN\n");
			break;
		}
	} while (input);//while循环可以利用0为假,其余为来实现用户可反复选择
//直到选到合适为止
	return 0;
}                     

Realize the game function

modular programming

Here the blogger introduces a concept: modular programming. It is easy to reference, it will not appear top-heavy, and it is not easy to be stolen when converted to a static library. Here you need to create three files: test.c game.c game.h   

test.c: is used to realize the game logic game.c: the function used to realize the game function game.h: used to declare the game function function (can be quoted)

Traditional programming: all functions are placed in main.c. If many modules are used, there will be a lot of codes in one file, which is not conducive to the organization and management of codes, and it will greatly affect the programmer's thinking.

Modular programming: Put the code of each module in different .c files, and provide the declaration of external callable functions in the .h file. When other .c files want to use the code, you only need to #include "XXX.h "The file is fine. The use of modular programming can greatly improve the readability, maintainability, portability, etc. of the code.

Traditional programming: all functions are placed in main.c. If many modules are used, there will be a lot of codes in one file, which is not conducive to the organization and management of codes, and it will greatly affect the programmer's thinking.

Modular programming: Put the code of each module in different .c files, and provide the declaration of external callable functions in the .h file. When other .c files want to use the code, you only need to #include "XXX.h "The file is fine. Using modular programming can greatly improve the readability, maintainability, portability, etc. of the code!

In general: when you have a lot of code, you can use modular programming to complete the program. 

Backgammon, we need to enter the position to be played on the board, which is equivalent to a three-by-three array (here we use the knowledge of two-dimensional arrays), then we need to initialize the board before the game starts (make the array in the The elements are all spaces), then it is the array initialization assignment (just use a loop to traverse each element and assign spaces to it).

Note: When setting the function here, because a two-dimensional array is used, the formal parameters of the function are the array name, row, column

void initboard(char board[row][col], int hang, int lie)
{
	int i = 0;

	int j = 0;

	for (i = 0; i < hang; i++)
	{
		for (j = 0; j <lie; j++)
		{
			board[i][j] =' ';
		}	
		printf("\n");
	}
}

print checkerboard

Separate empty two-dimensional arrays with lines

void displayboard(char board[row][col], int hang, int lie) //可以随意控制棋盘大小
{
	int i = 0;
	for (i = 0; i <hang; i++)
	{
		int j = 0;
		for (j = 0; j <lie; j++)
		{
			printf(" %c ",board[i][j]);
			if (j < lie - 1)//为了不让最后一行打印‘|’
			printf("|");
		}
		printf("\n");
		if (i < hang - 1)
		{
			int j = 0;
			for (j = 0; j < lie; j++)
			{
				printf("---");
				if (j < lie - 1)
				printf("|");
			}
			printf("\n");
		}
	}
}

renderings

 player playing chess

If the player plays chess, use the * sign, and use the coordinates to replace the "space"

void player(board[row][col],int hang,int lie)
{
    int x = 0;
    int y = 0;
printf("玩家开始下棋");
scanf("%d %d",&a,&b);
if(x>=1&&x<=3&&y>=1&&y<=3)   
{  
   if(board[x-1][y-1]==' ')
      {board[x-1][y-1]='*';}
    else
{printf("坐标已经被占用,请重新选择");}
    else
{printf("坐标非法请重新输入");}
 }   
}

The player needs to have the opposite in order to play chess, which is our computer

computer chess

Timestamp: Recommend an article

Method of generating random numbers in C language_c language random numbers_Cup shallow blog-CSDN blog

void computer(char board[row][col], int hang, int lie)
{
	printf("电脑下棋\n");
	int x = 0;
	int y = 0;
	while(1)
	{ 
	x = rand() % hang;//0-2//模取余数不会超过这个数
	y = rand() % lie;
	if (board[x][y] ==' ')
	{
		board[x][y] = '#';
		break;
	}
	}
}

judge win or lose

Winning and losing situation analysis: row three in a row, column three in a row, two diagonal lines.

char panduan(char board[row][col], int hang, int lie)
{
	int i = 0;
	for (i = 0; i < hang; i++)//行
	{
		if(board[i][0]==board[i][1]&&board[i][1]==board[i][2] && board[i][1] != ' ')
		{
			return board[i][1];//电脑和玩家都可以用这一个判断
		}
	}
	int j = 0;
	for (j = 0; j< lie; j++)//列
{
	if (board[0][j] == board[1][j] && board[1][j] == board[2][j] && board[1][j] != ' ')
		{
			return board[1][j];
		}
	}
	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];
	}
	//平局
	if (isfull(board, hang, lie))
	{
		return 'q';//平局 else
	}	
	return 'c';
}

game logic implementation

Create a menu function to choose to enter the game and exit the game.
First, initialize the chessboard.
Then, print the chessboard again. Note: It must be initialized first and then print the chessboard.
The player plays chess and prints out the chessboard (the player enters the row and column coordinates to make a move, 'x' = the player moves)
to judge whether the player wins and whether to continue the game. (The character 'c' stands for the continuation of the game, the character 'q' stands for the draw of the game)
The computer plays chess (plays at a random position, 'o' = computer moves)
to judge ③ ways to win or lose! They are: player wins, computer wins, and draw.
Then, go back to step ①, whether to choose to enter the game or exit the game.
 

void game()
{
	int key = 0;
	char board[row][col] = { 0 };   //不直接写成数字,利于改变棋盘大小
	//初始化棋盘的函数
	initboard(board,row,col);
	displayboard(board,row,col);
	while(1)
	{
		player(board, row, col);
		key=panduan(board, row, col);
		if(key!='c')
		{
			break;
		}
		displayboard(board, row, col); 
		computer(board, row, col);
		key = panduan(board, row, col);
		if (key != 'c')
		{
			break;
		}
		displayboard(board, row, col);
	}	
	if (key == '*')
	{
		printf("玩家胜利\n");
	}
	else if(key=='#')
	{
		printf("电脑胜利\n");
	}
	else if(key=='p')
	{
		printf("平局\n");
	}
}

In addition, we also need to put game.c into game.h in the form of declaration:

#pragma once
#define _CRT_SECURE_NO_WARNINGS 
#include <stdio.h>
#include<windows.h>
#include<stdlib.h>
#include<time.h>//这个全可以调用
#define row 3
#define col 3
//初始化棋盘
void initboard(char board[row][col], int hang, int lie);
//打印棋盘 难点
void displayboard(char board[row][col], int hang, int lie);
//玩家下棋
void player(char board[row][col], int hang, int lie);
//电脑下棋
void computer(char board[row][col], int hang, int lie);
//判断输赢  玩家赢  电脑赢  平  继续/
char panduan(char board[row][col], int hang, int lie);
int isfull(char board[row][col], int hang, int lie);

Then use test.c to implement the game logic (you need to add #include''game.h'' at the beginning of editing)

Well, today’s article is here, I hope it will be helpful to everyone!


 

Guess you like

Origin blog.csdn.net/fcccfffg/article/details/132351419