#define _CRT_SECURE_NO_WARNINGS 1
# include<stdio.h>
# include<stdlib.h>
# include<time.h>
#define ROW 3
#define COL 3
void menu()//开始提示
{
printf("###1.开始游戏,0.退出系统###");
}
void display_board(char arr[ROW][COL], int row, int col)//打印棋盘
{
int i = 0;
for(i=0;i<row;i++)
{
printf(" %c | %c | %c \n",arr[i][0],arr[i][1],arr[i][2]);
if(i!=2)
{
printf("---|---|---\n");
}
}
}
void init_board(char arr[ROW][COL], int row, int col)//初始化棋盘
{
int i = 0;
int j = 0;
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
arr[i][j] = ' ';
}
}
}
void player_move(char arr[ROW][COL], int row, int col)//玩家输入
{
int i = 0;
int j = 0;
while(1)
{
printf("请输入你要走的坐标:");
scanf("%d%d",&i,&j);
i-=1;
j-=1;
if(((i>=0)&&(i<row))&&((j>=0)&&(j<col)))
{
if(arr[i][j] == ' ')
{
arr[i][j] = '#';
break;
}
else
{
printf("该位置已被占,请重新输入\n");
}
}
}
}
void computer_move(char arr[ROW][COL], int row, int col)//电脑输入
{
int i = 0;
int j = 0;
srand((unsigned int)time(NULL));
while(1)
{
i = rand() % row;
j = rand() % col;
if(arr[i][j] == ' ')
{
arr[i][j] = '0';
break;
}
}
}
int check_win(char arr[ROW][COL], int row, int col)//判断是否以赢
{
int i = 0;
for(i=0; i<row; i++)
{
if(((arr[i][0]==arr[i][1])&&(arr[i][1]==arr[i][2]))&&(arr[i][0]!=' '))
{
return arr[i][0];
}
}
for(i=0; i<col; i++)
{
if(((arr[0][i]==arr[1][i])&&(arr[1][i]==arr[2][i]))&&(arr[0][i]!=' '))
{
return arr[0][i];
}
}
if(((arr[0][0]==arr[1][1])&&(arr[1][1]==arr[2][2]))&&(arr[1][1]!=' '))
{
return arr[1][1];
}
if(((arr[0][2]==arr[1][1])&&(arr[1][1]==arr[2][0]))&&(arr[1][1]!=' '))
{
return arr[1][1];
}
return 0;
}
int check_full(char arr[ROW][COL], int row, int col)//判断棋盘是否有已满
{
int i = 0;
int j = 0;
for(i=0; i<row; i++)
for(j=0; j<col;j++)
{
if(arr[i][j] == ' ')
return 0;
}
return -1;
}
void game()//开始游戏
{
int ret;
char arr[ROW][COL] = {0};
display_board(arr, ROW, COL);
init_board(arr, ROW, COL);
do
{
player_move(arr, ROW, COL);
display_board(arr, ROW, COL);
ret = check_win(arr, ROW, COL);
if(ret == '#')
{
break;
}
ret = check_full(arr, ROW, COL);
if(ret == -1)
{
break;
}
computer_move(arr, ROW, COL);
display_board(arr, ROW, COL);
ret = check_win(arr, ROW, COL);
if(ret == '0')
{
break;
}
ret = check_full(arr, ROW, COL);
if(ret == -1)
{
break;
}
}while(ret != -1);
if(ret == '#')
{
printf("玩家赢\n");
}
else if(ret == '0')
{
printf("电脑赢\n");
}
else
{
printf("平局\n");
}
}
int main()
{
int input = 0;
while(1)
{
menu();
printf("请输入:");
scanf("%d",&input);
switch(input)
{
case 1:
game();
case 0:
break;
default:
printf("输入错误\n");
break;
}
}
return 0;
}