I have a table with 8 <tr>s, each with 8 <td>s, each with a data-x value and data-y value of between one and eight, i.e. an 8×8 grid for a chessboard.
Given that bishops can only move diagonally and I have the coordinates of the starting and ending squares, what is the most efficient way to find all the <td> elements in the ‘path’.
Example:
// 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)
How could I select these elements:
td[data-x="5"][data-y="5"],
td[data-x="6"][data-y="4"],
td[data-x="7"][data-y="3"]
in the most efficient way, baring in mind the from and to are set dynamically?
For information, I have written a function used elsewhere to check if the bishop has moved diagonally to start with:
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;
}
}
I can only think of something like this:
http://jsfiddle.net/zerkms/gtEwV/1/