C语言基础三子棋程序编写

由玩家输入棋子坐标将棋子存入数组board中,由chessBoard得数组存储方式为{{%c|%c|%c}---{%c|%c|%c}---%c|%c|%c},最后根据isWin返回值判断玩家或电脑是否赢了游戏
#include
#include
#include
#include
#pragma warning(disable :4996)
void game();
void menu();
void chessBoard(char board[][3]);
char playerMove(char board[][3]);
void comeputerMove(char board[][3]);
int isFull(char board[][3]);
char isWin(char board[][3]);
void menu()
{
	printf("########################\n");
	printf("         1.play         \n");
	printf("          2.exit        \n");
	printf("########################\n");
}
//1.输出菜单2.选择进入游戏//
int main()
{
	menu();

	int choice;
	scanf("%d", &choice);
	switch (choice)
	{
	case 1:
		game();
		break;
	case 2:
		exit(0);
	}
	system("pause");
}
void game()
{
	char board[3][3];
	char ret;
	memset(board, ' ',9);                    //数组清零//
	//do{//
		do{
			chessBoard(board);              //输出面板//
			//playerMove(board);//
			ret = playerMove(board);       //输出提示坐标使玩家将棋子放入棋盘//
			if (ret == 'o')
			{
				comeputerMove(board);
				//chessBoard(board);//
				//break;//
			}
			else
			{
				printf("please try again\n");
				//break;//
			}
		} while ((isWin(board)!=0)||(isFull(board)==1));   //当棋盘满了或者isWin函数返回值不为零时跳出函数//
		char win;
		win = isWin(board);
		if (win = 'o')
		{
			printf("you win\n");
			//break;//
		}
		else if (win = 'x')
		{
			printf("you lose\n");
			//break;//
		}
		else if (win = 'p')
		{
			printf("pinju\n");
			//break;//
		}
		else
		{
			printf("erro!\n");
		}
	//} while( (isWin(board) != 0) || (isFull(board) == 1));//
}
void chessBoard(char board[][3])
{
	int i = 0;
	for (i = 0; i < 3; i++)
	{
		printf(" %c | %c | %c \n", board[i][0], board[i][1], board[i][2]);
		if (i < 2)
		{
			printf("  -  -  - \n");
		}
	}
}

char playerMove(char board[][3])
{
	int x;
	int y;
	printf("please enter\n");
	scanf("%d%d", &x, &y);
	if (board[x - 1][y - 1] == ' ')
	{
		board[x - 1][y - 1] = 'o';
		return board[x - 1][y - 1];
	}
	else
	{
		printf("please try again\n");
		return 1;
	}

}
void comeputerMove(char board[][3])
{
	srand((unsigned long)time(NULL));
	do{
		int x = rand() % 3;
		int y = rand() % 3;

		if (board[x - 1][y - 1] == ' ')
		{
			board[x - 1][y - 1] = 'x';
			break;
		}
	} while (1);
}
char isWin(char board[][3])
{
	int i = 0;
	for (i = 0; i < 3; i++)
	{
		if (board[i][0] == board[i][1] && board[i][1] == board[i][2])
			return board[i][1];
	}
	for (i = 0; i < 3; i++)
	{
		if (board[0][i] == board[1][i] && board[2][i] == board[1][1])
			return board[1][i];
	}
	if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[2][2] != ' ')
	{
		return board[0][0];
	}
	if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[1][1] != ' ')
	{
		return board[1][1];
	}
	if (isFull(board) == 1)
		return 'q';
	else
		return 0;
}
int isFull(char board[][3])
{
	int i;
	int j;
	for (i = 0; i < 3; i++)
	{
		for (j = 0; j < 3; j++)
		{
			if (board[i][j] == ' ')
			{
				return 0;
			}
		}

	}
	return 1;
}


 

你可能感兴趣的:(C语言基础三子棋程序编写)