Write a trio game in c

Sanzi is a simple game that everyone played on paper with their desk when they were young. This game can be achieved in c language.

In this article, I recommend you use the compilers for vs2013, vs2019, vs2022, etc. Some schools use vc6.0 and Devc++. The former is a c language compiler introduced in 1998, which is not compatible with current win10 or win11 systems. Some problems may arise, and the latter will be discontinued in 2015. These two ancestor c language compilers are not recommended, but if they are required or explicitly required for your school exams, I will not say so.

First, we'll create a project. The three common files are the header file game.h, the source file game.c, and the text.c. In the header file of this game.h, we put in the declaration of the function, define the constants, and reference to the header file. In the text.c file, we write the program that the game is playing, and in the game.c file, we write the function that implements the game.  

1. text.c Source File Section

1. main function part

Because we are definitely not addicted to playing a game, we need to play a few more games. We write a do while loop statement in the main function in the text.c file to play multiple times. Then we write a menu function in the loop statement to print the menu. Then we'll enter a value on the keyboard to determine if we're playing, using a switch branch here. The game starts when the user enters the correct input value. Here, a game function is used to implement the game flow.

int main()
{
	int n = 0;

	srand((size_t)time(NULL));
	do
	{
		menu();//Print Menu
		printf("Please enter  ");
		scanf("%d", &n);
		switch (n)
		{
		case 1:game(); break;
		case 0:printf("Game over\n"); break;
		default:printf("Input error, please re-enter!\n"); break;
		}
	} while (n != 0);
	
}

main function part

​void menu()
{
	printf("******************************************\n");
	printf("********         1.play          *********\n");
	printf("********         0.exit          *********\n");
	printf("******************************************\n");
}

​

​

menu function part

2. game function part

In the game function, we want to achieve the main process of the game, first we want to print a 3*3 board, which is probably like this.

(Here we will first make clear the flow of the game, but as for the functions that implement those steps, we will go into more detail in the Game Source File section later.)

  Since each grid is empty at the beginning of the game and symbols are entered in the game between players and computers, we also define a two-dimensional array of char s and initialize it to '   ’. Then it's the chess stage. We'll play chess many times in a row, so this is done using a while loop statement, which can be written as a dead loop. When the following function determines that a player has won or drawn, it uses break to jump out of the loop, because after playing chess on a computer or a player, we want to see where we've played. So we want to print the board again after the players and computers play chess. After each person has finished playing chess, we have to decide whether they have won or not, so we use conditional statements to determine whether they have won, lost or drawn. We have finished our basic game flow in the coordination loop.

void game()
{
	char board[ROW][COL];//Define a two-dimensional array.
	initboard(board, ROW, COL);//Initialize the array.
    printboard(board, ROW, COL);//Print the board.

	while (1)
	{
		//Players play chess
		playerboard(board, ROW, COL);
		//Print board
		printboard(board, ROW, COL);
		//Judging whether or not to win
		if (iswinboard(board, ROW, COL) == '*')
		{
			printf("Player wins\n");
			printf("**********    Whether to proceed to the next round    **********\n");
			printf("\n");
			break;
		}
		else if (iswinboard(board, ROW, COL) == '#')
		{
			printf("Computer wins\n");
			printf("**********    Whether to proceed to the next round    **********\n");
			printf("\n");
			break;
		}
		else if (iswinboard(board, ROW, COL) == 'Q')
		{
			printf("It ends in a draw\n");
			printf("**********    Whether to proceed to the next round    **********\n");
			printf("\n");
			break;
		}
		

		//Computer Chess
		computermove(board, ROW, COL);
		//Print board
		printboard(board, ROW, COL);
		//Judging whether or not to win
		if (iswinboard(board, ROW, COL) == '*')
		{
			printf("Player wins\n");
			printf("**********    Whether to proceed to the next round    **********\n");
			printf("\n");
			break;
		}
		else if (iswinboard(board, ROW, COL) == '#')
		{
			printf("Computer wins\n");
			printf("**********    Whether to proceed to the next round    **********\n");
			printf("\n");
			break;
		}
		else if (iswinboard(board, ROW, COL) == 'Q')
		{
			printf("It ends in a draw\n");
			printf("**********    Whether to proceed to the next round    **********\n");
			printf("\n");
			break;
		}
	}
}

