头文件:
game.h
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
#include "game.h"
#pragma warning(disable:4996)
#define ROW 3
#define COL 3
void game();//函数的声明
#endif
game.c
#include "game.h"
//显示面板的界面
static void displayBoard(char board[][COL], int row)//用static改变函数的链接属性,变为内部链接属性,更加安全
{
int i = 0;
for (; i < row; i++)
{
printf(" %c | %c | %c\n", board[i][0], board[i][1], board[i][2]);
if (i < row - 1)
{
printf("---|---|---\n");
}
}
}
//玩家玩游戏
static void playerMove(char board[][COL], int row)
{
int x, y;
do
{
printf("请输入<x,y>:");
scanf("%d%d", &x, &y);
if (x >= 1 && x <= 3 && y >= 1 && y <= 3)
{
if (board[x - 1][y - 1] == ' ')
{
board[x-1][y-1] = 'x';
break;
}
else
{
printf("已经被占用,请再次输入:\n");
}
}
else
{
printf("输入错误!再次输入\n");
}
} while (1);
}
//电脑玩游戏
static void computerPlayer(char board[][COL], int row)
{
srand((unsigned long)time(NULL));
do
{
int x = rand() % row;
int y = rand() % COL;
if (board[x][y] == ' ')
{
board[x][y] = 'o';
break;
}
} while (1);
}
//判断面板中是否为空
static int isFull(char board[][COL], int row)
{
int i = 0;
for (; i < row; i++)
{
int j = 0;
for (; j < row; j++)
{
if (board[i][j] == ' ')
{
return 0;
}
}
}
return 1;
}
//判断是哪方获胜
static char isWin(char board[][COL], int row)
{
int i = 0;
for (; i < row; i++)
{
if (board[i][0] == board[i][1] && board[i][1] == board[i][2]&&board[i][0]!=' ' )
{
return board[i][0];
}
}
for (i = 0; i < row; i++)
{
if (board[0][i] == board[1][i] && board[1][i] == board[2][i]&&board[0][i]!=' ')
{
return board[0][i];
}
}
if (board[0][0] == board[1][1] && board[1][1] == board[2][2]&&board[0][0]!=' ')
{
return board[1][1];
}
if (board[0][2] == board[1][1] && board[1][1] == board[2][0]&&board[0][2]!=' ')
{
return board[1][1];
}
if (isFull(board, row))
{
return 'q';
}
return ' ';
}
//游戏
void game()
{
char board[ROW][COL];
memset(board,' ', ROW*COL);
char ret;
do
{
displayBoard(board,ROW);
playerMove(board, ROW);
ret = isWin(board, ROW);
if (ret != ' ')
{
break;
}
computerPlayer(board, ROW);
} while (ret == ' ');
if (ret == 'x')
{
printf("恭喜你!你赢了\n");
}
else if (ret == 'o')
{
printf("电脑胜利!\n");
}
else if (ret == 'q')
{
printf("平局!\n");
}
else
{
printf("debug!\n");
}
}
main.c
#include "game.h"
//显示菜单界面
void menu()
{
printf("#########################\n");
printf("####1.play 2.exit####\n");
printf("#########################\n");
}
int main()
{
int input = 0;
do
{
menu();
printf("please choose<0|1>:");
scanf("%d", &input);
switch (input)
{
case 1:
game();
break;
case 0:
exit(0);
default:
break;
}
} while (1);
}