Gobang - C language entry-level games (nanny tutorial)

catalogue

Rules of the game

Game creation ideas

Game design

1. Design of game menu page

2. Chessboard initialization

3. Chessboard printing

4. Players play chess

5. Computer chess

 6. Judgment of victory and defeat

"Start game"

As the "big guys" on the road for the first time, they have learned the elementary C language for a short time. It's hard to calm down if they don't find a target to try their hand, isn't it? Today, the little blogger recommends a player to practice - Sanzi chess. Speaking of this, our next door classmate Lao Wang spoke. I can't write. What should I do? Boy, is that a problem? Obviously, this is not a problem. Next, xiao'an takes you to write a small Sanzi game.

Well, the old rule, fasten your seat belt, and the old driver is ready to start ~ woo woo

Rules of the game

The premise of writing a game is that we can already play the game. In order to prevent some students from not playing it, let's first introduce the rules of the game:

1. The game generally adopts 3 × 3 chessboard

2. The game is played by two players in turn

3. The two sides take turns to the next chess piece each time

4. Winning criteria: players connect their three pieces horizontally, vertically and obliquely, and win in one of the cases

Game creation ideas

First, we open the editor and create the following three new items

  1. test.c - Test game
  2. game.h -- Declaration of game function
  3. game.c -- implementation of game function

//Here we declare the declaration and implementation of the following game functions. The names can be different, but we strongly recommend consistency, because it is convenient for us to find.

Game design

1. Design of game menu page

First of all, when our old driver drives into the game, the first thing that appears should be our menu interface.

At this time, we need to choose to use the "menu function" (menu ()) to realize this function. The purpose of this is to make the game repeat many times, improve the repeatability of the program and ensure that the functions of code blocks are used in blocks.

The game menu should realize these functions:

  1. Start the game
  2. Exit the game
  3. Return of illegal input

Next is our code block to realize this function:

void menu()//Print menu
{
	printf("************************************************\n");
	printf("****************   1.Start the game   ****************\n");
	printf("****************   0.Exit the game   ****************\n");
	printf("************************************************\n");
}

And the code of the selection module:

void test_game()//Test game panel
{
	int input = 0;
	srand((unsigned int)time(NULL));//random number
	do
	{
		menu();
		scanf("%d", &input);
		switch (input)
		{
		case 1:
			game();
			break;
		case 0:
			printf("Exit the game\n");
			break;
		default:
			printf("Input error, please re-enter\n");
			break;
		}
	} while (input);
}

So what will happen after this code is operated by one of our old drivers?

 

 

At this time, Lao Wang's children's boots spoke. It's good to be Lao Wang's classmate again. Lao Wang: Master, there are only cars, no oil, no pilots and no venues. Cough, what's the hurry? It's coming

2. Chessboard initialization

At the beginning of the game, we need to initialize the chessboard and empty the chessboard to ensure the normal progress of subsequent games. At the beginning of the game, we need to initialize the chessboard and empty the chessboard to ensure the normal progress of subsequent games. We will use the "InitBoard()" function to initialize each checkerboard as a space.

The code is as follows:

//Initialize all chessboard elements to 0
	char board[ROW][COL] = { 0 };
	//Change each element of the chessboard into a space
	InitBoard(board, ROW, COL);
	

       

void InitBoard(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] = ' ';
		}
	}
}

3. Chessboard printing

After having a dream, how can light work in the brain? It must not be visible or palpable. Therefore, after completing the initialization of the chessboard, we need to show the initialized chessboard,.

Here, the old drivers need to use the function "BoardDisplay()" to implement it.

The code implementation is as follows:

//Print chessboard
	DisplayBoard(board, ROW, COL);
void DisplayBoard(char board[ROW][COL], int row, int col)
{
	int i = 0;
	int j = 0;
	for (i = 0; i < row; i++)
	{
		if (i < row)//Print delimited lines
		{
			for (j = 0; j < row; j++)
			{
				printf("---");
				if (j < col - 1)
					printf("+");
			}
		}
		printf("\n");  //Line feed
		for (j = 0; j < col; j++)
		{
			printf(" %c ", board[i][j]);
			if (j < col - 1)
				printf("|");//Print space between squares
		}
		printf("\n");//Line feed
	}
	for (j = 0; j < row; j++)
	{
		printf("---");
		if (j < col - 1)
			printf("+");
	}
	printf("\n");
}

//The excellent Lao Wang children's boots will speak again here. He said what if I don't want to have the same chessboard size every time?

