-
Notifications
You must be signed in to change notification settings - Fork 0
/
chessgame.js
107 lines (99 loc) · 3.36 KB
/
chessgame.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
const socket = io();
const chess = new Chess();
const boardElement = document.querySelector(".chessboard");
let draggedPiece = null;
let sourceSquare = null;
let playerRole = null;
const renderBoard = () => {
const board = chess.board();
boardElement.innerHTML = "";
board.forEach((row, rowindex) => {
row.forEach((square, squareindex) => {
const squareElement = document.createElement("div");
squareElement.classList.add("square", (rowindex + squareindex) % 2 == 0 ? "light" : "dark");
squareElement.dataset.row = rowindex;
squareElement.dataset.col = squareindex;
if (square) {
const pieceElement = document.createElement("div");
pieceElement.classList.add(
"piece", square.color === "w" ? "white" : "black"
);
pieceElement.innerText = getPieceUnicode(square);
pieceElement.draggable = playerRole === square.color;
pieceElement.addEventListener("dragstart", (e) => {
if (pieceElement.draggable) {
draggedPiece = pieceElement;
sourceSquare = { row: rowindex, col: squareindex };
e.dataTransfer.setData("text/plain", "");
}
});
pieceElement.addEventListener("dragged", (e) => {
draggedPiece = null;
sourceSquare = null;
});
squareElement.appendChild(pieceElement);
}
squareElement.addEventListener("dragover", function(e) {
e.preventDefault();
});
squareElement.addEventListener("drop", function(e) {
e.preventDefault();
if (draggedPiece) {
const targetSource = {
row: parseInt(squareElement.dataset.row),
col: parseInt(squareElement.dataset.col),
};
handleMove(sourceSquare, targetSource);
}
});
boardElement.appendChild(squareElement);
});
});
if (playerRole === 'b') {
boardElement.classList.add("flipped");
} else {
boardElement.classList.remove("flipped");
}
};
const handleMove = (source, target) => {
const move = {
from: `${String.fromCharCode(97 + source.col)}${8 - source.row}`,
to: `${String.fromCharCode(97 + target.col)}${8 - target.row}`,
promotion: "q"
};
socket.emit("move", move);
};
const getPieceUnicode = (piece) => {
const unicodePieces = {
p: "♙",
r: "♖",
n: "♘",
b: "♗",
q: "♕",
k: "♔",
P: "♟︎",
R: "♜",
N: "♞",
B: "♝",
Q: "♛",
K: "♚",
};
return unicodePieces[piece.type] || "";
};
socket.on("playerRole", function(role) {
playerRole = role;
renderBoard();
});
socket.on("spectatorRole", function() {
playerRole = null;
renderBoard();
});
socket.on("boardState", function(fen) {
chess.load(fen);
renderBoard();
});
socket.on("boardState", function(move) {
chess.move(move);
renderBoard();
});
renderBoard();