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
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
// Chess Game for Retro Arcade - with AI Opponent
class ChessGame {
    constructor(canvas, ctx) {
        this.canvas = canvas;
        this.ctx = ctx;
        this.boardSize = Math.min(canvas.width, canvas.height) - 40;
        this.squareSize = this.boardSize / 8;
        this.board = this.initializeBoard();
        this.selectedPiece = null;
        this.currentPlayer = 'white';
        this.gameOver = false;
        this.moveHistory = [];
        this.aiPlayer = 'black';
        this.aiThinking = false;
        this.validMoves = [];
    }

    initializeBoard() {
        const board = [];
        for (let row = 0; row < 8; row++) {
            board[row] = [];
            for (let col = 0; col < 8; col++) {
                board[row][col] = this.getInitialPiece(row, col);
            }
        }
        return board;
    }

    getInitialPiece(row, col) {
        if (row === 1) return { type: 'pawn', color: 'black' };
        if (row === 6) return { type: 'pawn', color: 'white' };
        
        if (row === 0 || row === 7) {
            const color = row === 0 ? 'black' : 'white';
            const pieces = ['rook', 'knight', 'bishop', 'queen', 'king', 'bishop', 'knight', 'rook'];
            return { type: pieces[col], color: color };
        }
        
        return null;
    }

    draw() {
        this.ctx.fillStyle = '#8B4513';
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
        
        // Draw board
        for (let row = 0; row < 8; row++) {
            for (let col = 0; col < 8; col++) {
                const x = col * this.squareSize + 20;
                const y = row * this.squareSize + 20;
                
                // Square color
                this.ctx.fillStyle = (row + col) % 2 === 0 ? '#D2B48C' : '#8B4513';
                this.ctx.fillRect(x, y, this.squareSize, this.squareSize);
                
                // Highlight valid moves
                if (this.validMoves.some(m => m.row === row && m.col === col)) {
                    this.ctx.fillStyle = 'rgba(0, 255, 0, 0.3)';
                    this.ctx.fillRect(x, y, this.squareSize, this.squareSize);
                }
                
                // Highlight selected piece
                if (this.selectedPiece && this.selectedPiece.row === row && this.selectedPiece.col === col) {
                    this.ctx.strokeStyle = '#FFD700';
                    this.ctx.lineWidth = 3;
                    this.ctx.strokeRect(x, y, this.squareSize, this.squareSize);
                }
                
                // Draw piece
                const piece = this.board[row][col];
                if (piece) {
                    this.drawPiece(piece, x, y);
                }
            }
        }
        
        // Draw game info
        this.ctx.fillStyle = '#FFF';
        this.ctx.font = '16px Arial';
        this.ctx.textAlign = 'left';
        let statusText = `Current: ${this.currentPlayer}`;
        if (this.aiThinking) statusText += ' (AI thinking...)';
        this.ctx.fillText(statusText, 20, this.canvas.height - 10);
        
        if (this.gameOver) {
            this.ctx.fillStyle = 'rgba(0,0,0,0.7)';
            this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
            this.ctx.fillStyle = '#FFD700';
            this.ctx.font = '30px Arial';
            this.ctx.textAlign = 'center';
            const winner = this.currentPlayer === 'white' ? 'Black' : 'White';
            this.ctx.fillText(`${winner} Wins!`, this.canvas.width/2, this.canvas.height/2 - 20);
            this.ctx.font = '16px Arial';
            this.ctx.fillText('Click Restart to play again', this.canvas.width/2, this.canvas.height/2 + 20);
        }
    }

    drawPiece(piece, x, y) {
        this.ctx.font = `${this.squareSize * 0.7}px Arial`;
        this.ctx.textAlign = 'center';
        this.ctx.textBaseline = 'middle';
        
        const pieces = {
            'king': '♔', 'queen': '♕', 'rook': '♖',
            'bishop': '♗', 'knight': '♘', 'pawn': '♙'
        };
        
        this.ctx.fillStyle = piece.color === 'white' ? '#FFF' : '#000';
        this.ctx.fillText(
            pieces[piece.type],
            x + this.squareSize/2,
            y + this.squareSize/2
        );
    }