Here, I want to tell Lao Wang children's boots that we need to use the global variables ROW and COL ¢ to operate. By changing the values of these two global variables, we can operate the size pattern of the chessboard.

The code runs as follows:

Next, the venue was found, and Lao Wang's children's boots told us that he didn't know how to float. Why don't you show him?

 

4. Players play chess

Next, let's realize the function of old players playing chess.

To complete this function, we need to pay attention to the following points:

Receive - accept the address position entered by the player (the array element we judge should be the value entered by the player - 1, because the starting position of the subscript of the array element is 0)

Judge - judge whether the address entered by the player has been settled

Storage - drop the player's pieces into the corresponding location

Code implementation:

//Players start playing chess
		player_move(board, ROW, COL);
		DisplayBoard(board, ROW, COL);
		win = IsWin(board, ROW, COL);
		if (win != 'C')
			break;
void player_move(char board[ROW][COL], int row, int col)
{
	printf("Players play chess, please enter coordinates->\n");
	int x = 0;
	int y = 0;
	while (1)
	{
		scanf("%d %d", &x, &y);
		if (x >= 1 && y >= 1 && x <= row && y <= col)
		{
			if (board[x - 1][y - 1] == ' ')
			{
				board[x - 1][y - 1] = '*';
				break;
			}
			else
			{
				printf("There are pieces in this coordinate, please repeat the previous operation\n");
			}
		}
		else
		{
			printf("The coordinate does not exist, please repeat the previous operation\n");
		}
	}
}

Operation results:

5. Computer chess

When playing chess on the computer, he must play it at random. The so-called no move wins with a move

To realize computer random chess, we need to set a random number

x = rand() % row;
y = rand() %  col;     To create a random number of coordinates

Of course, computer chess is consistent with players' chess, and they should also abide by the rules (accept, judge and store)

Code implementation:

//The computer began to play chess
		computer_move(board, ROW, COL);
		DisplayBoard(board, ROW, COL);
		win = IsWin(board, ROW, COL);
void computer_move(char board[ROW][COL], int row, int col)
{
	printf("Computer chess->\n");
	int x = 0;
	int y = 0;
	while (1)
	{
		x = rand() % row;//x belongs to 0 to 2
		y = rand() % col;//y belongs to 0 to 2
		if (board[x - 1][y - 1] == ' ')
		{
			board[x - 1][y - 1] = '#';
			break;
		}
	}

Code running result:

Lao Wang's children's boots said again, yes, it's him again, very excellent!

Lao Wang: we don't know who is the God of cars in the end!

You see, you see, it hasn't started yet. The desire to win or lose is coming out. Good. Come on

 6. Judgment of victory and defeat

Here, we use the Iswin() function to determine the outcome.

In this function, we need to implement the following logic:

To return to four different states

Players win -- > return '*'

Computer win -- > return '#'

Draw -- > return 'C'

Game continues -- > return to 'E'

Judge the winner or loser and return to * player wins, # computer wins, 'C' continues and 'E' draws

The code is as follows:

	//Judge the winner or loser and return to * player wins, # computer wins, 'C' continues and 'E' draws
		//char win = IsWin(board, ROW, COL);
if (win == '#')
		printf("My God, you're not even as good as artificial intelligence\n");
	else if (win == '*')
		printf("Wow, congratulations on your victory\n");
	else
		printf("I'm sorry, you're fifty-five with the computer\n");

When implementing the function of Iswin(), the old drivers should pay attention to the following points:

Judgment line

Judgment column

Judge diagonal

Judge whether the chessboard is full -- > confirm whether the game continues (an Is_full() function is required to realize this function)

char IsWin(char board[ROW][COL], int row, int col)
{
	int i = 0;
	int j = 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];
		}
	}
	//Judge diagonal
	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 whether there is a draw. If the chessboard is full and there is no winner, there will be a draw
	if (IsFull(board, ROW, COL))
	{
		return 'E';
	}
	else
		return 'C';
}
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;//There are spaces. The chessboard is not full. Continue
			}
		}
	}
	return 1;//If no space is found, return 1 and draw
}

"Start game"

Finally, family members, dear old drivers, the moment we look forward to is coming!!!

I declare the game open:

Wow, let's congratulate Lao Wang children's boots with the warmest applause!!!

 

test.c:

#define _CRT_SECURE_NO_WARNINGS 1

#include "szq.h"

