server-side move validation improvements

This commit is contained in:
Nathaniel Tampus
2023-01-16 15:25:39 +08:00
parent a65202357e
commit dc233b2c84

View File

@@ -87,36 +87,50 @@ export async function sendMove(this: Socket, m: { from: string; to: string; prom
if (game.pgn) { if (game.pgn) {
chess.loadPgn(game.pgn); chess.loadPgn(game.pgn);
} }
const prevTurn = chess.turn();
const newMove = chess.move(m);
if (chess.isGameOver()) {
let reason = "";
if (chess.isCheckmate()) reason = "checkmate";
else if (chess.isStalemate()) reason = "stalemate";
else if (chess.isThreefoldRepetition()) reason = "repetition";
else if (chess.isInsufficientMaterial()) reason = "insufficient";
else if (chess.isDraw()) reason = "draw";
const winnerSide = try {
reason === "checkmate" ? (prevTurn === "w" ? "white" : "black") : undefined; const prevTurn = chess.turn();
const winnerName =
reason === "checkmate" if (
? winnerSide === "white" (prevTurn === "b" && this.request.session.id !== game.black?.id) ||
? game.white?.name (prevTurn === "w" && this.request.session.id !== game.white?.id)
: game.black?.name ) {
: undefined; throw new Error("not turn to move");
if (reason === "checkmate") {
game.winner = winnerSide;
} else {
game.winner = "draw";
} }
io.to(game.code as string).emit("gameOver", { reason, winnerName, winnerSide });
} const newMove = chess.move(m);
if (newMove === null) { if (chess.isGameOver()) {
let reason = "";
if (chess.isCheckmate()) reason = "checkmate";
else if (chess.isStalemate()) reason = "stalemate";
else if (chess.isThreefoldRepetition()) reason = "repetition";
else if (chess.isInsufficientMaterial()) reason = "insufficient";
else if (chess.isDraw()) reason = "draw";
const winnerSide =
reason === "checkmate" ? (prevTurn === "w" ? "white" : "black") : undefined;
const winnerName =
reason === "checkmate"
? winnerSide === "white"
? game.white?.name
: game.black?.name
: undefined;
if (reason === "checkmate") {
game.winner = winnerSide;
} else {
game.winner = "draw";
}
io.to(game.code as string).emit("gameOver", { reason, winnerName, winnerSide });
}
if (newMove) {
game.pgn = chess.pgn();
this.to(game.code as string).emit("receivedMove", m);
} else {
throw new Error("invalid move");
}
} catch (e) {
console.log("sendMove error: " + e);
this.emit("receivedLatestGame", game); this.emit("receivedLatestGame", game);
} else {
game.pgn = chess.pgn();
this.to(game.code as string).emit("receivedMove", m);
} }
} }