Add small helper functions

This commit is contained in:
Sage Vaillancourt 2020-12-30 10:08:18 -05:00
parent e121755d29
commit a83829e2aa
1 changed files with 31 additions and 22 deletions

View File

@ -135,14 +135,15 @@ class Board extends React.Component {
new Piece(BLACK, KNIGHT), new Piece(BLACK, KNIGHT),
new Piece(BLACK, ROOK) new Piece(BLACK, ROOK)
]; ];
function add(num, color, type) {
for(var i = 0; i < num; i++) {
squares.push(new Piece(color, type));
}
}
let squares = whiteRow; let squares = whiteRow;
for(var i = 0; i < 8; i++) { add(8, WHITE, PAWN);
squares.push(new Piece(WHITE, PAWN));
}
squares = squares.concat(Array(32).fill(null)); squares = squares.concat(Array(32).fill(null));
for(i = 0; i < 8; i++) { add(8, BLACK, PAWN);
squares.push(new Piece(BLACK, PAWN));
}
squares = squares.concat(blackRow); squares = squares.concat(blackRow);
return squares; return squares;
@ -154,10 +155,18 @@ class Board extends React.Component {
return [x, y]; return [x, y];
} }
getIndex(x, y) {
return x + (y * 8);
}
isValidXY(x, y) {
return x < 8 && x >=0 && y < 8 && y >= 0;
}
pieceAt(x, y) { pieceAt(x, y) {
let i = x + (y * 8); let i = this.getIndex(x, y);
if (i < 64 && x < 8 && y < 8 && x >= 0 && y >= 0) { if (i < 64 && this.isValidXY(x, y)) {
return this.state.squares[x + (y * 8)]; return this.state.squares[this.getIndex(x, y)];
} else { } else {
return null; return null;
} }
@ -188,7 +197,8 @@ class Board extends React.Component {
var i; var i;
var moves = []; var moves = [];
let tryAddMove = (x, y) => { let tryAddMove = (x, y) => {
if (x >= 0 && x < 8 && y >= 0 && y < 8 && this.pieceAt(x, y) == null) { if (this.isValidXY(x, y)) {
if(this.pieceAt(x, y) == null) {
moves.push({x: x, y: y}); moves.push({x: x, y: y});
// Keep searching // Keep searching
return 0; return 0;
@ -197,6 +207,7 @@ class Board extends React.Component {
} }
// Stop searching // Stop searching
return 1; return 1;
}
}; };
if (isPawn(piece)) { if (isPawn(piece)) {
@ -222,7 +233,7 @@ class Board extends React.Component {
} }
} }
[x + 1, x - 1].forEach(x => { [x + 1, x - 1].forEach(x => {
if (x >= 0 && x < 8 && this.isEnemyOf(piece, x, y + shift)) { if (this.isValidXY(x, y + shift) && this.isEnemyOf(piece, x, y + shift)) {
moves.push({x: x, y: y + shift}); moves.push({x: x, y: y + shift});
} }
}); });
@ -393,9 +404,7 @@ class Board extends React.Component {
let [destX, destY] = this.getXandY(dest); let [destX, destY] = this.getXandY(dest);
for (var move of this.getValidMoves(source)) { for (var move of this.getValidMoves(source)) {
let x = move.x; if (destX === move.x && destY === move.y) {
let y = move.y;
if (destX === x && destY === y) {
return move; return move;
} }
} }