#include <stdio.h>
#include <Windows.h>
#include<time.h>
#define row 3
#define list 3 void init_Board(char board[row][list]) //对二维数组元素全部赋值为 “ ”
{
memset(board,' ',row*list*sizeof(char));
} void display_Board(char board[row][list])//画出棋谱
{
system("cls");
int i = ;
for (i = ; i < row; i++)
{
printf(" %c |%c | %c\n", board[i][], board[i][], board[i][]);
if (i != ){
printf(" --|--|--\n");
}
}
printf("(X代表玩家,0代表电脑)\n") ;
} void man_Play(char board[row][list]) //玩家下“子”
{
int i = ;
int j = ;
flag:
printf("选择一个坐标:\n");
scanf("%d", &i);
if (i > || i <)
{
printf("横坐标越界,重输:\n");
goto flag;
}
scanf("%d", &j);
if (j > || j <)
{
printf("纵坐标越界,重输:\n");
goto flag;
}
if (board[i-][j-] == ' ')
board[i-][j-]='X';
else
{
printf("所选位置已被下过,请重新输入\n");
goto flag;
}
} char is_Win(char board[row][list])
{
int i = ;
int j = ;
for (i = ; i < row; i++)
{
if ((board[i][] == board[i][]) && (board[i][] == board[i][]))
return board[i][];
}
for (j = ; j < row; j++)
{
if ((board[][j] == board[][j]) &&( board[][j] == board[][j]))
return board[][j];
}
if ((board[][] == board[][]) && (board[][] == board[][]))
return board[][];
if ((board[][] == board[][]) && (board[][] == board[][]))
return board[][];
return ' ';
}
void computer_Play(char board[row][list]) //电脑下“子”
{
int i = ;
int j = ;
while ()
{
srand((int)time());//设置随机种子
i = rand() % ; //产生随机数
j = rand() % ;
if (board[i][j] == ' ')
{
board[i][j] = '';
break;
}
}
} int is_Full(char board[row][list])
{
int i = ;
int j = ;
int count = ;
for (i = ; i < row;i++)
for (j = ; j < list; j++)
{
if (board[i][j] == ' ')
count++;
}
return count;
} int main()
{
char board[row][list];
init_Board(board);
display_Board(board);
while ()
{
if ((is_Full(board) > ))
{
man_Play(board);
display_Board(board);
printf("\n");
if (is_Win(board) == 'X')
{
printf("玩家胜\n");
break;
}
}
else
{
printf("平局!");
break;
}
if ((is_Full(board) >))
{
computer_Play(board);
display_Board(board);
printf("\n");
if (is_Win(board) == )
{
printf("电脑胜\n");
break;
}
}
else
{
printf("平局!");
break;
}
}
printf("游戏结束!\n");
system("pause");
return ;
}