三字棋是C语言学习阶段一个有趣的项目,就分享给大家了
#include<stdio.h>
#include<stdlib.h>#include<time.h>
char a[4][4]={0};
int size= 9;
void dayinqipan() //打印棋盘
{
int i=1;
printf(" | | \n");
for(i=1;i<4;i++)
{
printf("_%c_|_%c_|_%c_\n",a[i][1],a[i][2],a[i][3]);
if(i<3)
printf(" | | \n");
}
}
void chushihuaqipan() //初始化棋盘
{
int i = 0;
int j = 0;
for(i=1;i<4;i++)
{
for(j=1;j<4;j++)
{
a[i][j]=' ';
}
}
}
void w_play() //玩家棋子
{
int n;
int m;
printf("请输入棋子位置您的棋子为:");
scanf("%d %d",&m,&n);
if(m<1||m>3||n<1||n>3||a[m][n]!=' ')
{
printf("您输入的坐标不合法:\n");
w_play();
}
else
{
a[m][n]='1';
size=size-1;
}
}
void c_play() //电脑棋子
{
int n=0;
int m=0;
printf("电脑的棋子为0\n");
m=rand()%3;
n=rand()%3;
while(a[m][n] != ' ')
{
m=rand()%3;
n=rand()%3;
}
a[m][n]='0';
size=size-1;
}
int winner() //判断输赢
{
if((a[1][1]==a[1][2]&&a[1][2]==a[1][3]&&a[1][3]=='1')||
(a[2][1]==a[2][2]&&a[2][2]==a[2][3]&&a[2][3]=='1')||
(a[3][1]==a[3][2]&&a[3][2]==a[3][3]&&a[3][3]=='1')||
(a[1][1]==a[2][1]&&a[2][1]==a[3][1]&&a[3][1]=='1')||
(a[1][2]==a[2][2]&&a[2][2]==a[3][2]&&a[3][2]=='1')||
(a[1][3]==a[2][3]&&a[2][3]==a[3][3]&&a[3][3]=='1')||
(a[1][1]==a[2][2]&&a[2][2]==a[3][3]&&a[3][3]=='1')||
(a[1][3]==a[2][2]&&a[2][2]==a[3][1]&&a[3][1]=='1'))
return 1;
else if((a[1][1]==a[1][2]&&a[1][2]==a[1][3]&&a[1][3]=='0')||
(a[2][1]==a[2][2]&&a[2][2]==a[2][3]&&a[2][3]=='0')||
(a[3][1]==a[3][2]&&a[3][2]==a[3][3]&&a[3][3]=='0')||
(a[1][1]==a[2][1]&&a[2][1]==a[3][1]&&a[3][1]=='0')||
(a[1][2]==a[2][2]&&a[2][2]==a[3][2]&&a[3][2]=='0')||
(a[1][3]==a[2][3]&&a[2][3]==a[3][3]&&a[3][3]=='0')||
(a[1][1]==a[2][2]&&a[2][2]==a[3][3]&&a[3][3]=='0')||
(a[1][3]==a[2][2]&&a[2][2]==a[3][1]&&a[3][1]=='0'))
return 0;
else if(size==0)
return -1;
else
return 2;
}
int main()
{
int input=1;
int b;
srand((unsigned int)time(NULL));
while(input)
{
printf("######################\n");
printf("#######三子棋游戏#####\n");
printf("## 1.play ##\n");
printf("## 0.exit ##\n");
printf("######################\n");
printf("请选择:");
scanf("%d",&b);
switch(b)
{
case 1:
chushihuaqipan();
while(1)
{
dayinqipan();
if(winner()==-1||winner()==0||winner()==1)
{
break;
}
w_play();
dayinqipan();
if(winner()==-1||winner()==0||winner()==1)
{
break;
}
c_play();
}
if(winner()==1)
{
printf("玩家获胜");
}
else if(winner()==0)
{
printf("你输了");
}
else
{
printf("普天同庆平局");
}
break;
case 0:
break;
}
}
system("pause");
return 0;
}