game function part

2. game.h Header File Section

In the header file we need to declare the function and define the constants. How to do this can be noted in the code below.

Here the rows and columns of our board are defined in the header file using ROW and COL to make it easier for us to change the size of the board later, only in the header file. We can also see below that there are many places where these two constants are used.

#pragma once
//Declare functions and define constants in the game header file.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>

//Const
#define ROW 3//Change the size of the board here by changing the values of ROW,COL
#define COL 3//can be changed to n*n's board.

//Function declaration
//Print board
void printboard(char board[ROW][COL], int row, int col);

//Initialize Array
void initboard(char board[ROW][COL], int row, int col);

//Players can play chess//2-D arrays without writing lines when passing function parameters
void playerboard(char board[][COL], int row, int col); 

//Computer Chess
void computermove(char board[ROW][COL], int row, int col);

//Judging whether or not to win
char iswinboard(char board[ROW][COL], int row, int col);

game.h section

3. game.c Source File Section

Remember which functions we used in text.c?

1. Let's first initialize a two-dimensional array

2. Print the board

3. Players play chess

4. Computer Chess

5. Judging victory

The next game.c file is to write functions that implement these steps.

First, it's easy to initialize the array, with two for loops.

//Initialize array elements
void initboard(char board[ROW][COL], int row, int col)
{
	int i = 0, j = 0;
	//Assign the array first, because it's an n*n array, so assign n*n times
	//This is done using two for loops.
	for (i = 0; i < row; i++)
	{
		for (j = 0; j < col; j++)
		{
			board[i][j] = ' ';
		}
	}
}

Initialize Array Element Function

Then print the board function.

In printing the board, we need to note that we need to print an array of rows, a line of'---'symbols. '|'does not print at the end of each line. In the bottom line'---|---|---'does not print, here we only need to control the for loop condition to achieve, it is not difficult.

 

//Print board
void printboard(char board[ROW][COL], int row, int col)
{
	int i = 0, j = 0;
	for (i = 0; i < row; i++)
	{
		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 < row; j++)
			{
				printf("---");
				if (j < row - 1)
				{
					printf("|");
				}

			}
		}
		
		printf("\n");
		
	}
}

Then the player's chess function

This means assigning values to arrays, because players may not have learned c or know that the subscripts of arrays in c start from 0, so we need to do array operations after coordinate-1 is entered. Here you can write an infinite loop to remind the player to restart when the player drops out of the illegal coordinates and break out when the player drops out correctly.

//Player's Chess Function
void playerboard(char board[][COL], int row, int col)
{
	int x = 0, y = 0;
	printf("Ask players to play chess\n");
	while (1)//Here you can write an infinite loop to remind the player to restart when an illegal coordinate is released.
			//break out again when the player is in the right position.
	{
		printf("Please enter coordinates,Please separate with spaces.    \n");
		scanf("%d %d", &x, &y);
		if (x >= 1 && x <= row && y >= 1 && y <= col)//Determine if the player's coordinates are correct.
		{
			if (board[x-1][y-1] == ' ')
			{
				board[x-1][y-1] = '*';
				break;
			}
			else
			{
				printf("Coordinates already occupied, please re-enter!");
			}
		}
		else
		{
			printf("Illegal coordinates, please re-enter!");
		}
	}
}

  Then Computer Chess

It is easier than playing chess on a computer. Just use rand ()%3 to randomly generate a value between 0 and 2 to determine if it is occupied.

