File size: 9,503 Bytes
3447886
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
// Chess game initialization
const chess = new Chess();
const boardElement = document.getElementById('chessboard');
const fenDisplay = document.getElementById('fen-display');
const moveHistory = document.getElementById('move-history');
const currentTurn = document.getElementById('current-turn');
const moveCount = document.getElementById('move-count');
const newGameBtn = document.getElementById('new-game');
const flipBoardBtn = document.getElementById('flip-board');
const aiMoveBtn = document.getElementById('ai-move');
const toggleAiBtn = document.getElementById('toggle-ai');
const aiLevelSelect = document.getElementById('ai-level');
const undoMoveBtn = document.getElementById('undo-move');
const gameStatus = document.getElementById('game-status');
const whiteScore = document.getElementById('white-score');
const blackScore = document.getElementById('black-score');
// Stockfish AI
const stockfish = new Worker('https://cdnjs.cloudflare.com/ajax/libs/stockfish.js/10.0.2/stockfish.js');
let isPlayerTurn = true;
let isAiGame = false;
let aiLevel = 2;
// Initialize the board
function initializeBoard() {
    boardElement.innerHTML = '';
    let isWhite = true;
    
    for (let i = 0; i < 8; i++) {
        for (let j = 0; j < 8; j++) {
            const square = document.createElement('div');
            square.className = `square ${isWhite ? 'white-square' : 'black-square'}`;
            square.dataset.row = i;
            square.dataset.col = j;
            square.addEventListener('click', () => handleSquareClick(i, j));
            boardElement.appendChild(square);
            isWhite = !isWhite;
        }
        isWhite = !isWhite;
    }
    
    updateBoard();
    updateScores();
}
// Update the board with current pieces
function updateBoard() {
    const squares = boardElement.querySelectorAll('.square');
    squares.forEach(square => {
        square.innerHTML = '';
        square.classList.remove('highlight', 'selected', 'possible-move', 'check');
    });

    // Highlight king in check
    if (chess.in_check()) {
        const kingPos = chess.board().flat().find(p => p && p.type === 'k' && p.color === chess.turn());
        if (kingPos) {
            const square = document.querySelector(`.square[data-row="${kingPos.square[1] - 1}"][data-col="${kingPos.square.charCodeAt(0) - 97}"]`);
            square.classList.add('check');
        }
    }

    // Place pieces on board
    for (let i = 0; i < 8; i++) {
        for (let j = 0; j < 8; j++) {
            const piece = chess.get(String.fromCharCode(97 + j) + (8 - i));
            if (piece) {
                const square = document.querySelector(`.square[data-row="${i}"][data-col="${j}"]`);
                const pieceElement = document.createElement('div');
                pieceElement.className = 'piece';
                pieceElement.textContent = getPieceSymbol(piece);
                square.appendChild(pieceElement);
            }
        }
    }

    // Update game info
    fenDisplay.textContent = chess.fen();
    currentTurn.textContent = chess.turn() === 'w' ? 'White' : 'Black';
    moveCount.textContent = chess.history().length;
}

// Get Unicode chess piece symbols
function getPieceSymbol(piece) {
    const symbols = {
        'p': 'β™Ÿ', 'n': 'β™ž', 'b': '♝', 'r': 'β™œ', 'q': 'β™›', 'k': 'β™š',
        'P': 'β™™', 'N': 'β™˜', 'B': 'β™—', 'R': 'β™–', 'Q': 'β™•', 'K': 'β™”'
    };
    return symbols[piece.type] || '';
}

// Handle square clicks
let selectedSquare = null;
let possibleMoves = [];
function showPieceMovement(piece, fromSquare) {
    clearSelection();
    const moves = chess.moves({
        square: fromSquare,
        verbose: true
    });
    
    // Highlight the selected piece
    const [file, rank] = fromSquare.split('');
    const col = file.charCodeAt(0) - 97;
    const row = 8 - parseInt(rank);
    const square = document.querySelector(`.square[data-row="${row}"][data-col="${col}"]`);
    square.classList.add('selected');
    
    // Highlight possible moves
    moves.forEach(move => {
        const toRow = 8 - parseInt(move.to[1]);
        const toCol = move.to.charCodeAt(0) - 97;
        const square = document.querySelector(`.square[data-row="${toRow}"][data-col="${toCol}"]`);
        square.classList.add('possible-move');
    });
}

