C语言实现三连棋的判断

对三连棋的判断无非以下三点:

  1. 对三连棋棋盘及棋子的数组化输入
  2. 对行向和列向的连续判断
  3. 对主对角线和副对角线的连续判断
#include
#include
#include

int main() {
	const int size = 3;
	int matrix[3][3];
	int i, j;
	int num0fx,num1fx;
	int num0fo,num1fo;
	int result = -1;//reslut-1没人赢 result=1 x赢;result=0 是o赢;
	for (i = 0; i < size; i++)
	{
		for (j = 0;j < size;j++) 
		{
			scanf_s("%d", &matrix[i][j]);
		}


	}
	for (i = 0; i < size; i++)//输出棋盘
	{
		for (j = 0;j < size;j++)
		{
			if (matrix[i][j] == 1)
			{
				printf("X  ");
			}
			else
			{
				printf("O  ");
			}
		}
		printf("\n");
	}
	for (i = 0; i < size&&result == -1; i++)//行向或列向三连
	{
		num0fo = num0fx = 0;
		num1fo = num1fx = 0;
		for(j = 0;j < size;j++)
		{
			if (matrix[i][j] == 1) 
			{
				num0fx++;
			}
			else if(matrix[i][j]==0)
			{
				num0fo++;

			}
			else if (matrix[j][i]==1)
			{
				num1fx++;

			}
			else if (matrix[j][i]==0)
			{
				num1fo++;

			}
			
		}
		if (num0fo==3||num1fo==3)
		{
			result = 0;

		}
		else if (num0fx==3||num1fx==3)
		{
			result = 1;

		}
		
	}
	if (result==-1)//主对角线三连
	{
		num0fo = num0fx = 0;
		for ( i = 0; i < size; i++)
		{
		
			if (matrix[i][i]==1)
			{
				num0fx++;
			}
			else if (matrix[i][i]==0)
			{
				num0fo++;

			}
	
		}
		if (num0fx==3)
		{
			result = 1;

		}
		else if (num0fo==3)
		{
			result = 0;
		}
	}
	if (result==-1)
	{
		num0fo = num0fx = 0;
		for (i =0; i < size; i++)
		{

			if (matrix[i][size-i-1] == 1)
			{
				num0fx++;
			}
			else if (matrix[i][size-i-1] == 0)
			{
				num0fo++;

			}

		}
		if (num0fx == 3)
		{
			result = 1;

		}
		else if (num0fo == 3)
		{
			result = 0;
		}

	}
	switch (result)
	{
	case -1:printf("没有赢家\n");
		break;
	case 0:printf("O胜利\n");
		break;
	default:printf("X胜利\n");
		break;
	}
	return 0;
}

你可能感兴趣的:(C语言学习,数组应用)