Add small helper functions
This commit is contained in:
parent
e121755d29
commit
a83829e2aa
37
src/index.js
37
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,7 +197,8 @@ 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) {
|
||||
if (this.isValidXY(x, y)) {
|
||||
if(this.pieceAt(x, y) == null) {
|
||||
moves.push({x: x, y: y});
|
||||
// Keep searching
|
||||
return 0;
|
||||
|
@ -197,6 +207,7 @@ class Board extends React.Component {
|
|||
}
|
||||
// Stop searching
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
|
||||
if (isPawn(piece)) {
|
||||
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue