中国象棋算法
2024-07-22 19:52:43作者:饭克斯
对于中国象棋,每一个字都有自己的规则,正所谓无规矩不成方圆。
棋盘先设定好,a:array[1..10][1..9]ofMapStruct;
是个二维数组,每个单元符全自定义的棋盘结构
不要定义一个棋字结构
intStepJudge(intoldx,intoldy,intnowx,intnowy)
/*oldx,oldy棋字原来位置*/
/*oldx,oldy棋字新位置*/
/*判断从原位置到新位置的合法性*/
{
intindex,count=0;
intnox,noy;
intx,y,x1,x2,y1,y2;
BYTEChessId;/*棋字是哪一方的,有RED,BLUE,NONE三种值*/
ChessId=map[oldx][oldy].Id;
if(ChessId==NONE)return0;
if(oldx==nowx&&oldy==nowy)return0;
if(nowx>8||nowx9)return0;
nox=nowx-oldx;noy=nowy-oldy;
switch(map[oldx][oldy].num)
{
case0:/*HeaderCapital*/将或帅
{
if(map[nowx][nowy].num==0&&map[nowx][nowy].Id!=NONE&&oldx==nowx)
{
/*FacetoFace*/
y1=oldy;y2=nowy;
if(nowy<oldy)Swap(&y1,&y2);
for(y=y1+1;y<y2;y++)if(map[nowx][y].Id!=NONE)count++;
if(count==0)return1;
}
if(abs(nox)>1||abs(noy)>1||abs(nox)==1&&abs(noy)==1)return0;
if(nowy>2&&nowy5)return0;
break;
}
case14:case15:/*Genaral*/车
{
if(abs(nox)!=0&&abs(noy)!=0)return0;
if(abs(nox)>1&&noy==0)
{
x1=oldx;x2=nowx;
if(nowx<oldx)Swap(&x1,&x2);
for(x=x1+1;x<x2;x++)if(map[x][nowy].Id!=NONE)return0;
}
if(nox==0&&abs(noy)>1)
{
y1=oldy;y2=nowy;
if(nowy<oldy)Swap(&y1,&y2);
for(y=y1+1;y<y2;y++)if(map[nowx][y].Id!=NONE)return0;
}
break;
}
case10:case11:/*Horse*/马
{
if(abs(nox)==2&&abs(noy)==1||abs(nox)==1&&abs(noy)==2)
{
if(abs(nox)==1&&map[oldx][oldy+noy/2].Id!=NONE)return0;
if(abs(nox)==2&&map[oldx+nox/2][oldy].Id!=NONE)return0;
break;
}
elsereturn0;
}
case12:case13:/*Gun*/炮
{
if(abs(nox)>0&&abs(noy)>0)return0;
if(abs(nox)>0&&noy==0)
{
x1=oldx;x2=nowx;
if(nowx<oldx)Swap(&x1,&x2);
for(x=x1+1;x<x2;x++)if(map[x][nowy].Id!=NONE)count++;
}
elseif(nox==0&&abs(noy)>0)
{
y1=oldy;y2=nowy;
if(nowy<oldy)Swap(&y1,&y2);
for(y=y1+1;y<y2;y++)if(map[nowx][y].Id!=NONE)count++;
}
if(count==0&&map[nowx][nowy].Id!=NONE)return0;
if(count==1&&map[nowx][nowy].Id==NONE)return0;
if(count>1)return0;
break;
}
case3:case4:/*Minister*/象或相
{
if(abs(nox)!=2||abs(noy)!=2)return0;
elseif(map[oldx+nox/2][oldy+noy/2].Id!=NONE)return0;
if(nowy==0||nowy==4||nowy==5||nowy==9)
if(nowx==2||nowx==6)break;
if(nowy==2||nowy==7)
if(nowx==0||nowx==4||nowx==8)break;
}
case1:case2:/*Shi*/士或仕
{
if(abs(nox)!=1||abs(noy)!=1)return0;
if(nowy>2&&nowy5)return0;
break;
}
case5:case6:case7:case8:case9:/*Soldier*/兵或卒
{
if(abs(nox)>0&&abs(noy)>0)return0;
if(ChessId==GREEN&&GreenChess[0].y<3||ChessId==RED&&RedChess[0].y<3)
{
if(oldy>4)
{
if(nox==0&&noy!=1)return0;
if(abs(nox)!=1&&noy==0)return0;
}
if(oldy<5)if(nox!=0||noy!=1)return0;
}
if(ChessId==GREEN&&GreenChess[0].y>6||ChessId==RED&&RedChess[0].y>6)
{
if(oldy<5)
{
if(nox==0&&noy!=-1)return0;
if(abs(nox)!=1&&noy==0)return0;
}
if(oldy>4)if(nox!=0||noy!=-1)return0;
}
index=map[oldx][oldy].num;
if(ChessId==GREEN)
if(GreenChess[0].y4||GreenChess[0].y>6&&GreenChess[index].y<5)
GreenChess[index].FixLevel=ADVANCED_SOLDIER_LEVEL;
if(ChessId==RED)
if(RedChess[0].y4||RedChess[0].y>6&&RedChess[index].y<5)
RedChess[index].FixLevel=ADVANCED_SOLDIER_LEVEL;//兵过河后等级值加1
break;
}
}
if(ChessId==map[nowx][nowy].Id)return2;
elsereturn1;
}
用c语言写的