//Computer Chess
void computermove(char board[ROW][COL], int row, int col)
{
	int x = 0; 
	int y = 0;
	printf("Computer Chess:>\n");
	while (1)
	{
		x= rand() % ROW;//Random values outside a loop can end up in an infinite loop.
		y= rand() % COL;
		if (board[x][y] == ' ')
		{
			board[x][y] = '#';
			break;
		}
	}
}

Finally, the function to determine whether or not to win

This is a long one, but it is basically if conditional statements to make judgments, to determine rows, columns, diagonals, and draws. If the victory is won, return to the symbols in one of the connected cells, so you don't have to worry about whether the computer or the player has won. Return to text.c and output accordingly.

//Judging whether or not to win
char iswinboard(char board[ROW][COL], int row, int col)
{
	int i = 0, j = 0, count = 0;

	//Judging whether the line won
	for (i=0;i<row;i++)
	{
		if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != ' ')
		{
			return board[i][0];
			break;
		}
	}
	//Determine whether a column won
	for (j = 0; j < col; j++)
	{
		if (board[0][j] == board[1][j] && board[1][j] == board[2][j] && board[0][j] != ' ')
		{
			return board[0][j];
			break;
		}
	}
	//Judging Diagonals
	if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != ' ')
	{
		return board[0][0];
	}
	if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] != ' ')
	{
		return board[0][2];
	}

	//Judge whether a draw is drawn
	for (i = 0; i < row; i++)
	{
		for (j = 0; j < col; j++)
		{
			if (board[i][j] == ' ')
			{
				count++;
			}
		}
	}
	if (count == 0)
	{
		return 'Q';
	}
	return 'C';
}

So we've written a trio game. You can send it to a friend or keep it private. (steam can't do it anymore, just play for yourself.)

Function

  Last but not least, put all the code here

game.h

#pragma once
//Declare functions and define constants in the game header file.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>

//Const
#define ROW 3//Change the size of the board here by changing the values of ROW,COL
#define COL 3//can be changed to n*n's board.

//Function declaration
//Print board
void printboard(char board[ROW][COL], int row, int col);

//Initialize Array
void initboard(char board[ROW][COL], int row, int col);

//Players can play chess//2-D arrays without writing lines when passing function parameters
void playerboard(char board[][COL], int row, int col); 

//Computer Chess
void computermove(char board[ROW][COL], int row, int col);

//Judging whether or not to win
char iswinboard(char board[ROW][COL], int row, int col);

text.c

#define _CRT_SECURE_NO_WARNINGS 1
#include"game.h"
void menu()
{
	printf("******************************************\n");
	printf("********         1.play          *********\n");
	printf("********         0.exit          *********\n");
	printf("******************************************\n");
}
void game()
{
	char board[ROW][COL];//Define a two-dimensional array.
	initboard(board, ROW, COL);//Initialize the array.
    printboard(board, ROW, COL);//Print the board.

	while (1)
	{
		//Players play chess
		playerboard(board, ROW, COL);
		//Print board
		printboard(board, ROW, COL);
		//Judging whether or not to win
		if (iswinboard(board, ROW, COL) == '*')
		{
			printf("Player wins\n");
			printf("**********    Whether to proceed to the next round    **********\n");
			printf("\n");
			break;
		}
		else if (iswinboard(board, ROW, COL) == '#')
		{
			printf("Computer wins\n");
			printf("**********    Whether to proceed to the next round    **********\n");
			printf("\n");
			break;
		}
		else if (iswinboard(board, ROW, COL) == 'Q')
		{
			printf("It ends in a draw\n");
			printf("**********    Whether to proceed to the next round    **********\n");
			printf("\n");
			break;
		}
		

		//Computer Chess
		computermove(board, ROW, COL);
		//Print board
		printboard(board, ROW, COL);
		//Judging whether or not to win
		if (iswinboard(board, ROW, COL) == '*')
		{
			printf("Player wins\n");
			printf("**********    Whether to proceed to the next round    **********\n");
			printf("\n");
			break;
		}
		else if (iswinboard(board, ROW, COL) == '#')
		{
			printf("Computer wins\n");
			printf("**********    Whether to proceed to the next round    **********\n");
			printf("\n");
			break;
		}
		else if (iswinboard(board, ROW, COL) == 'Q')
		{
			printf("It ends in a draw\n");
			printf("**********    Whether to proceed to the next round    **********\n");
			printf("\n");
			break;
		}
	}
}
int main()
{
	int n = 0;

	srand((size_t)time(NULL));
	do
	{
		menu();//Print Menu
		printf("Please enter  ");
		scanf("%d", &n);
		switch (n)
		{
		case 1:game(); break;
		case 0:printf("Game over\n"); break;
		default:printf("Input error, please re-enter!\n"); break;
		}
	} while (n != 0);
	
}