function handleSquareClick(row, col) {
    if (!isPlayerTurn) return;
    
    const squareNotation = String.fromCharCode(97 + col) + (8 - row);
const clickedSquare = document.querySelector(`.square[data-row="${row}"][data-col="${col}"]`);
    
    // If a piece is selected and user clicks on a possible move
    if (selectedSquare && possibleMoves.some(move => move.to === squareNotation)) {
        const move = possibleMoves.find(move => move.to === squareNotation);
        makeMove(move);
        return;
    }
    
    // Clear previous selection
    clearSelection();
    
    // Select new piece if it's the current player's turn
    const piece = chess.get(squareNotation);
    if (piece && piece.color === chess.turn()) {
        selectedSquare = { row, col, notation: squareNotation };
        clickedSquare.classList.add('selected');
        
        // Highlight possible moves
        possibleMoves = chess.moves({
            square: squareNotation,
            verbose: true
        });
        
        possibleMoves.forEach(move => {
            const toRow = 8 - parseInt(move.to[1]);
            const toCol = move.to.charCodeAt(0) - 97;
            const square = document.querySelector(`.square[data-row="${toRow}"][data-col="${toCol}"]`);
            square.classList.add('possible-move');
        });
    }
}

function clearSelection() {
    document.querySelectorAll('.square').forEach(sq => {
        sq.classList.remove('selected', 'possible-move');
    });
    selectedSquare = null;
    possibleMoves = [];
}
// Make a move
function makeMove(move) {
    chess.move(move);
    updateBoard();
    addToMoveHistory(move);
    clearSelection();
    updateGameStatus();
    
    if (isAiGame && chess.turn() === 'b') {
        isPlayerTurn = false;
        getAiMove();
    }
}
// Add move to history
function addToMoveHistory(move) {
    const moveElement = document.createElement('div');
    moveElement.className = 'flex justify-between py-1 px-2 hover:bg-gray-600 rounded';
    moveElement.textContent = `${move.piece.toUpperCase()} ${move.from} β†’ ${move.to}`;
    moveHistory.appendChild(moveElement);
    moveHistory.scrollTop = moveHistory.scrollHeight;
}

// AI move using Stockfish
function getAiMove() {
    stockfish.postMessage(`uci`);
    stockfish.postMessage(`position fen ${chess.fen()}`);
    stockfish.postMessage(`go depth ${aiLevel}`);
    
    stockfish.onmessage = (event) => {
        if (event.data.startsWith('bestmove')) {
            const moveStr = event.data.split(' ')[1];
            const move = {
                from: moveStr.substring(0, 2),
                to: moveStr.substring(2, 4),
                promotion: moveStr.length > 4 ? moveStr.substring(4, 5) : undefined
            };
            
            setTimeout(() => {
                makeMove(move);
                isPlayerTurn = true;
            }, 500);
        }
    };
}

// Event listeners
newGameBtn.addEventListener('click', () => {
    chess.reset();
    updateBoard();
    moveHistory.innerHTML = '';
    if (isAiGame && chess.turn() === 'b') {
        isPlayerTurn = false;
        getAiMove();
    } else {
        isPlayerTurn = true;
    }
});

flipBoardBtn.addEventListener('click', () => {
    boardElement.classList.toggle('flipped');
});

aiMoveBtn.addEventListener('click', () => {
    if (!isAiGame && chess.turn() === 'b') {
        getAiMove();
    }
});
toggleAiBtn.addEventListener('click', () => {
    isAiGame = !isAiGame;
    toggleAiBtn.textContent = isAiGame ? 'Playing vs AI' : 'Play vs AI';
    toggleAiBtn.classList.toggle('bg-purple-600', !isAiGame);
    toggleAiBtn.classList.toggle('bg-purple-800', isAiGame);
});

undoMoveBtn.addEventListener('click', () => {
    if (chess.history().length > 0) {
        chess.undo();
        updateBoard();
        moveHistory.innerHTML = '';
        chess.history().forEach(move => {
            addToMoveHistory(move);
        });
        isPlayerTurn = chess.turn() === 'w';
        updateGameStatus();
    }
});
aiLevelSelect.addEventListener('change', (e) => {
    aiLevel = parseInt(e.target.value);
});
// Update game status and scores
function updateGameStatus() {
    if (chess.in_checkmate()) {
        gameStatus.textContent = `Checkmate! ${chess.turn() === 'w' ? 'Black' : 'White'} wins!`;
        gameStatus.className = 'text-sm font-medium text-red-400';
        updateScores();
    } else if (chess.in_stalemate()) {
        gameStatus.textContent = 'Stalemate! Game is a draw.';
        gameStatus.className = 'text-sm font-medium text-yellow-400';
    } else if (chess.in_check()) {
        gameStatus.textContent = `${chess.turn() === 'w' ? 'White' : 'Black'} is in check!';
        gameStatus.className = 'text-sm font-medium text-orange-400';
    } else {
        gameStatus.textContent = 'Game in Progress';
        gameStatus.className = 'text-sm font-medium text-green-400';
    }
}

function updateScores() {
    if (chess.in_checkmate()) {
        if (chess.turn() === 'w') {
            whiteScore.textContent = parseInt(whiteScore.textContent) + 1;
    } else {
        blackScore.textContent = parseInt(blackScore.textContent) + 1;
    }
}

// Initialize the game
initializeBoard();