#define _CRT_SECURE_NO_WARNINGS 1
#include "game.h"
//函数实现
//游戏菜单
void menu()
{
printf("**************************\n");
printf("***** 0.Exit 1.Play *****\n");
printf("**************************\n");
}
void InitBoard(char board[ROW][COL], int row, int col)
{
int i = 0;
for (i = 0; i < row; i++)
{
int j = 0;
for (j = 0; j < col; j++)
{
board[i][j] = ' ';
}
}
}
void PrintBoard(char board[ROW][COL], int row, int col)//打印棋盘,空
{
int i = 0;
int j = 0;
//打印顶部X轴坐标
for (i=0;i<col;i++)
{
printf(" %d ", i + 1);
}
printf("\n");
for (i = 0; i < row; i++)
{
printf("%d ",i+1);
for (j = 0; j < col; j++)
{
if (j < col - 1)
printf(" %c |", board[i][j]);
else if (j = col - 1)
printf(" %c ", board[i][j]);
}
printf("\n");
if (i < row - 1)
{
printf(" ");
for (j = 0; j < col; j++)
{
if (j < col - 1)
printf("---|");
else if (j = col - 1)
printf("---");
}
printf("\n");
}
}
}
//判断输赢,注意:这里只是针对三子棋的棋盘进行判断的,只取三个元素进行判断
//如果想要五子棋或者其他,则需要改进这个判断输赢的函数
char Win(char board[ROW][COL], int row, int col)
{
int i = 0;
int equal = 1;
for (i = 0; i < row ; i++)//判断行元素是否相同
{
if (board[i][0] == board[i][1] && board[i][1] == board[i][2])
{
return board[i][1];
}
}
for (int j = 0; j < col; j++)//判断列元素是否相同
{
if (board[0][j] == board[1][j] && board[2][j] == board[1][j])
{
return board[1][j];
}
}
//判断对角线元素是否相同
if (board[0][0] == board[1][1] && board[2][2] == board[1][1])
{
return board[1][1];
}
else if (board[0][2] == board[1][1] && board[2][0] == board[1][1])
{
return board[1][1];
}
return ' ';
}
void PlayMove(char board[ROW][COL], int row, int col)//玩家落子
{
int x = 0;
int y = 0;
while (1)
{
printf("玩家走->\n");
printf("请输入坐标:");
scanf("%d %d", &x, &y);
if (0 < x && x < row + 1 && 0 < y && y < col + 1)
{
if (board[x - 1][y - 1] == ' ')
{
board[x - 1][y - 1] = 'X';
break;
}
else
{
printf("坐标被占用!\n");
}
}
else
{
printf("输入坐标非法!请重新输入\n");
}
}
}
void ComputerMove(char board[ROW][COL], int row, int col)//玩家落子
{
int x = 0;
int y = 0;
printf("电脑走->\n");
while (1)
{
x = rand() % 3 + 1;
y = rand() % 3 + 1;
if (board[x - 1][y - 1] == ' ')
{
board[x - 1][y - 1] = 'O';
break;
}
}
}
void game()
{
int x = 0;
int y = 0;
char flag;
int num = ROW * COL;
char board[ROW][COL];
InitBoard(board, ROW, COL);//初始化棋盘, 全部为空格
PrintBoard(board, ROW, COL);//打印棋盘,空
while (num)
{
PlayMove(board, ROW, COL);
PrintBoard(board, ROW, COL);
num--;
if (num > 0)
{
ComputerMove(board, ROW, COL);
PrintBoard(board, ROW, COL);
num--;
flag = Win(board, ROW, COL);
if (flag == 'X')
{
printf("玩家获胜!\n");
break;
}
else if (flag == 'O')
{
printf("电脑获胜!\n");
break;
}
}
else
{
printf("平局!\n");
break;
}
}
}