1.game.h头文件
#define ROW 3
#define COL 3
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
//初始化棋盘
void init(char board[ROW][COL],int row,int col);
//打印棋盘
void displayboard(char board[ROW][COL],int row,int col);
//玩家下棋
void playermove(char board[ROW][COL],int row,int col);
//电脑下棋
void computermove(char board[ROW][COL],int row,int col);
//判断输赢
char iswin(char board[ROW][COL],int row,int col);
2.test.c源文件
#include"game.h"
void menu()
{
printf("*********************\n");
printf("***1.play 0.exit***\n");
printf("*********************\n");
}
void game()
{
char ret=0;
char board[ROW][COL]={0};
//初始化棋盘的函数
init(board,ROW,COL);
displayboard(board,ROW,COL);//打印棋盘
//下棋
while(1)
{
playermove(board,ROW,COL);
//判断输赢
ret=iswin(board,ROW,COL);
if(ret!='!')
{
break;
}
displayboard(board,ROW,COL);
computermove(board,ROW,COL);
//判断输赢
ret=iswin(board,ROW,COL);
if(ret!='!')
{
break;
}
displayboard(board,ROW,COL);
}
if(ret=='*')
{
printf("玩家赢\n");
displayboard(board,ROW,COL);
}
else if(ret=='#')
{
printf("电脑赢\n");
displayboard(board,ROW,COL);
}
else
{
printf("平局\n");
}
}
int main()
{
int i=0;
srand((unsigned int)time(NULL));
do
{
menu();//打印菜单
printf("请输入:");
scanf("%d",&i);
switch(i)
{
case 1:
game();
break;
case 0:
printf("退出游戏\n");
break;
default:
printf("输入错误,重新输入\n");
break;
}
}while(i);
return 0;
}
3.game.c源文件
#include"game.h"
void init(char board[ROW][COL],int row,int col)
{
int i=0;
int j=0;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
board[i][j]=' ';
}
}
}
void displayboard(char board[ROW][COL],int row,int col)
{
int i=0;
int j=0;
for(i=0;i<row;i++)
{
//打印数据
for(j=0;j<col;j++)
{
printf("%c ",board[i][j]);
if(j<col-1)
printf("|");
}
printf("\n");
//打印分割行
if(i<row-1)
{
for(j=0;j<col;j++)
{
printf("--");
if(j<col-1)
printf("|");
}
}
printf("\n");
}
}
void playermove(char board[ROW][COL],int row,int col)
{
int x=0;
int y=0;
printf("玩家下棋:");
while(1)
{
scanf("%d %d",&x,&y);
if(x>=1&&x<=row&&y>=1&&y<=col)
{
if(board[x-1][y-1]==' ')
{
board[x-1][y-1]='*';
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()%row;
y=rand()%col;
if(board[x][y]==' ')
{
board[x][y]='#';
break;
}
}
}
int is_full(char board[ROW][COL],int row,int col)
{
int i=0;
int j=0;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
if(board[i][j]==' ')
{
return 0;
}
}
}
return 1;
}
char iswin(char board[ROW][COL],int row,int col)
{
int i=0;
int j=0;
//行
for(i=0;i<row;i++)
{
if(board[i][0]==board[i][1]&&board[i][1]==board[i][2]&&board[i][1]!=' ')
{
return board[i][1];
}
//列
if(board[0][j]==board[1][j]&&board[1][j]==board[2][j]&&board[0][j]!=' ')
{
return board[1][j];
}
//对角线
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(is_full(board,row,col))
{
return '~';
}
//继续
return '!';
}