三子棋
#include <stdio.h>
#include <time.h>
#define Max_row 3
#define Max_col 3
char chess[3][3];
void qipan()
{
for (int row = 0; row < Max_row; row++)
for (int col = 0; col < Max_col; col++)
chess[row][col] = ' ';
}
void xianshi(void)
{
printf("_____________\n");
printf("|_%c_|_%c_|_%c_|\n", chess[0][0], chess[0][1], chess[0][2]);
printf("|_%c_|_%c_|_%c_|\n", chess[1][0], chess[1][1], chess[1][2]);
printf("|_%c_|_%c_|_%c_|\n", chess[2][0], chess[2][1], chess[2][2]);
}
void player(void)
{
int row;
int col;
printf("玩家下棋(请输入坐标下棋):");
while (1)
{
scanf("%d %d", &row, &col);
if (chess[row - 1][col - 1] != ' ')
{
printf("此位置已用,请重新输入:");
}
else break;
}
chess[row-1][col-1] = '#';
}
char winner(void)
{
for (int row = 0; row < Max_col; row++)
{
if (chess[row][0] == chess[row][1] && chess[row][0] == chess[row][2] && chess[row][0] == '#')
return '#';
if (chess[row][0] == chess[row][1] && chess[row][0] == chess[row][2] && chess[row][0] == 'x')
return 'x';
}
for (int col = 0; col < Max_col; col++)
{
if (chess[0][col] == chess[1][col] && chess[0][col] == chess[2][col] && chess[0][col] == '#')
return '#';
if (chess[0][col] == chess[1][col] && chess[0][col] == chess[2][col] && chess[0][col] == 'x')
return 'x';
}
if (chess[0][0] == chess[1][1] && chess[0][0] == chess[2][2] && chess[0][0] == '#')
return '#';
if (chess[0][2] == chess[1][1] && chess[0][2] == chess[2][0] && chess[0][2] == 'x')
return 'x';
return ' ';
}
int pingju(void)
{
for (int row = 0; row < Max_col; row++)
for (int col = 0; col < Max_col; col++)
{
if (chess[row][col] == ' ')
return 0;
}
return 1;
}
int computer(void)
{
int row, col;
while (1)
{
row = rand() % 3;
col = rand() % 3;
if (chess[row][col] == ' ')
{
chess[row][col] = 'x';
break;
}
}
}
int main(void)
{
srand((unsigned int)time(0));
//初始化棋盘
qipan();
printf("***************************\n");
printf("* *\n");
printf("* 1:开始游戏。 *\n");
printf("* 2:结束游戏。 *\n");
printf("* *\n");
printf("***************************\n");
int n = 0;
while (scanf("%d", &n)==1)
{
switch (n)
{
case 1:
printf("游戏开始:\n");
xianshi();
break;
case 2:
printf("退出游戏。\n");
system("pasue");
return 0;
default:
printf("输入错误,请重新输入。\n");
break;
}
if (n == 1)
break;
}
while (1)
{
//玩家下棋
player();
xianshi();
//判断胜负
winner();
if (winner() == '#')
{
printf("你赢了!!!\n");
break;
}
else if (winner() == 'x')
{
printf("你输了。。。\n");
break;
}
else if (pingju())
{
printf("平局\n");
break;
}
//电脑下棋
printf("电脑下棋。\n");
computer();
xianshi();
//判定胜负
winner();
if (winner() == '#')
{
printf("你赢了!!!\n");
break;
}
else if (winner() == 'x')
{
printf("你输了。。。\n");
break;
}
else if (pingju())
{
printf("平局\n");
break;
}
}
system("pause");
return 0;
}