Realización de Duoziqi en lenguaje C

Hay algunos pasos en la realización de Duo Ziqi

(1) Diseño general del juego

#include<stdio.h>
int main()
{
	int input = 0;
	do
	{
		menu();//游戏菜单
		printf("请作出选择:>");
		scanf("%d", &input);
		switch (input)
		{
		case 1:
			game();
			break;
		case 0:
			printf("退出游戏\n");
			break;
		default:printf("选择有误,请重新选择\n");
			break;
		}
	} while (input);
	return 0;
}

Primero, use la instrucción do while() para darse cuenta del uso repetido del juego, y luego use la función Cambiar para construir la interfaz de inicio del juego y usarla con el menú.

(2) Diseño del menú del juego

void menu()
{
	printf("********************************\n");
	printf("***** 1、进入游戏 **************\n");
	printf("***** 0、退出游戏 **************\n");
	printf("********************************\n");
}

El menú del juego todavía usa la función printf() para simplemente realizar la función del menú.

(3) Diseño del juego

Dado que el tablero de ajedrez es pequeño de acuerdo con el significado de espacio bidimensional, se realiza utilizando una matriz bidimensional.Primero, defina la matriz como una matriz bidimensional.

int arr[ROW][COL] = {0} ;

ROW y COL usan la forma de definición macro, solo para poder lograr multi-ziqi, no solo se limitan al ajedrez de tres lunas o cuatro lunas, etc.

#define ROW 3
#define COL 3

Aquí primero lo definimos como tres para explicar, y luego puede cambiar el número a voluntad.

El tablero de ajedrez es primero una pizarra blanca, primero tenemos que inicializar la matriz e inicializarla en un espacio solo para dejar espacio para jugar al ajedrez.

Primero construya una función de inicialización initialize(arr, ROW, COL). Luego continúa construyendo la función de esta función.

void initialize(char arr[ROW][COL], int row, int col)
{
	int i = 0;
	int j = 0;
	for (i = 0; i < row; i++)
	{
		for (j = 0; j < col; j++)
		{
			arr[i][j] = ' ';
		}
	}
}

Una vez completada la inicialización, actualmente solo hay 9 espacios más, y es necesario imprimir la apariencia inicial del tablero de ajedrez y crear una función para imprimir el tablero de ajedrez.