    handleClick(x, y) {
        if (this.gameOver || this.aiThinking || this.currentPlayer === this.aiPlayer) return;
        
        const col = Math.floor((x - 20) / this.squareSize);
        const row = Math.floor((y - 20) / this.squareSize);
        
        if (col < 0 || col > 7 || row < 0 || row > 7) return;
        
        const piece = this.board[row][col];
        
        if (this.selectedPiece) {
            // Try to move
            if (this.isValidMove(this.selectedPiece, row, col)) {
                this.movePiece(this.selectedPiece, row, col);
                this.selectedPiece = null;
                this.validMoves = [];
                this.currentPlayer = this.aiPlayer;
                this.draw();
                
                // Trigger AI after a short delay
                setTimeout(() => this.makeAIMove(), 300);
            } else {
                this.selectedPiece = null;
                this.validMoves = [];
            }
        } else if (piece && piece.color === this.currentPlayer) {
            this.selectedPiece = { row, col, piece };
            this.validMoves = this.getValidMovesForPiece(row, col);
        }
    }

    getValidMovesForPiece(row, col) {
        const moves = [];
        const piece = this.board[row][col];
        if (!piece) return moves;
        
        for (let r = 0; r < 8; r++) {
            for (let c = 0; c < 8; c++) {
                if (this.isValidMove({row, col, piece}, r, c)) {
                    moves.push({row: r, col: c});
                }
            }
        }
        return moves;
    }

    isValidMove(from, toRow, toCol) {
        const piece = from.piece;
        const rowDiff = Math.abs(toRow - from.row);
        const colDiff = Math.abs(toCol - from.col);
        
        if (toRow < 0 || toRow > 7 || toCol < 0 || toCol > 7) return false;
        if (from.row === toRow && from.col === toCol) return false;
        
        const targetPiece = this.board[toRow][toCol];
        if (targetPiece && targetPiece.color === piece.color) return false;
        
        // Check path for sliding pieces
        if (['rook', 'bishop', 'queen'].includes(piece.type)) {
            if (!this.isPathClear(from.row, from.col, toRow, toCol)) return false;
        }
        
        switch(piece.type) {
            case 'pawn':
                const direction = piece.color === 'white' ? -1 : 1;
                if (colDiff === 0 && !targetPiece) {
                    if (toRow === from.row + direction) return true;
                    if ((from.row === 6 || from.row === 1) && toRow === from.row + 2 * direction) {
                        return this.isPathClear(from.row, from.col, toRow, toCol);
                    }
                }
                if (colDiff === 1 && toRow === from.row + direction && targetPiece) return true;
                return false;
                
            case 'rook':
                return (rowDiff === 0 || colDiff === 0);
                
            case 'bishop':
                return rowDiff === colDiff;
                
            case 'queen':
                return (rowDiff === 0 || colDiff === 0 || rowDiff === colDiff);
                
            case 'king':
                return rowDiff <= 1 && colDiff <= 1;
                
            case 'knight':
                return (rowDiff === 2 && colDiff === 1) || (rowDiff === 1 && colDiff === 2);
                
            default:
                return false;
        }
    }

    isPathClear(fromRow, fromCol, toRow, toCol) {
        const rowStep = Math.sign(toRow - fromRow);
        const colStep = Math.sign(toCol - fromCol);
        let r = fromRow + rowStep;
        let c = fromCol + colStep;
        
        while (r !== toRow || c !== toCol) {
            if (this.board[r][c] !== null) return false;
            r += rowStep;
            c += colStep;
        }
        return true;
    }

    movePiece(from, toRow, toCol) {
        this.board[toRow][toCol] = from.piece;
        this.board[from.row][from.col] = null;
        this.moveHistory.push({
            from: { row: from.row, col: from.col },
            to: { row: toRow, col: toCol },
            piece: from.piece
        });
        
        // Check for pawn promotion
        if (from.piece.type === 'pawn' && (toRow === 0 || toRow === 7)) {
            this.board[toRow][toCol] = { type: 'queen', color: from.piece.color };
        }
        
        // Check for king capture (win condition)
        if (this.isKingCaptured()) {
            this.gameOver = true;
        }
    }

    isKingCaptured() {
        let whiteKing = false;
        let blackKing = false;
        for (let r = 0; r < 8; r++) {
            for (let c = 0; c < 8; c++) {
                const p = this.board[r][c];
                if (p && p.type === 'king') {
                    if (p.color === 'white') whiteKing = true;
                    else blackKing = true;
                }
            }
        }
        return !whiteKing || !blackKing;
    }

