Add full checkmate functionality

Some clean-up of move-finding
This commit is contained in:
Sage Vaillancourt 2020-12-29 09:56:49 -05:00
parent 0a721d111a
commit d4b540a05b
1 changed files with 23 additions and 23 deletions

View File

@ -254,24 +254,16 @@ class Board extends React.Component {
moves = moves.concat(this.getValidMovesAt(rook, x, y));
moves = moves.concat(this.getValidMovesAt(bishop, x, y));
} else if (isKnight(piece)) {
tryAddMove(x + 2, y + 1);
tryAddMove(x + 2, y - 1);
tryAddMove(x - 2, y + 1);
tryAddMove(x - 2, y - 1);
tryAddMove(x + 1, y + 2);
tryAddMove(x + 1, y - 2);
tryAddMove(x - 1, y + 2);
tryAddMove(x - 1, y - 2);
let deltas = [
[2, 1], [2, -1], [-2, 1], [-2, -1],
[1, 2], [1, -2], [-1, 2], [-1, -2],
];
deltas.forEach((delta) => tryAddMove(x + delta[0], y + delta[1]));
} else if (isKing(piece)) {
tryAddMove(x + 1, y + 1);
tryAddMove(x + 1, y - 1);
tryAddMove(x - 1, y + 1);
tryAddMove(x - 1, y - 1);
tryAddMove(x, y + 1);
tryAddMove(x, y - 1);
tryAddMove(x + 1, y);
tryAddMove(x - 1, y);
let deltas = [
[1, 1], [1, -1], [-1, 1], [-1, -1], [0, 1], [0, -1], [1, 0], [-1, 0]
];
deltas.forEach((delta) => tryAddMove(x + delta[0], y + delta[1]));
}
return moves;
}
@ -335,7 +327,8 @@ class Board extends React.Component {
let moves = board.getValidMoves(i)
for(var j = 0; j < moves.length; j++) {
let [from, to] = moves[j];
board.makeMove(from, to);
board.state.squares[to] = board.state.squares[from];
board.state.squares[from] = null;
if (board.inCheck(checkedKing) !== checkedKing) {
return false;
}
@ -386,12 +379,12 @@ class Board extends React.Component {
if (this.isValidMove(from, to)) {
squares[to] = squares[from];
squares[from] = null;
this.setHand({
heldPiece: null,
});
this.setState({
squares: squares,
blackIsNext: !this.state.blackIsNext,
hand: {
heldPiece: null,
}
});
return 0;
}
@ -399,6 +392,9 @@ class Board extends React.Component {
}
handleClick(i) {
if (this.checkmate()) {
return;
}
if (this.isHoldingPiece()) {
if (this.makeMove(this.heldPiece(), i) !== 0) {
this.setHand({
@ -449,8 +445,12 @@ class Board extends React.Component {
render() {
let checkMsg = this.whoInCheck() ? "Check! " : "";
const status = this.checkmate() ? "CHECKMATE" :
checkMsg + (this.state.blackIsNext ? 'Black' : 'White') + "'s Turn";
let isCheckmate = this.checkmate();
var namedPlayer = isCheckmate ?
!this.state.blackIsNext : this.state.blackIsNext
let color = namedPlayer ? 'Black' : 'White';
const status = this.checkmate() ? "Checkmate! " + color + " Wins!" :
checkMsg + color + "'s Turn";
var texttext =
<div style={{textAlign: `center`,}}>