game.c

#define _CRT_SECURE_NO_WARNINGS 1
#include"game.h"

//Initialize array elements
void initboard(char board[ROW][COL], int row, int col)
{
	int i = 0, j = 0;
	//Assign the array first, because it's an n*n array, so assign n*n times
	//This is done using two for loops.
	for (i = 0; i < row; i++)
	{
		for (j = 0; j < col; j++)
		{
			board[i][j] = ' ';
		}
	}
}

//Print board
void printboard(char board[ROW][COL], int row, int col)
{
	int i = 0, j = 0;
	for (i = 0; i < row; i++)
	{
		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 < row; j++)
			{
				printf("---");
				if (j < row - 1)
				{
					printf("|");
				}

			}
		}
		
		printf("\n");
		
	}
}

//Player's Chess Function
void playerboard(char board[][COL], int row, int col)
{
	int x = 0, y = 0;
	printf("Ask players to play chess\n");
	while (1)//Here you can write an infinite loop to remind the player to restart when an illegal coordinate is released.
			//break out again when the player is in the right position.
	{
		printf("Please enter coordinates,Please separate with spaces.    \n");
		scanf("%d %d", &x, &y);
		if (x >= 1 && x <= row && y >= 1 && y <= col)//Determine if the player's coordinates are correct.
		{
			if (board[x-1][y-1] == ' ')
			{
				board[x-1][y-1] = '*';
				break;
			}
			else
			{
				printf("Coordinates already occupied, please re-enter!");
			}
		}
		else
		{
			printf("Illegal coordinates, please re-enter!");
		}
	}
}

//Computer Chess
void computermove(char board[ROW][COL], int row, int col)
{
	int x = 0; 
	int y = 0;
	printf("Computer Chess:>\n");
	while (1)
	{
		x= rand() % ROW;//Random values outside a loop can end up in an infinite loop.
		y= rand() % COL;
		if (board[x][y] == ' ')
		{
			board[x][y] = '#';
			break;
		}
	}
}

//Judging whether or not to win
char iswinboard(char board[ROW][COL], int row, int col)
{
	int i = 0, j = 0, count = 0;

	//Judging whether the line won
	for (i=0;i<row;i++)
	{
		if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != ' ')
		{
			return board[i][0];
			break;
		}
	}
	//Determine whether a column won
	for (j = 0; j < col; j++)
	{
		if (board[0][j] == board[1][j] && board[1][j] == board[2][j] && board[0][j] != ' ')
		{
			return board[0][j];
			break;
		}
	}
	//Judging Diagonals
	if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != ' ')
	{
		return board[0][0];
	}
	if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] != ' ')
	{
		return board[0][2];
	}

	//Judge whether a draw is drawn
	for (i = 0; i < row; i++)
	{
		for (j = 0; j < col; j++)
		{
			if (board[i][j] == ' ')
			{
				count++;
			}
		}
	}
	if (count == 0)
	{
		return 'Q';
	}
	return 'C';
}

Borrowing Peng Ge's Avatar (Dog Head for Life)

Tags: C Back-end

Posted on Tue, 23 Nov 2021 16:36:19 -0500 by novicephp