瞎几把的写五子棋
#include <stdio.h>
#include <string.h>
#define CHESSBOARDROW 19
#define CHESSBOARDCOL 19
char chessboard[CHESSBOARDROW][CHESSBOARDCOL];
void initchessboard()
{
memset(chessboard,'0',CHESSBOARDROW*CHESSBOARDROW);
int k1=1,k2=1;
chessboard[0][0]=' ';
for(int j=1;j<CHESSBOARDROW;j++)
{
if(j%2 == 0)
{
chessboard[0][j]=(k1+'0');
k1++;
}
}
for(int i=1;i<CHESSBOARDROW;i++)
{
if(i%2 == 0)
{
chessboard[i][0]=(k2+'0');
k2++;
}
}
for(int i=1;i<CHESSBOARDROW;i++)
{
for(int j=1;j<CHESSBOARDCOL;j++)
if(i%2==0 && j%2 ==0)
chessboard[i][j] = '.';
}
}
void showchessboard()
{
for(int i=0;i<CHESSBOARDROW;i++)
{
for(int j=0;j<CHESSBOARDCOL;j++)
if(i%2==0 && j%2 ==0)
printf("%3c",chessboard[i][j]);
else
printf("%c",' ');
printf("\n");
}
}
int is_vaild(int x,int y)
{
//出了边界违法,这个地方有旗子也违法
if(x<1 || x>9 || y<1 || x>9)
return 0;
if(chessboard[x*2][y*2]!='.')
return 0;
chessboard[x*2][y*2] = 'x';
return 1;
}
int is_again(int ret)
{
if(ret == 0)
return -1;
if(ret == 3)
printf("平局!\n");
else
printf("玩家%d获胜!\n",ret);
int again = -1;
do
{
printf("是否继续玩:(0:退出,1:继续) ");
scanf("%d",&again);
}while(again!=0 && again!=1);
return again;
}
int Judge_who_win(int play,int x,int y)
{
char chess[2] = {0};
chess[0] = 'x';
if(play != 1)
chess[0] = 'o';
int flag = 0,is_full = 0;
chessboard[x*2][y*2]=chess[0];
for(int k = 0;k<4;k++) //四个方向的判断
{
int step=8,is_win =0;
for(int i=0;i<5;i++) //5个位置的移动
{
for(int j=0;j<9;j+=2) //判断五个旗子
{
int px,py;
if(k==0)
{
px = x*2-step+j;
py = y*2-step+j;
}
else if(k==1)
{
px = x*2;
py = y*2-step+j;
}
else if(k==2)
{
px = x*2+step-j;
py = y*2-step+j;
}
else if(k==3)
{
px = x*2-step+j;
py = y*2;
}
if((px > 1 && px < CHESSBOARDROW) && (py > 1 && py < CHESSBOARDCOL) && chessboard[px][py] == chess[0])
is_win++;
else
{
is_win = 0;
break;
}
}
if(is_win == 5)
{
flag = 1;
break;
}
step-=2;
is_win=0;
}
if(flag)
break;
}
if(flag)
{
if(play!=1)
play = 2;
return play;
}
end:
for(int i =2;i<CHESSBOARDROW;i+=2)
{
for(int j =2;i<CHESSBOARDCOL;j+=2)
{
if(chessboard[i][j] == '.')
{
is_full = 0;
break;
}
}
}
if(is_full)
return 3;
return 0;
}
int main()
{
//玩家1是x,玩家2是o
//平局是3
int playx,playy;
int again = 1,vaildret,play,ret =0;
do
{
if(again == 1)
{
initchessboard();
play = 1,vaildret=1,ret=0,again = 0;
showchessboard();
}
do
{
if(!vaildret)
printf("落子位置违法,");
if(play<0)
printf("请玩家%d落子(x y): ",2);
else
printf("请玩家%d落子(x y): ",play);
scanf("%d %d",&playx,&playy); //非法输入会死循环
vaildret = is_vaild(playx,playy);
}while(!vaildret);
ret = Judge_who_win(play,playx,playy);
showchessboard();
again = is_again(ret);
play*=-1;
}while (again);
printf("退出游戏!\n");
return 0;
}
懒死了----------------------