void copychec(char arr[ROW][COL], int row, int col)
{
	int i = 0;
	int j = 0;
	for (i = 0; i < row; i++)
	{
		for (j = 0; j < col; j++)
		{
			printf(" %c ", arr[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");
		}
	}
}

Una vez que se completa la impresión del tablero de ajedrez, el juego de ajedrez comenzará oficialmente.

Primero el jugador juega al ajedrez, construye la función.

Debido a que hemos adquirido algunos conocimientos informáticos, sabemos que la matriz comienza con el subíndice 0, y las personas que no conocen la informática probablemente no lo sepan. Por lo tanto, el rango del ajedrez de nuestros jugadores, las coordenadas horizontales y verticales deben ser mayores o iguales a 1, y menor o igual a ROW o COL (Es el número de piezas de ajedrez que pusiste al principio, pero lo escribimos con tres piezas de ajedrez al principio, por lo que nuestro rango es mayor o igual a 1 y menor o igual a 3).

void playmove(char arr[ROW][COL], int row, int col)
{
	int x = 0;
	int y = 0;
	printf("玩家下棋\n");
	while (1)
	{
		printf("请输入下棋的坐标:>");
		scanf("%d %d", &x, &y);
		if (x >= 1 && x <= row && y >= 1 && y <= col)
		{
			if (arr[x - 1][y - 1] == ' ')
			{
				arr[x - 1][y - 1] = '*' ;
				break;
			}
			else
			{
				printf("位置被占,请重新输入\n");
			}
		}
		else
		{
			printf("输入不合法,请重新输入\n");
		}
	}
}

Después de jugar al ajedrez, para facilitar el siguiente paso, tenemos que imprimir el tablero de ajedrez en este momento.

Vuelva a llamar a la función copycheck().

Luego es el turno de la computadora para jugar al ajedrez, que también es la función de construcción. Entre ellos, también usamos la función rand() para hacer que las coordenadas debajo de la computadora sean valores aleatorios. Antes de usar la función rand, debe agregar srand ((int sin firmar) tiempo (NULL)) a la función principal; los nombres de los archivos de encabezado son: #include<stdlib.h> e #include<time.h>

void computemove(char arr[ROW][COL], int row, int col)
{
	int x = 0;
	int y = 0;
	printf("电脑下棋\n");
	while (1)
	{
		x = rand() % row;
		y = rand() % col;
		if (arr[x][y] == ' ')
		{
			arr[x][y] = '#'; 
			break;
		}
	}
}

También es necesario imprimir el tablero de ajedrez y llamar a la función copycheck().

-------------------------------------------------- ------------------------------

Es imposible para nosotros jugar al ajedrez con un solo movimiento, así que ponemos lo anterior en la función while()

En este punto, el marco del juego es simple de construir.

void game()
{
	char arr[ROW][COL] = { 0 };
	initialize(arr, ROW, COL);//数组初始化
	copychec(arr, ROW, COL);//打印棋盘

	while (1)
	{
		playmove(arr, ROW, COL);//玩家下棋
		copychec(arr, ROW, COL);//打印棋盘

		computemove(arr, ROW, COL);//电脑下棋
		copychec(arr, ROW, COL);//打印棋盘
	}
}

Por supuesto que hay ganadores y perdedores en el juego.

Tiene que ser juzgado después de que el jugador haya terminado de jugar y la computadora haya terminado de jugar al ajedrez. Así que diseñe una función para satisfacer esta función.

Hay cuatro situaciones en el juicio, "el jugador gana, la computadora gana, empatar, continuar”, que están representadas por el valor de retorno "*, #, m, n" respectivamente. En el proceso de juicio, usamos el conteo para juzgar quién gana , que también cumple con los requisitos cambiantes de Duo Ziqi, no limitado a un cierto número de piezas de ajedrez, por lo que la escritura es más flexible. Al evaluar las columnas, intercambiamos las posiciones de bucle de i y j, para que pueda evaluarse columna por columna.

Y finalmente, cuando juzgamos el empate, usamos la función Inspect() para verificar si hay cuadrículas vacías en todo el tablero de ajedrez, y devolvemos 0 si las hay, y devolvemos 1 en caso contrario.

//返回的是‘*’玩家赢
//返回的是‘#’电脑赢
//返回的是‘m'平局
//返回的是‘n'继续
//

int Inspect(char arr[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 (arr[i][j] == ' ')
				return 0;
		
		}
	}
	return 1;
}

char Deter(char arr[ROW][COL], int row, int col)
{
	int i = 0;
	int j = 0;
	//判断行
	for (i = 0; i < row ; i++)
	{
		int count = 0;
		for (j = 0; j < col - 1; j++)
		{
			if (arr[i][j] == arr[i][j + 1] && arr[i][j] != ' ')
			{
				count++;
			}
			if(count == row - 1)
				return arr[i][j];
		}
	}
	//判断列
	for (j = 0; j < col ; j++)
	{
		int count = 0;
		for (i = 0; i < row - 1; i++)
		{
			if (arr[i][j] == arr[i + 1][j] && arr[i][j] != ' ')
			{
				count++;
			}
			if(count == row -1)
				return arr[i][j];
		}
	}
	//判断对角线
		int countn = 0;
	for (i = 0; i < row - 1; i++)
	{
		//判断右对角线

		for (j = 0; j < col; j++)
		{
			if (i + j == row - 1 && arr[i][j] == arr[i + 1][j - 1] && arr[i][j] != ' ')
			{
				countn++;
			}
			if(countn == row - 1)
				return arr[i][j];
		}
	}
	//判断左对角线
	int count = 0;
	for (i = 0; i < row - 1; i++)
	{
		for (j = 0; j < col - 1; j++)
		{
			if (i == j && arr[i][j] == arr[i + 1][j + 1] && arr[i][j] != ' ')
			{
				count++;
			}
			if(count == row - 1)
				return arr[i][j];
		}
	}
	//平局
	if (Inspect(arr, ROW, COL) == 1)
	{
		return 'm';
	}
    //继续
	return 'n';
}

Finalmente, se diseñó con éxito la función del juego.

void game()
{
	char arr[ROW][COL] = { 0 };
	initialize(arr, ROW, COL);//数组初始化
	copychec(arr, ROW, COL);//打印棋盘
	char net = 0;
	while (1)
	{
		playmove(arr, ROW, COL);//玩家下棋
		copychec(arr, ROW, COL);//打印棋盘
		net = Deter(arr, ROW, COL);//判断输赢
		if (net != 'n')
			break;

		computemove(arr, ROW, COL);//电脑下棋
		copychec(arr, ROW, COL);//打印棋盘
		net = Deter(arr, ROW, COL);//判断输赢
		if (net != 'n')
			break;
	}
		if (net == '*')
		{
			printf("玩家赢了\n");
		}
		else if (net == '#')
		{
			printf("电脑赢了\n");
		}
		else if (net == 'm')
		{
			printf("平局\n");
		
		}
	
}

El código general del juego es:

#define ROW 3
#define COL 3
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void menu()
{
	printf("********************************\n");
	printf("***** 1、进入游戏 **************\n");
	printf("***** 0、退出游戏 **************\n");
	printf("********************************\n");
}

void initialize(char arr[ROW][COL], int row, int col)
{
	int i = 0;
	int j = 0;
	for (i = 0; i < row; i++)
	{
		for (j = 0; j < col; j++)
		{
			arr[i][j] = ' ';
		}
	}
}

void copychec(char arr[ROW][COL], int row, int col)
{
	int i = 0;
	int j = 0;
	for (i = 0; i < row; i++)
	{
		for (j = 0; j < col; j++)
		{
			printf(" %c ", arr[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 playmove(char arr[ROW][COL], int row, int col)
{
	int x = 0;
	int y = 0;
	printf("玩家下棋\n");
	while (1)
	{
		printf("请输入下棋的坐标:>");
		scanf("%d %d", &x, &y);
		if (x >= 1 && x <= row && y >= 1 && y <= col)
		{
			if (arr[x - 1][y - 1] == ' ')
			{
				arr[x - 1][y - 1] = '*';
				break;
			}
			else
			{
				printf("位置被占,请重新输入\n");
			}
		}
		else
		{
			printf("输入不合法,请重新输入\n");
		}
	}
}

void computemove(char arr[ROW][COL], int row, int col)
{
	int x = 0;
	int y = 0;
	printf("电脑下棋\n");
	while (1)
	{
		x = rand() % row;
		y = rand() % col;
		if (arr[x][y] == ' ')
		{
			arr[x][y] = '#';
			break;
		}
	}
}


//返回的是‘*’玩家赢
//返回的是‘#’电脑赢
//返回的是‘m'平局
//返回的是‘n'继续
//

int Inspect(char arr[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 (arr[i][j] == ' ')
				return 0;

		}
	}
	return 1;
}

char Deter(char arr[ROW][COL], int row, int col)
{
	int i = 0;
	int j = 0;
	//判断行
	for (i = 0; i < row; i++)
	{
		int count = 0;
		for (j = 0; j < col - 1; j++)
		{
			if (arr[i][j] == arr[i][j + 1] && arr[i][j] != ' ')
			{
				count++;
			}
			if (count == row - 1)
				return arr[i][j];
		}
	}
	//判断列
	for (j = 0; j < col; j++)
	{
		int count = 0;
		for (i = 0; i < row - 1; i++)
		{
			if (arr[i][j] == arr[i + 1][j] && arr[i][j] != ' ')
			{
				count++;
			}
			if (count == row - 1)
				return arr[i][j];
		}
	}
	//判断对角线
	int countn = 0;
	for (i = 0; i < row - 1; i++)
	{
		//判断右对角线

		for (j = 0; j < col; j++)
		{
			if (i + j == row - 1 && arr[i][j] == arr[i + 1][j - 1] && arr[i][j] != ' ')
			{
				countn++;
			}
			if (countn == row - 1)
				return arr[i][j];
		}
	}
	//判断左对角线
	int count = 0;
	for (i = 0; i < row - 1; i++)
	{
		for (j = 0; j < col - 1; j++)
		{
			if (i == j && arr[i][j] == arr[i + 1][j + 1] && arr[i][j] != ' ')
			{
				count++;
			}
			if (count == row - 1)
				return arr[i][j];
		}
	}
	//平局
	if (Inspect(arr, ROW, COL) == 1)
	{
		return 'm';
	}
	return 'n';
}

void game()
{
	char arr[ROW][COL] = { 0 };
	initialize(arr, ROW, COL);//数组初始化
	copychec(arr, ROW, COL);//打印棋盘
	char net = 0;
	while (1)
	{
		playmove(arr, ROW, COL);//玩家下棋
		copychec(arr, ROW, COL);//打印棋盘
		net = Deter(arr, ROW, COL);//判断输赢
		if (net != 'n')
			break;

		computemove(arr, ROW, COL);//电脑下棋
		copychec(arr, ROW, COL);//打印棋盘
		net = Deter(arr, ROW, COL);//判断输赢
		if (net != 'n')
			break;
	}
		if (net == '*')
		{
			printf("玩家赢了\n");
		}
		else if (net == '#')
		{
			printf("电脑赢了\n");
		}
		else if (net == 'm')
		{
			printf("平局\n");
		
		}
	
}



int main()
{
	int input = 0;
	do
	{
		menu();//游戏菜单
		printf("请作出选择:>");
		scanf("%d", &input);
		switch (input)
		{
		case 1:
			game();
			break;
		case 0:
			printf("退出游戏\n");
			break;
		default:printf("选择有误,请重新选择\n");
			break;
		}
	} while (input);
	return 0;
}

Este es el final de la explicación del juego Duoziqi esta vez, porque mi nivel es limitado, la explicación no es muy clara en algunos lugares, todos pueden corregir, ¡gracias!

Supongo que te gusta

Origin blog.csdn.net/weixin_74967884/article/details/131342078
Recomendado
Clasificación