3
我有一個table
8個<tr>
s,各具有8個<td>
s,各具有data-x
值和之間的一個和八個的data-y
值,即8×8網格,棋盤。jQuery的選擇所有S IN一個棋子的路徑
鑑於主教只能對角移動,並且我有起始和結束方塊的座標,所以在「路徑」中找到所有<td>
元素的最有效方法是什麼。
例子:
// coordinates representing a bishop move from d6 (4, 6) to h2 (8, 2)
var from = {
x: 4,
y: 6
},
to = {
x: 8,
y: 2
}
// code to select squares e5 (5,5), f4 (6,4) and g3 (7,3)
我怎麼會選擇這些元素:
td[data-x="5"][data-y="5"],
td[data-x="6"][data-y="4"],
td[data-x="7"][data-y="3"]
以最有效的方式,在思路中披露的from
和to
動態設置?
有關信息,我已經寫在其他地方用來檢查功能,如果主教搬到斜入手:
function is_valid_bishop_move(from, to){
var tan_theta = (to.y - from.y)/(to.x - from.x);
if(tan_theta === 1 || tan_theta === -1){
return true;
}else{
return false;
}
}
爲什麼不使用'return Math.abs(to.y - from.y)=== Math.abs(to.x - from.x)'? – Blender
另外,我實現了一個非常基本的Python國際象棋界面(它可以進行隨機有效移動),以防萬一你感興趣:https://github.com/Blender3D/Elephant/blob/master/main.py – Blender