Reputation: 1459
I'm currently writing a chess program and trying to loop through all rook's moves. For that, I need to get these set of numbers: 1 0 (right), -1 0 (left), 0 1 (up), 0 -1 (down). I came up with this line of code:
if (this.piece == "rook" || this.piece == "queen") {
for (var dir = -3; dir <= 3; dir += 2) {
let checkChar = pposChar, checkNum = pposNum, m1, m2;
for (var i = 0; i < this.step; i++) {
if (dir == 1 || dir == -1) {
m1 = 0, m2 = dir;
} else {
m1 = dir/Math.abs(dir), m2 = 0;
}
if (isLegal(checkChar, checkNum, m1, m2)) {
this.moves.push(isLegal(checkChar, checkNum, m1, m2));
checkChar += m1;
checkNum += m2;
} else
break;
}
}
}
It works just fine, but it looks kind of ugly and hard to read. Is there any way to perform this cleaner or better?
Upvotes: 1
Views: 123
Reputation: 386578
Just take an array of offsets and add these values to the indices.
var adjacent = [[1, 0], [-1, 0], [0, 1], [0 -1]];
Upvotes: 2