    // ========== AI OPPONENT ==========
    makeAIMove() {
        if (this.gameOver) return;
        this.aiThinking = true;
        this.draw();
        
        // Use setTimeout to allow UI update before AI calculates
        setTimeout(() => {
            const move = this.findBestMove(3); // Depth 3 for balance
            if (move) {
                this.movePiece(move.from, move.to.row, move.to.col);
                this.currentPlayer = 'white';
                this.aiThinking = false;
                this.draw();
            } else {
                this.aiThinking = false;
                this.draw();
            }
        }, 100);
    }

    findBestMove(depth) {
        let bestMove = null;
        let bestValue = -Infinity;
        
        const moves = this.getAllPossibleMoves(this.aiPlayer);
        
        for (const move of moves) {
            // Make move
            const captured = this.board[move.to.row][move.to.col];
            const piece = this.board[move.from.row][move.from.col];
            this.board[move.to.row][move.to.col] = piece;
            this.board[move.from.row][move.from.col] = null;
            
            // Evaluate
            const value = this.minimax(depth - 1, -Infinity, Infinity, false);
            
            // Undo move
            this.board[move.from.row][move.from.col] = piece;
            this.board[move.to.row][move.to.col] = captured;
            
            if (value > bestValue) {
                bestValue = value;
                bestMove = move;
            }
        }
        
        return bestMove;
    }

    minimax(depth, alpha, beta, isMaximizing) {
        if (depth === 0 || this.isKingCaptured()) {
            return this.evaluateBoard();
        }
        
        const player = isMaximizing ? this.aiPlayer : 'white';
        const moves = this.getAllPossibleMoves(player);
        
        if (moves.length === 0) return isMaximizing ? -1000 : 1000;
        
        if (isMaximizing) {
            let maxEval = -Infinity;
            for (const move of moves) {
                const captured = this.board[move.to.row][move.to.col];
                const piece = this.board[move.from.row][move.from.col];
                this.board[move.to.row][move.to.col] = piece;
                this.board[move.from.row][move.from.col] = null;
                
                const eval_ = this.minimax(depth - 1, alpha, beta, false);
                
                this.board[move.from.row][move.from.col] = piece;
                this.board[move.to.row][move.to.col] = captured;
                
                maxEval = Math.max(maxEval, eval_);
                alpha = Math.max(alpha, eval_);
                if (beta <= alpha) break;
            }
            return maxEval;
        } else {
            let minEval = Infinity;
            for (const move of moves) {
                const captured = this.board[move.to.row][move.to.col];
                const piece = this.board[move.from.row][move.from.col];
                this.board[move.to.row][move.to.col] = piece;
                this.board[move.from.row][move.from.col] = null;
                
                const eval_ = this.minimax(depth - 1, alpha, beta, true);
                
                this.board[move.from.row][move.from.col] = piece;
                this.board[move.to.row][move.to.col] = captured;
                
                minEval = Math.min(minEval, eval_);
                beta = Math.min(beta, eval_);
                if (beta <= alpha) break;
            }
            return minEval;
        }
    }

    getAllPossibleMoves(color) {
        const moves = [];
        for (let r = 0; r < 8; r++) {
            for (let c = 0; c < 8; c++) {
                const piece = this.board[r][c];
                if (piece && piece.color === color) {
                    for (let tr = 0; tr < 8; tr++) {
                        for (let tc = 0; tc < 8; tc++) {
                            if (this.isValidMove({row: r, col: c, piece}, tr, tc)) {
                                moves.push({
                                    from: {row: r, col: c, piece},
                                    to: {row: tr, col: tc}
                                });
                            }
                        }
                    }
                }
            }
        }
        return moves;
    }

    evaluateBoard() {
        const pieceValues = {
            'pawn': 100,
            'knight': 320,
            'bishop': 330,
            'rook': 500,
            'queen': 900,
            'king': 20000
        };
        
        let score = 0;
        for (let r = 0; r < 8; r++) {
            for (let c = 0; c < 8; c++) {
                const piece = this.board[r][c];
                if (piece) {
                    const value = pieceValues[piece.type] || 0;
                    if (piece.color === this.aiPlayer) {
                        score += value;
                        // Bonus for advanced pawns
                        if (piece.type === 'pawn') {
                            score += (piece.color === 'black' ? r : (7 - r)) * 10;
                        }
                    } else {
                        score -= value;
                    }
                }
            }
        }
        return score;
    }
}

// Export for use in main games.js
if (typeof module !== 'undefined' && module.exports) {
    module.exports = ChessGame;
}