在看到鹏哥视频后的得到的启发。
将需要的头文件都包入自己创建的game.h中,方便创建静态库。
cpp代码如下:
#include"game.h"
void menu()
{
printf("********************************\n");
printf("********************************\n");
printf("********************************\n");
printf("1.游戏开始 0.退出程序\n");
printf("********************************\n");
printf("********************************\n");
printf("********************************\n");
}
void game(char arr[ROW][COL], int row, int col)
{
int i, j;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
printf(" %c ", arr[i][j]);
if (j < col - 1)
printf("|");
}
printf("\n");
for (j = 0; j < col; j++)
{
if (i == 2)
break;
printf("---");
if (j < col - 1)
printf("|");
}printf("\n");
}
}
void initialize(char arr[ROW][COL], int row, int col)
{
int i, j;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
arr[i][j] = ' ';
}
}
}
int player(char arr[ROW][COL], int inputrow, int inputcol)
{
if (arr[inputrow][inputcol] == ' ')
arr[inputrow][inputcol] = '*';
else
{
printf("输入有误,重新输入\n");
return 0;
}
}
void computer(char arr[ROW][COL],int row,int col)
{
int i = 0, j = 0;
while (1)
{
again:
i = rand() % ROW;
j = rand() % COL;
if (arr[i][j] == ' ')
{
arr[i][j] = '#';
break;
}
else if (arr[i][j] == '#' || arr[i][j] == '*')
goto again;
}
}
char victory(char arr[ROW][COL], int row, int col)
{
int i = 0, j = 0,k=0,a=0,b=0,c=0,d=0,z=0;
for(i=0;i<row;i++)
for (j = 0; j < col; j++)
{
if (arr[i][1] == arr[i][2] && arr[i][0] == arr[i][1])
{
if (arr[i][1] == '*')
{
printf("玩家胜利\n");
return 0;
}
if (arr[i][1] == '#')
{
printf("电脑胜利\n");
return 0;
}
}
if (arr[1][i] == arr[2][i] && arr[1][i] == arr[0][i])
{
if (arr[1][i] == '*')
{
printf("玩家胜利\n");
return 0;
}
if (arr[1][i] == '#')
{
printf("电脑胜利\n");
return 0;
}
}
if (i == j)
{
k++;
if (k == COL)
{
for (a = 0; a <= ROW; a++)
{
for (b = 0; b <= COL; b++)
{
if (a == b)
{
if (arr[a][b] == '*')
c++;
if (arr[a][b] == '#')
d++;
}
}
}
}
if (c == ROW+1)
{
printf("玩家胜利\n");
c = 0;
return 0;
}
if (d == ROW+1)
{
printf("电脑胜利\n");
d = 0;
return 0;
}
}
if (i+j==ROW-1)
{
z++;
if(z==ROW)
for (a = 0; a <= ROW; a++)
{
for (b = 0; b <= COL; b++)
{
if (a + b == ROW - 1)
{
if (arr[a][b] == '*')
c++;
if (arr[a][b] == '#')
d++;
}
}
}
if (c == ROW+1)
{
printf("玩家胜利\n");
return 0;
}
if (d == ROW+1)
{
printf("电脑胜利\n");
return 0;
}
}
}
}
int main()
{
int i, j, a;
int k[5] = { 0 };
char arr[ROW][COL] = {0};
srand(unsigned int(time(NULL)));
menu();
scanf_s("%d", &i);
if (i)
{
initialize(arr, ROW, COL);
while (1)
{
game(arr, ROW, COL);
printf("玩家输入\n");
scanf_s("%d %d", &k[0], &k[1]);
player(arr, k[0]-1, k[1]-1);
game(arr, ROW, COL);
k[3] = k[3] + 2;
k[0] = 0;
k[1] = 0;
a=victory(arr, ROW, COL);
if (a == 0)
break;
if (k[3] >= ROW * COL)
{
a = 1;
break;
}
printf("电脑输入\n");
computer(arr, ROW, COL);
a=victory (arr,ROW,COL);
if (a == 0)
break;
}
}
if (a == 1)
{
printf("平局,游戏结束\n");
}
system("pause");
return 0;
}