diff --git a/assets/js/hooks/chessBoard.js b/assets/js/hooks/chessBoard.js index 7e2ad40..c7b2fda 100644 --- a/assets/js/hooks/chessBoard.js +++ b/assets/js/hooks/chessBoard.js @@ -13,7 +13,7 @@ export const ChessBoard = { dests: this.getValidDests(), }, events: { - move: (orig, dest, _metadata) => { + move: (orig, dest, _capturedPiece) => { this.handleMove(orig, dest); }, }, @@ -41,27 +41,43 @@ export const ChessBoard = { }, getValidDests() { - // Convert chess.js moves into the Map format Chessground expects const dests = new Map(); + this.chess.moves({ verbose: true }).forEach((m) => { if (!dests.has(m.from)) dests.set(m.from, []); dests.get(m.from).push(m.to); }); + return dests; }, handleMove(orig, dest) { - const move = this.chess.move({ from: orig, to: dest, promotion: "q" }); + const { role, color } = this.ground.state.pieces.get(dest); + const destRank = dest.split("").pop() + + const isPromotion = this.isPromotion(role, destRank) + + if (isPromotion) { + console.log("PROMOTION LOGIC") + this.executeMove(orig, dest, "q"); + return + } + + this.executeMove(orig, dest, "q"); + }, + + isPromotion(piece, rank) { + return piece === "pawn" && (rank === "1" || rank === "8"); + }, + + showPromotionDialog() { + console.log("trigger promotion dialog"); + }, + + executeMove(orig, dest, promotion) { + const move = this.chess.move({ from: orig, to: dest, promotion }); if (move) { - const piece = this.chess.get(orig); - - if (piece && piece.type === "p" && (dest[1] === "8" || dest[1] === "1")) { - this.pendingPromotion = { orig, dest }; - this.showPromotionDialog(); - return; - } - this.pushEvent("move_played", { from: orig, to: dest, @@ -73,6 +89,7 @@ export const ChessBoard = { this.ground.set({ turnColor: nextTurnColor, + fen: this.chess.fen(), movable: { color: nextTurnColor, dests: this.getValidDests(),