棋盤棋子繪制完成后,接下來玩家要移動(dòng)棋子開始與機(jī)器對(duì)弈训措。
那么如何判斷當(dāng)前棋子移動(dòng)合法?
棋盤中所有的位置坐標(biāo)映射為一個(gè)二維數(shù)組效果圖莉测,藍(lán)色數(shù)字代表數(shù)組維數(shù)
棋盤二維數(shù)組表示圖
黑帥移動(dòng)規(guī)則:不能出九宮格据过,走直線,每步只能走一格
黑方九宮格
黑士移動(dòng)規(guī)則:不能出九宮格鞠绰,走斜線,每步只能走一格
黑方九宮格
黑象移動(dòng)規(guī)則:不能過河飒焦,走“田”字蜈膨,象眼處沒有棋子
黑象移動(dòng)規(guī)則圖
馬移動(dòng)規(guī)則:馬走"日",馬蹄處沒有棋子
車移動(dòng)規(guī)則:走直線
兵移動(dòng)規(guī)則:走直線,不能后退牺荠,過河前翁巍,只能向前,過了河休雌,可左右移動(dòng)灶壶,每步只能走一格
炮移動(dòng)規(guī)則:走直線,隔棋吃棋子
了解完棋子移動(dòng)規(guī)則杈曲。
我們用代碼來實(shí)現(xiàn)如上規(guī)則
首先要把坐標(biāo)轉(zhuǎn)變?yōu)閿?shù)組的維數(shù)
//二維數(shù)組
int[][] qizi;
//起始位置維數(shù)
int fromY, fromX;
//目的位置維數(shù)
int toY, toX;
// 起始位置是什么棋子
int moveChessID = qizi[fromX][fromY] ;
//黑帥
moveChessID == 1;
if (toY > 2 || toX < 3 || toX > 5 ) {//出了九宮格
return false;
} else if ((Math.round(toX-fromX) + Math.round(toY - fromY)) == 1) {
//只能走一格
return true;
} else {
return false;
}
//黑士
moveChessID == 5;
if (toY > 2 || toX < 3 || toX > 5) { //出了九宮格
return false;
} else if (Math.round(toX - fromX) == 1 && Math.round(toY - fromY) == 1) {
//走斜線驰凛,直走一格
return true;
} else {
return false;
}
//黑象
moveChessID == 6;
if (toY > 4) {//過河了
return false;
} else if (Math.roung(toY - fromY) == 2 && Math.round(toX - fromX) == 2) {
//走"田"字
int centerX = ( toY + fromY) / 2;
int centerY = (toX + fromX) / 2;
if (qizi[centerY][centerX] != 0) {// 象眼處有棋子
return false;
}
return true;
} else {
return false;
}
//黑馬
moveChessID == 3;
if (Math.round(toY - fromY) == 2 && Math.round(toX - fromX) == 1) {
int centerY = (toY + fromY) / 2;
if (qizi[centerY][fromX] != 0) {//馬蹄處有棋子
return false;
}
return true;
} else if (Math.round(toY - fromY) == 1 && Math.round(toX - fromX) == 2) {
int centerX = (toX + fromX) / 2;
if (qizi[fromY][centerX] != 0) {//馬蹄處有棋子
return false;
}
return true;
} else {
return false;
}
//車
moveChessID == 2 || moveChessID == 9;
if (Math.round(toY - fromY) > 0 && Math.round(toX - fromX) == 0) {
//走的橫豎線
if (toY > fromY) {
for (int i = fromY + 1 ; i < toY; i++) {
if (qizi[i][fromX] != 0) {
return false;
}
}
} else {
for (int i = toY - 1 ; i > fromY; i--) {
if (qizi[i][fromX] != 0) {
return false;
}
}
}
return true;
} else if (Math.round(toX - fromX) > 0 && Math.round(toY - fromY) == 0) {
//走的橫線
if (toX > fromX) {
for (int i = fromX + 1 ; i < toX; i++) {
if (qizi[fromY][i] != 0) {
return false;
}
}
} else {
for (int i = toX - 1 ; i > fromX; i--) {
if (qizi[fromY][i] != 0) {
return false;
}
}
}
return true;
} else {
return false;
}
//黑士
moveChessID == 7;
if ((toY - fromY) < 0 ) {
//后退
return false;
} else if (fromY > 4) {//過了河
if () {
}
} else {//沒過河
}