diff --git a/src/index.js b/src/index.js index bf96000..06c5881 100644 --- a/src/index.js +++ b/src/index.js @@ -135,14 +135,15 @@ class Board extends React.Component { new Piece(BLACK, KNIGHT), 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; - for(var i = 0; i < 8; i++) { - squares.push(new Piece(WHITE, PAWN)); - } + add(8, WHITE, PAWN); squares = squares.concat(Array(32).fill(null)); - for(i = 0; i < 8; i++) { - squares.push(new Piece(BLACK, PAWN)); - } + add(8, BLACK, PAWN); squares = squares.concat(blackRow); return squares; @@ -154,10 +155,18 @@ class Board extends React.Component { 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) { - let i = x + (y * 8); - if (i < 64 && x < 8 && y < 8 && x >= 0 && y >= 0) { - return this.state.squares[x + (y * 8)]; + let i = this.getIndex(x, y); + if (i < 64 && this.isValidXY(x, y)) { + return this.state.squares[this.getIndex(x, y)]; } else { return null; } @@ -188,15 +197,17 @@ class Board extends React.Component { var i; var moves = []; let tryAddMove = (x, y) => { - if (x >= 0 && x < 8 && y >= 0 && y < 8 && this.pieceAt(x, y) == null) { - moves.push({x: x, y: y}); - // Keep searching - return 0; - } else if (this.isEnemyOf(piece, x, y)) { - moves.push({x: x, y: y}); + if (this.isValidXY(x, y)) { + if(this.pieceAt(x, y) == null) { + moves.push({x: x, y: y}); + // Keep searching + return 0; + } else if (this.isEnemyOf(piece, x, y)) { + moves.push({x: x, y: y}); + } + // Stop searching + return 1; } - // Stop searching - return 1; }; if (isPawn(piece)) { @@ -208,7 +219,7 @@ class Board extends React.Component { let left = this.pieceAt(x - 1, y); let right = this.pieceAt(x + 1, y); if (left != null && left.passantable && left.color !== piece.color) { - moves.push({x:x - 1, y:y + shift, passant: {x: x - 1, y: y}}) + moves.push({x: x - 1, y: y + shift, passant: {x: x - 1, y: y}}) } if (right != null && right.passantable && right.color !== piece.color) { moves.push({x: x + 1, y: y + shift, passant: {x: x + 1, y: y}}) @@ -222,7 +233,7 @@ class Board extends React.Component { } } [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}); } }); @@ -393,9 +404,7 @@ class Board extends React.Component { let [destX, destY] = this.getXandY(dest); for (var move of this.getValidMoves(source)) { - let x = move.x; - let y = move.y; - if (destX === x && destY === y) { + if (destX === move.x && destY === move.y) { return move; } }