#define _CRT_SECURE_NO_WARNINGS 1
#include"game.h"
void print()
{
printf("*************************\n");
printf("*********1、paly*********\n");
printf("*********0、exit*********\n");
printf("*************************\n");
}
void Init(char(*arr)[COLS], int row, int col)
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
*(*(arr + i) + j) = ' ';
}
}
}
void PrintBorad(char(*arr)[COLS], int row, int col)
{
int i = 0;
for (i = 1; i <= row; i++)
{
int j = 0;
for (j = 1; j <= col; j++)
{
printf(" %c ", *(*(arr + i) + j));
if (j <= col - 1)
printf("|");
}
printf("\n");
if (i <= row - 1)
{
for (j = 1; j <= col; j++)
{
printf("---");
if (j <= col - 1)
printf("|");
}
printf("\n");
}
}
}
void PlayerInput(char(*arr)[COLS], int row, int col)
{
int x = 0;
int y = 0;
printf("玩家回合:\n");
printf("请输入要下棋的坐标(中间用空格隔开):");
while (scanf("%d%d", &x, &y) == 2)
{
while (getchar() != '\n')
{
;
}
if (x >= 1 && x <= row && y >= 1 && y <= col)
{
if (arr[x][y] == ' ')
{
arr[x][y] = 'O';
break;
}
else
printf("此处已下过棋子,请重新下子:");
}
else
printf("非法输入,请重新输入:");
}
}
void ComputerInput(char(*arr)[COLS], int row, int col)
{
printf("电脑回合:\n");
while (1)
{
int x = rand() % row + 1;//生产1-5的随机数
int y = rand() % col + 1;
if (arr[x][y] != ' ')
{
continue;
}
else
{
arr[x][y] = 'X';
break;
}
/*if (arr[x][y] == ' ')
{
arr[x][y] = 'X';
}
else
{
;
}*/
}
}
char IsWin(char(*arr)[COLS], int row, int col)//c继续 q平局 O玩家获胜 X电脑获胜
{
int i = 0;
int j = 0;
char c = 'c';
char q = 'q';
//斜线确定
for (i = 1; i <= row; i++)
{
for (j = 1; j <= col; j++)
{
if (arr[i][j] != ' ')
{
if (arr[i][j] == arr[i - 1][j - 1] && arr[i][j] == arr[i + 1][j + 1])
{
return arr[i][j];
}
else if (arr[i][j] == arr[i - 1][j + 1] && arr[i][j] == arr[i + 1][j - 1])
{
return arr[i][j];
}
}
}
}
//行确定
int sum = 0;//优化方案
for (i = 1; i <= row; i++)
{
sum = 0;
for (j = 1; j <= col - 1; j++)
{
if (arr[i][j] == arr[i][j + 1] && arr[i][j] != ' ')
{
sum = sum + 1;
if (sum == 2)
{
return arr[i][j];
}
}
else
sum = 0;
}
}
//列确定
for (j = 1; j <= col; j++)
{
sum = 0;
for (i = 1; i <= row - 1; i++)
{
if (arr[i][j] == arr[i + 1][j] && arr[i][j] != ' ')
{
sum = sum + 1;
if (sum == 2)
{
return arr[i][j];
}
}
else
sum = 0;
}
}
//平局
for (i = 1; i <= row; i++)
{
for (j = 1; j <= col; j++)
{
if (arr[i][j] == ' ')
return c;
}
}
return q;
}
void play(char(*arr)[COLS], int rows, int cols)
{
Init(arr, rows, cols);//初始化7*7棋盘
PrintBorad(arr, ROW, COL);//打印只需打印5*5棋盘即可
char poi = 0;
while (1)
{
PlayerInput(arr, ROW, COL);//玩家下棋
PrintBorad(arr, ROW, COL);
poi = IsWin(arr, ROW, COL);//判断胜负
if (poi != 'c')
break;
ComputerInput(arr, ROW, COL);//电脑下棋
PrintBorad(arr, ROW, COL);
poi = IsWin(arr, ROW, COL);//判断胜负
if (poi != 'c')
break;
}
if (poi == 'O')
{
printf("玩家获胜!\n");
}
else if (poi == 'X')
{
printf("电脑获胜!\n");
}
else
{
printf("平局!\n");
}
}