game.h
#define _CRT_SECURE_NO_WARNINGS 1
#include
#include
#include
#include
void menu();
void game();
#define ROW 3
#define COL 3
void board();
void play();
int win();
game.c
#include “game.h”
void menu()
{
printf("***** 1.paly *\n");
printf(" 0.exit ******\n");
printf("*********************\n");
printf("*********************\n");
}
int win(char a[ROW][COL], int row, int col)
{
int i = 0;
int j = 0;
int d = 0;
for (i = 0; i < row; i++) //横着赢
{
if ((a[i][0] == a[i][1]) && (a[i][1] == a[i][2]) && (a[i][0] != ‘\0’))
return a[i][0];
}
for (j = 0; j < col; j++) //竖着赢
{
if ((a[0][j] == a[1][j]) && (a[1][j] == a[2][j]) && (a[0][j] != ‘\0’))
return a[0][j];
}
if ((a[0][0] == a[1][1]) && (a[1][1] == a[2][2]) && (a[0][0] != '\0')) //向下斜着赢
return a[0][0];
if ((a[2][0] == a[1][1]) && (a[1][1] == a[0][2]) && (a[2][0] != '\0')) //向上斜着赢
return a[2][0];
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
if (a[i][j] != '\0')
d++; //计数器,判断棋盘已下子个数
}
}
if (d == (row*col)) //判断棋盘是否满
{
return 'Q'; //平局
}
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
if (a[i][j] == '\0') //在没有输赢也没有平局的情况下,只有遇见空字符就继续游戏
return 'C';
}
}
}
void play(char a[ROW][COL], int row, int col)
{
int x = 0;
int y = 0;
char c;
while (1)
{
c = win(a, row, col);
if (c == ‘C’)
{
while (1)
{
{
printf(“玩家下\n”);
printf(“请输入坐标”);
scanf("%d%d", &x, &y);
if (a[x - 1][y - 1] == ‘\0’)
{
a[x - 1][y - 1] = ‘*’;
board(a, row, col);
printf("\n");
break;
}
else
printf(“输入错误,请重新输入\n”);
}
}
}
else
break;
c = win(a, ROW, COL);
if (c == 'C')
{
printf("电脑下\n");
while (1)
{
x = rand() % 3;
y = rand() % 3;
if (a[x][y] == '\0')
{
a[x][y] = '#';
board(a, ROW, COL);
break;
}
}
}
else
break;
}
if (c == 'Q')
{
printf("平局");
}
if (c == '*')
{
printf("玩家赢");
}
if (c == '#')
{
printf("电脑赢");
}
}
void board(char a[ROW][COL], int row, int col)
{
int i = 0, j = 0;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
printf(" %c ", a[i][j]);
if (j < col - 1)
printf("|");
}
printf("\n");
for (j = 0; j < col; j++)
{
if (i < row - 1)
printf("--- ");
}
printf("\n");
}
}
void game()
{
char a[ROW][COL] = { 0 };
memset(&a[0][0], ‘\0’, ROWCOLsizeof(a[0][0])); //将数组初始化
int i, j;
board(a, ROW, COL);
play(a, ROW, COL); //开始进入游戏
}
test.c
#include “game.h”
int main()
{
int input = 0;
menu(); //建立菜单
srand((unsigned int)time(NULL));
printf(“请输入一个整数”);
do{
scanf("%d", &input);
switch (input)
{
case 0:
printf(“退出成功\n”);
break;
case 1:
game();
break;
default:
printf(“输入错误,请重新输入\n”);
break;
}
} while (input);
system("pause");
return 0;
}