下棋的过程中,某一方主帅被对方攻击就是将军,如果不能解除危险,就是死棋。在这个游戏中实现了将军的判断和死棋的检测。具体如下:
(1)每走一步棋时,先要判断自己能不能这样走,当然除了走法是否合乎规则,比如说是否为蹩脚马等等,还要判断自己这样走是否被对方将军。
(2)走完一步棋后,还要判断是否将对方的军,是否造成对方死棋。
首先介绍一下将军的判断方法:能够将军的无非就是对方的车,马,炮,兵和主帅,只要穷举一下,看对方的能否那样走棋,如果能攻击就是将军了。
bool MoveGenerator::isAttackGeneral(const char *arrChessman, char attackedGeneral)
{
int pos[5];
memset(pos, 0, sizeof(int) * 5);
getChessmanPos(arrChessman, attackedGeneral, pos);
bool attacked = false;
if (attackedGeneral == BLACK_GENERAL)
{
attacked = attackedByGeneral(arrChessman, pos[0], RED_GENERAL) ||
attackGeneral(arrChessman, pos[0], RED_CHARIOT) ||
attackGeneral(arrChessman, pos[0], RED_CANNON) ||
attackGeneral(arrChessman, pos[0], RED_HORSE) ||
attackGeneral(arrChessman, pos[0], RED_SOLDIER);
}
else
{
attacked = attackedByGeneral(arrChessman, pos[0], BLACK_GENERAL) ||
attackGeneral(arrChessman, pos[0], BLACK_CHARIOT) ||
attackGeneral(arrChessman, pos[0], BLACK_CANNON) ||
attackGeneral(arrChessman, pos[0], BLACK_HORSE) ||
attackGeneral(arrChessman, pos[0], BLACK_SOLDIER);
}
return attacked;
}
关于死棋检测,自己被对方将军了,自己能否解除将军的局面,死里逃生。
bool MoveGenerator::canSaveGeneral(char *arrChessman, int index, char attackedGeneral)
{
bool saved = false;
char killedChessman = 0;
char movingChessman = arrChessman[index];
for (int i = RANK_TOP; i <= RANK_BOTTOM; i++)
{
for (int j = FILE_LEFT; j <= FILE_RIGHT; j++)
{
int dstPos = COORD_XY(j, i);
if (validateMove(arrChessman, index, dstPos))
{
killedChessman = arrChessman[dstPos];
//再判断走棋后,自己是否被对方将军
arrChessman[index] = 0;
arrChessman[dstPos] = movingChessman;
if (!isAttackGeneral(arrChessman, attackedGeneral))
{
saved = true;
}
arrChessman[index] = movingChessman;
arrChessman[dstPos] = killedChessman;
if (saved)
{
break;
}
}
}
}
return saved;
}
源代码下载链接:
http://download.csdn.net/detail/zxywd/9172917