void menu()//Print menu
{
	printf("************************************************\n");
	printf("****************   1.Start the game   ****************\n");
	printf("****************   0.Exit the game   ****************\n");
	printf("************************************************\n");
}
void game()
{
	//Initialize all chessboard elements to 0
	char board[ROW][COL] = { 0 };
	//Change each element of the chessboard into a space
	InitBoard(board, ROW, COL);
	//Print chessboard
	DisplayBoard(board, ROW, COL);
	char win = 0;
	while (1)
	{
		//Players start playing chess
		player_move(board, ROW, COL);
		DisplayBoard(board, ROW, COL);
		win = IsWin(board, ROW, COL);
		if (win != 'C')
			break;
		//The computer began to play chess
		computer_move(board, ROW, COL);
		DisplayBoard(board, ROW, COL);
		win = IsWin(board, ROW, COL);
		if (win != 'C')
			break;
		//Judge the winner or loser and return to * player wins, # computer wins, 'C' continues and 'E' draws
		//char win = IsWin(board, ROW, COL);
	}
	if (win == '#')
		printf("My God, you're not even as good as artificial intelligence\n");
	else if (win == '*')
		printf("Wow, congratulations on your victory\n");
	else
		printf("I'm sorry, you're fifty-five with the computer\n");
}
void test_game()//Test game panel
{
	int input = 0;
	srand((unsigned int)time(NULL));//random number
	do
	{
		menu();
		printf("Dear old driver, please enter:>");
		scanf("%d", &input);
		switch (input)
		{
		case 1:
			game();
			break;
		case 0:
			printf("Exit the game\n");
			break;
		default:
			printf("Input error, please re-enter\n");
			break;
		}
	} while (input);
}
int main()
{
	test_game();
	return 0;
}

saq.c:

#define _CRT_SECURE_NO_WARNINGS 1

#include "szq.h"

void InitBoard(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;
	int j = 0;
	for (i = 0; i < row; i++)
	{
		if (i < row)//Print delimited lines
		{
			for (j = 0; j < row; j++)
			{
				printf("---");
				if (j < col - 1)
					printf("+");
			}
		}
		printf("\n");  //Line feed
		for (j = 0; j < col; j++)
		{
			printf(" %c ", board[i][j]);
			if (j < col - 1)
				printf("|");//Print space between squares
		}
		printf("\n");//Line feed
	}
	for (j = 0; j < row; j++)
	{
		printf("---");
		if (j < col - 1)
			printf("+");
	}
	printf("\n");
}
void player_move(char board[ROW][COL], int row, int col)
{
	printf("Players play chess, please enter coordinates->\n");
	int x = 0;
	int y = 0;
	while (1)
	{
		scanf("%d %d", &x, &y);
		if (x >= 1 && y >= 1 && x <= row && y <= col)
		{
			if (board[x - 1][y - 1] == ' ')
			{
				board[x - 1][y - 1] = '*';
				break;
			}
			else
			{
				printf("There are pieces in this coordinate, please repeat the previous operation\n");
			}
		}
		else
		{
			printf("The coordinate does not exist, please repeat the previous operation\n");
		}
	}
}
void computer_move(char board[ROW][COL], int row, int col)
{
	printf("Computer chess->\n");
	int x = 0;
	int y = 0;
	while (1)
	{
		x = rand() % row;//x belongs to 0 to 2
		y = rand() % col;//y belongs to 0 to 2
		if (board[x - 1][y - 1] == ' ')
		{
			board[x - 1][y - 1] = '#';
			break;
		}
	}
}
char IsWin(char board[ROW][COL], int row, int col)
{
	int i = 0;
	int j = 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];
		}
	}
	//Judge diagonal
	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 whether there is a draw. If the chessboard is full and there is no winner, there will be a draw
	if (IsFull(board, ROW, COL))
	{
		return 'E';
	}
	else
		return 'C';
}
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;//There are spaces. The chessboard is not full. Continue
			}
		}
	}
	return 1;//If no space is found, return 1 and draw
}

saq.h:

#pragma once
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define ROW 3
#define COL 3

void InitBoard(char board[ROW][COL], int row, int col);
void DisplayBoard(char board[ROW][COL], int row, int col);
void player_move(char board[ROW][COL], int row, int col);
void computer_move(char board[ROW][COL], int row, int col);
char IsWin(char board[ROW][COL], int row, int col);

Thank you for your patience, and express your heartfelt thanks again. I hope it will help the students in their study. If you think it's good, you can pay attention to xiao'an. When there's something good next time, we'll see it first. Thank you for your support!!!

 

 

 

Keywords: C

Added by wrathyimp on Wed, 02 Mar 2022 06:22:43 +0200