Skip to content

Commit

Permalink
handle invalid move exceptioin & support promotion
Browse files Browse the repository at this point in the history
  • Loading branch information
Nathaniel Tampus committed Jan 16, 2023
1 parent f108262 commit e823fb1
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 21 deletions.
47 changes: 27 additions & 20 deletions client/src/components/Board/Board.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,8 @@ const Board = () => {

socket.on("receivedLatestGame", (latestGame: Game) => {
if (latestGame.pgn) {
const loadSuccess = game.loadPgn(latestGame.pgn);
if (loadSuccess) {
forceUpdate();
}
game.loadPgn(latestGame.pgn);
forceUpdate();
}
if (latestGame.black?.id === session?.user.id) {
if (side !== "b") setSide("b");
Expand Down Expand Up @@ -80,16 +78,21 @@ const Board = () => {
}

function makeMove(m: { from: string; to: string; promotion?: string }) {
const result = game.move({ from: m.from, to: m.to });
if (result) {
setOptionSquares({
[m.from]: { background: "rgba(255, 255, 0, 0.4)" },
[m.to]: { background: "rgba(255, 255, 0, 0.4)" }
});
} else {
try {
const result = game.move(m);
if (result) {
setOptionSquares({
[m.from]: { background: "rgba(255, 255, 0, 0.4)" },
[m.to]: { background: "rgba(255, 255, 0, 0.4)" }
});
return result;
} else {
throw new Error("invalid move");
}
} catch (e) {
setOptionSquares({});
return false;
}
return result;
}

function isDraggablePiece({ piece }: { piece: string }) {
Expand All @@ -100,13 +103,15 @@ const Board = () => {
function onDrop(sourceSquare: Square, targetSquare: Square) {
if (side !== game.turn()) return false;

const move = makeMove({
const moveDetails = {
from: sourceSquare,
to: targetSquare,
promotion: "q"
});
if (move === null) return false; // illegal move
socket?.emit("sendMove", { from: move.from, to: move.to });
};

const move = makeMove(moveDetails);
if (!move) return false; // illegal move
socket?.emit("sendMove", moveDetails);
return true;
}

Expand Down Expand Up @@ -163,16 +168,18 @@ const Board = () => {
return;
}

const move = makeMove({
const moveDetails = {
from: moveFrom as Square,
to: square,
promotion: "q"
});
if (move === null) {
};

const move = makeMove(moveDetails);
if (!move) {
resetFirstMove(square);
} else {
setMoveFrom("");
socket?.emit("sendMove", { from: move.from, to: move.to });
socket?.emit("sendMove", moveDetails);
}
}

Expand Down
2 changes: 1 addition & 1 deletion server/src/socket/game.socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ export async function sendMove(this: Socket, m: { from: string; to: string; prom
this.emit("receivedLatestGame", game);
} else {
game.pgn = chess.pgn();
this.to(game.code as string).emit("receivedMove", { from: m.from, to: m.to });
this.to(game.code as string).emit("receivedMove", m);
}
}

Expand Down

0 comments on commit e823fb1

Please sign in to comment.