# 3.总结

1.首先向大家介绍一下三子棋的原理

2.分块代码实现

1>首先我们需要打印一个菜单，引导用户输入决定玩游戏或是退出游戏，我们使用函数实现这一步骤

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

``````void test()
{
int input = 0;
srand((unsigned int)time(NULL));
do
{
printf("请选择:>");
scanf("%d", &input);
switch (input)
{
case 1:
game();
break;
case 0:
printf("退出游戏n");
break;
default:
printf("选择错误n");
break;
}

} while (input);
}``````

在这一段中srand的使用我们后面再说，接下来为大家介绍game函数中游戏的实现。

2>game函数的实现

``````#define ROW 3
#define COL 3
``````

``char board[ROW][COL] = { 0 };``

``````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++)
{
//数据
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 < col; j++)
{
printf("---");
if (j < col - 1)
printf("|");
}
}
printf("n");
}
}
``````

``````void player_move(char board[ROW][COL], int row, int col)
{
printf("玩家下棋:>");
int x = 0;
int y = 0;

while (1)
{
scanf("%d %d", &x, &y);
if (x >= 1 && x <= row && y >= 1 && y <= col)
{
if (board[x - 1][y - 1] == ' ')
{
board[x - 1][y - 1] = '*';
break;
}
else
{
printf("该坐标被占用，请重新输入！n");
}
}
else
{
printf("坐标非法，请重输入!n");
}
}
}``````

``````void computer_move(char board[ROW][COL], int row, int col)
{
int x = 0;
int y = 0;
printf("电脑下棋>n");
while (1)
{
x = rand() % ROW;//0~2
y = rand() % COL;//0~2
if (board[x][y] == ' ')
{
board[x][y] = '#';
break;
}
}
}``````

``````har is_win(char board[ROW][COL], int row, int col)
{
int i = 0;
//三行
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];
}
}
//三列
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];
}
}
//对角线的判断
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];
}

//判断平局
if (1 == is_full(board, row, col))i
{
return 'Q';
}
//继续
return 'C';
}
``````

``````void game()
{

char board[ROW][COL] = { 0 };
InitBoard(board, ROW, COL);//初始化棋牌
//打印棋盘
DisplayBoard(board, ROW, COL);
//下棋
char ret = 0;
while (1)
{
player_move(board, ROW, COL);
DisplayBoard(board, ROW, COL);
ret = is_win(board, ROW, COL);
if (ret != 'C')
{
break;
}
computer_move(board, ROW, COL);
DisplayBoard(board, ROW, COL);
ret = is_win(board, ROW, COL);
if (ret != 'C')
{
break;
}
}
if (ret == '*')
{
printf("玩家赢n");
}
else if (ret == '#')
{
printf("电脑赢n");
}
else
{
printf("平局n");
}
}``````

3.总结

THE END

)">