-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchess.html
510 lines (452 loc) · 28.1 KB
/
chess.html
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
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML Chess Game (Dynamic Buttons)</title>
<style>
body {
font-family: sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
background-color: #f0f0f0;
}
#game-area {
display: flex;
flex-direction: column;
align-items: center;
}
#board-container {
display: grid;
grid-template-areas:
". top ."
"left board right"
". bottom .";
grid-template-columns: auto 1fr auto; /* auto for labels, 1fr for board */
grid-template-rows: auto 1fr auto;
gap: 5px; /* Small gap between labels and board */
}
.labels {
display: flex;
justify-content: center;
align-items: center;
font-weight: bold;
color: #555;
}
.labels.files { flex-direction: row; }
.labels.ranks { flex-direction: column; }
.label {
width: 60px; /* Match square size */
height: 60px;
display: flex;
justify-content: center;
align-items: center;
}
#top-files { grid-area: top; }
#bottom-files { grid-area: bottom; }
#left-ranks { grid-area: left; }
#right-ranks { grid-area: right; }
#chessboard {
grid-area: board;
width: 480px; /* 8 squares * 60px */
height: 480px;
display: grid;
grid-template-columns: repeat(8, 1fr);
grid-template-rows: repeat(8, 1fr);
border: 5px solid #333;
box-shadow: 0 0 10px rgba(0,0,0,0.5);
}
/* Common styles for both buttons and divs */
.square-base {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
/* Make the actual text (notation) visually hidden but accessible */
font-size: 1px; /* Hide text */
color: transparent; /* Hide text */
box-sizing: border-box;
position: relative; /* For pseudo-elements */
border: none; /* Remove default button border */
padding: 0;
margin: 0;
}
/* Use ::before to display the piece symbol */
/* Target only squares that have a piece */
.square-base.has-piece::before {
content: attr(data-piece-symbol); /* Get symbol from data attribute */
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 40px; /* Restore original piece size */
color: inherit; /* Inherit color from .white/.black class */
text-shadow: inherit; /* Inherit shadow from .white/.black class */
pointer-events: none; /* Don't interfere with clicks */
}
.square-base.light { background-color: #f0d9b5; }
.square-base.dark { background-color: #b58863; }
/* Piece Colors (apply to both) */
.square-base.white { color: #ffffff; text-shadow: 1px 1px 2px #000000; }
.square-base.black { color: #000000; text-shadow: 1px 1px 2px #aaaaaa;}
/* Button-specific styles */
.square-button {
cursor: pointer;
transition: background-color 0.1s ease-in-out, box-shadow 0.1s ease-in-out;
}
.square-button:hover {
/* Subtle hover for buttons */
filter: brightness(1.1);
}
/* --- Interaction State Classes (applied only to buttons) --- */
.square-button.selected {
box-shadow: inset 0 0 0 4px rgba(0, 150, 0, 0.7);
}
.square-button.valid-move::after {
content: '';
position: absolute;
width: 25%;
height: 25%;
background-color: rgba(0, 0, 0, 0.25);
border-radius: 50%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
pointer-events: none;
}
.square-button.capture-move {
border: 4px dashed rgba(200, 0, 0, 0.6);
/* Adjust padding so border doesn't shrink content area */
/* padding: 4px; */ /* This might shift content, box-sizing should handle it */
}
.square-button.capture-move.selected {
box-shadow: inset 0 0 0 4px rgba(0, 150, 0, 0.7), 0 0 0 4px rgba(200, 0, 0, 0.6);
border: none;
}
/* Div-specific styles (if any needed beyond .square-base) */
.square-div {
cursor: default;
}
#status {
margin-top: 20px;
font-size: 1.2em;
font-weight: bold;
min-height: 1.5em;
color: #333;
}
#resetButton {
margin-top: 15px;
padding: 10px 20px;
font-size: 1em;
cursor: pointer;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
}
#resetButton:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<div id="game-area">
<div id="status">White's turn</div>
<div id="board-container">
<div id="top-files" class="labels files"></div>
<div id="left-ranks" class="labels ranks"></div>
<div id="chessboard"></div>
<div id="right-ranks" class="labels ranks"></div>
<div id="bottom-files" class="labels files"></div>
</div>
<button id="resetButton">Reset Game</button>
</div>
<script>
const chessboardElement = document.getElementById('chessboard');
const statusElement = document.getElementById('status');
const resetButton = document.getElementById('resetButton');
const topFilesLabel = document.getElementById('top-files');
const bottomFilesLabel = document.getElementById('bottom-files');
const leftRanksLabel = document.getElementById('left-ranks');
const rightRanksLabel = document.getElementById('right-ranks');
// --- Game State ---
let board = [];
let currentPlayer = 'white';
let selectedPiece = null; // { element: null (not needed now), piece, row, col }
let validMoves = []; // Array of { row, col } for the selected piece
let initialClickablePieces = []; // Array of {row, col} for pieces clickable at turn start
let gameOver = false;
let checkStatus = { white: false, black: false };
let castlingRights = {
white: { kingSide: true, queenSide: true },
black: { kingSide: true, queenSide: true }
};
let enPassantTarget = null;
// --- Piece Representation --- (Same as before)
const PIECES = { 'P': { type: 'pawn', color: 'white', unicode: '♙' }, 'R': { type: 'rook', color: 'white', unicode: '♖' }, 'N': { type: 'knight', color: 'white', unicode: '♘' }, 'B': { type: 'bishop', color: 'white', unicode: '♗' }, 'Q': { type: 'queen', color: 'white', unicode: '♕' }, 'K': { type: 'king', color: 'white', unicode: '♔' }, 'p': { type: 'pawn', color: 'black', unicode: '♟' }, 'r': { type: 'rook', color: 'black', unicode: '♜' }, 'n': { type: 'knight', color: 'black', unicode: '♞' }, 'b': { type: 'bishop', color: 'black', unicode: '♝' }, 'q': { type: 'queen', color: 'black', unicode: '♛' }, 'k': { type: 'king', color: 'black', unicode: '♚' } };
const initialBoardSetup = [ ['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'], ['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'], [null, null, null, null, null, null, null, null], [null, null, null, null, null, null, null, null], [null, null, null, null, null, null, null, null], [null, null, null, null, null, null, null, null], ['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'], ['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'] ];
// --- Initialization ---
function initGame() {
board = initialBoardSetup.map(row => row.map(p => p ? { ...PIECES[p] } : null));
currentPlayer = 'white';
selectedPiece = null;
validMoves = [];
initialClickablePieces = [];
gameOver = false;
checkStatus = { white: false, black: false };
castlingRights = { white: { kingSide: true, queenSide: true }, black: { kingSide: true, queenSide: true } };
enPassantTarget = null;
createLabels();
prepareTurn(); // Calculate initial state and render
}
function createLabels() { // (Same as before)
const files = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];
const ranks = ['8', '7', '6', '5', '4', '3', '2', '1'];
topFilesLabel.innerHTML = ''; bottomFilesLabel.innerHTML = ''; leftRanksLabel.innerHTML = ''; rightRanksLabel.innerHTML = '';
files.forEach(file => { const tl = document.createElement('div'); tl.classList.add('label'); tl.textContent = file; topFilesLabel.appendChild(tl); const bl = document.createElement('div'); bl.classList.add('label'); bl.textContent = file; bottomFilesLabel.appendChild(bl); });
ranks.forEach(rank => { const ll = document.createElement('div'); ll.classList.add('label'); ll.textContent = rank; leftRanksLabel.appendChild(ll); const rl = document.createElement('div'); rl.classList.add('label'); rl.textContent = rank; rightRanksLabel.appendChild(rl); });
}
// --- Core Turn Preparation ---
function prepareTurn() {
selectedPiece = null; // Ensure no piece is selected at turn start
validMoves = [];
updateCheckStatus(); // Check if current player is in check
initialClickablePieces = findClickablePieces(); // Find which pieces can move
checkGameEnd(); // Check for mate/stalemate based on available moves
updateStatusDisplay();
renderBoard(); // Render based on the new state
}
// --- Rendering (Major Change) ---
function renderBoard() {
chessboardElement.innerHTML = ''; // Clear previous state
for (let r = 0; r < 8; r++) {
for (let c = 0; c < 8; c++) {
const piece = board[r][c];
let element; // Will be button or div
let isClickable = false;
let isSelected = false;
let isValidTarget = false;
let isCaptureTarget = false;
// Determine if this square should be clickable
if (!gameOver) {
if (selectedPiece) {
// State: Piece is selected
if (r === selectedPiece.row && c === selectedPiece.col) {
isClickable = true; // Allow deselecting
isSelected = true;
} else {
isValidTarget = validMoves.some(move => move.row === r && move.col === c);
if (isValidTarget) {
isClickable = true;
isCaptureTarget = piece !== null || // Regular capture
(selectedPiece.piece.type === 'pawn' && c !== selectedPiece.col && piece === null && enPassantTarget && r === enPassantTarget.row && c === enPassantTarget.col); // En passant target
}
}
} else {
// State: No piece selected - check initial clickable pieces
isClickable = initialClickablePieces.some(p => p.row === r && p.col === c);
}
} // else game is over, nothing is clickable
// Create the element (button or div)
element = document.createElement(isClickable ? 'button' : 'div');
element.classList.add('square-base'); // Common styles
element.classList.add(isClickable ? 'square-button' : 'square-div'); // Type-specific styles/cursor
// Add standard classes
element.classList.add((r + c) % 2 === 0 ? 'light' : 'dark');
element.dataset.row = r;
element.dataset.col = c;
// Add chess notation (a1, b2, etc.) as visually hidden text
const file = String.fromCharCode(97 + c);
const rank = 8 - r;
const notation = file + rank;
element.textContent = notation;
// Add piece content and color class using pseudo-element
if (piece) {
// Set data attribute for the ::before pseudo-element
element.dataset.pieceSymbol = piece.unicode;
element.classList.add(piece.color); // Add 'white' or 'black' class
element.classList.add('has-piece'); // Marker class for CSS selector
} // No else needed, textContent is already set to notation
// Add interaction classes (only if it's a button)
if (isClickable) {
if (isSelected) {
element.classList.add('selected');
} else if (isValidTarget) {
element.classList.add(isCaptureTarget ? 'capture-move' : 'valid-move');
}
}
chessboardElement.appendChild(element);
}
}
// Ensure event listener is attached (delegation handles dynamic elements)
chessboardElement.removeEventListener('click', handleSquareClick);
if (!gameOver) {
chessboardElement.addEventListener('click', handleSquareClick);
}
}
// --- Event Handling (Adapted) ---
function handleSquareClick(event) {
// Listener is on the chessboard, target might be button or div, but we only care about buttons
const targetButton = event.target.closest('.square-button');
if (!targetButton) return; // Clicked on a non-interactive div or gap
const row = parseInt(targetButton.dataset.row);
const col = parseInt(targetButton.dataset.col);
if (selectedPiece) {
// State: Piece is selected, clicked a button
if (row === selectedPiece.row && col === selectedPiece.col) {
// Clicked the selected piece itself: Deselect
selectedPiece = null;
validMoves = [];
renderBoard(); // Re-render to show initial clickable pieces
} else {
// Clicked a valid move target button
makeMove(selectedPiece.row, selectedPiece.col, row, col);
// Move made, switch player and prepare their turn
switchPlayer();
prepareTurn(); // This recalculates everything and re-renders
}
} else {
// State: No piece selected, clicked an initial clickable piece button
const clickedPieceData = board[row][col]; // Should always exist here
selectPiece(clickedPieceData, row, col); // Select the piece
renderBoard(); // Re-render to show selected piece and its moves
}
}
function selectPiece(pieceData, row, col) {
selectedPiece = { piece: pieceData, row, col }; // No element needed now
// Calculate valid moves *for rendering* (already filtered for check during initial calculation)
const potentialMoves = calculateValidMoves(pieceData, row, col);
validMoves = potentialMoves.filter(move => {
const tempBoard = simulateMove(row, col, move.row, move.col);
return !isKingInCheck(currentPlayer, tempBoard);
});
// No highlighting function needed, renderBoard handles it
}
// --- Move Logic --- (Largely the same, but calls prepareTurn at the end)
function makeMove(fromRow, fromCol, toRow, toCol) {
const pieceToMove = board[fromRow][fromCol];
const capturedPiece = board[toRow][toCol];
let specialMove = null;
// En Passant Capture
if (pieceToMove.type === 'pawn' && enPassantTarget && toRow === enPassantTarget.row && toCol === enPassantTarget.col) {
const capturedPawnRow = currentPlayer === 'white' ? toRow + 1 : toRow - 1;
board[capturedPawnRow][toCol] = null;
specialMove = 'enpassant';
}
// Castling
if (pieceToMove.type === 'king' && Math.abs(toCol - fromCol) === 2) {
specialMove = 'castling';
const rookCol = toCol > fromCol ? 7 : 0;
const rookTargetCol = toCol > fromCol ? 5 : 3;
const rook = board[fromRow][rookCol];
board[fromRow][rookTargetCol] = rook;
board[fromRow][rookCol] = null;
}
// Update Board State
board[toRow][toCol] = pieceToMove;
board[fromRow][fromCol] = null;
// Update Game State (En Passant Target for *next* turn)
let nextEnPassantTarget = null;
if (pieceToMove.type === 'pawn' && Math.abs(toRow - fromRow) === 2) {
nextEnPassantTarget = { row: (fromRow + toRow) / 2, col: fromCol };
}
enPassantTarget = nextEnPassantTarget;
// Update Castling Rights (Same logic as before)
if (pieceToMove.type === 'king') { castlingRights[pieceToMove.color].kingSide = false; castlingRights[pieceToMove.color].queenSide = false; }
else if (pieceToMove.type === 'rook') { if (fromRow === (pieceToMove.color === 'white' ? 7 : 0)) { if (fromCol === 0) castlingRights[pieceToMove.color].queenSide = false; if (fromCol === 7) castlingRights[pieceToMove.color].kingSide = false; } }
if (capturedPiece && capturedPiece.type === 'rook') { const capColor = capturedPiece.color; if (toRow === (capColor === 'white' ? 7 : 0)) { if (toCol === 0) castlingRights[capColor].queenSide = false; if (toCol === 7) castlingRights[capColor].kingSide = false; } }
// Pawn Promotion (Auto-Queen)
if (pieceToMove.type === 'pawn' && (toRow === 0 || toRow === 7)) {
const promotedPieceKey = pieceToMove.color === 'white' ? 'Q' : 'q';
board[toRow][toCol] = { ...PIECES[promotedPieceKey] };
specialMove = 'promotion';
}
// NOTE: No renderBoard() here. It's called in prepareTurn after switching player.
}
function switchPlayer() {
currentPlayer = (currentPlayer === 'white') ? 'black' : 'white';
}
function updateStatusDisplay() { // (Same as before)
if (gameOver) { statusElement.textContent = gameOver; statusElement.style.color = 'red'; }
else { let statusText = `${currentPlayer.charAt(0).toUpperCase() + currentPlayer.slice(1)}'s turn`; if (checkStatus[currentPlayer]) { statusText += " (Check!)"; statusElement.style.color = 'orange'; } else { statusElement.style.color = '#333'; } statusElement.textContent = statusText; }
}
// --- Rule Calculations --- (Helper functions remain the same)
// NEW Helper: Find pieces that have at least one legal move
function findClickablePieces() {
const clickable = [];
for (let r = 0; r < 8; r++) {
for (let c = 0; c < 8; c++) {
const piece = board[r][c];
if (piece && piece.color === currentPlayer) {
if (hasAnyValidMovesForPiece(piece, r, c)) {
clickable.push({ row: r, col: c });
}
}
}
}
return clickable;
}
// NEW Helper: Check if a specific piece has any legal moves
function hasAnyValidMovesForPiece(piece, row, col) {
const moves = calculateValidMoves(piece, row, col);
const legalMoves = moves.filter(move => {
const tempBoard = simulateMove(row, col, move.row, move.col);
return !isKingInCheck(currentPlayer, tempBoard); // Check against the current player's king
});
return legalMoves.length > 0;
}
// --- Existing Rule Calculation Functions (Unchanged) ---
// calculateValidMoves, isValidSquare, findKing, isSquareAttacked,
// calculateRawAttacks, isKingInCheck, simulateMove
function calculateValidMoves(piece, row, col) { // (Identical to previous version)
const moves = [];
const color = piece.color;
const opponentColor = (color === 'white') ? 'black' : 'white';
const addMove = (r, c) => { if (isValidSquare(r, c)) { const targetPiece = board[r][c]; if (targetPiece === null) { moves.push({ row: r, col: c }); return true; } else if (targetPiece.color === opponentColor) { moves.push({ row: r, col: c }); return false; } else { return false; } } return false; };
const addPawnMove = (r, c) => { if (isValidSquare(r, c) && board[r][c] === null) { moves.push({ row: r, col: c }); return true; } return false; };
const addPawnCapture = (r, c) => { if (isValidSquare(r, c)) { const targetPiece = board[r][c]; if (targetPiece && targetPiece.color === opponentColor) { moves.push({ row: r, col: c }); } else if (enPassantTarget && r === enPassantTarget.row && c === enPassantTarget.col && board[r][c] === null) { moves.push({ row: r, col: c }); } } };
switch (piece.type) {
case 'pawn': const dir = color === 'white' ? -1 : 1; const startRow = color === 'white' ? 6 : 1; if (addPawnMove(row + dir, col)) { if (row === startRow) { addPawnMove(row + 2 * dir, col); } } addPawnCapture(row + dir, col - 1); addPawnCapture(row + dir, col + 1); break;
case 'rook': case 'bishop': case 'queen': const dirs = { 'rook': [[-1, 0], [1, 0], [0, -1], [0, 1]], 'bishop': [[-1, -1], [-1, 1], [1, -1], [1, 1]], 'queen': [[-1, 0], [1, 0], [0, -1], [0, 1], [-1, -1], [-1, 1], [1, -1], [1, 1]] }[piece.type]; dirs.forEach(([dr, dc]) => { let r = row + dr; let c = col + dc; while (addMove(r, c)) { r += dr; c += dc; } }); break;
case 'knight': const knightMoves = [[-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]]; knightMoves.forEach(([dr, dc]) => { addMove(row + dr, col + dc); }); break;
case 'king': const kingMoves = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]; kingMoves.forEach(([dr, dc]) => { addMove(row + dr, col + dc); }); if (!isKingInCheck(color, board)) { if (castlingRights[color].kingSide && board[row][col + 1] === null && board[row][col + 2] === null && board[row][col + 3]?.type === 'rook') { if (!isSquareAttacked(row, col + 1, opponentColor, board) && !isSquareAttacked(row, col + 2, opponentColor, board)) { moves.push({ row: row, col: col + 2 }); } } if (castlingRights[color].queenSide && board[row][col - 1] === null && board[row][col - 2] === null && board[row][col - 3] === null && board[row][col - 4]?.type === 'rook') { if (!isSquareAttacked(row, col - 1, opponentColor, board) && !isSquareAttacked(row, col - 2, opponentColor, board)) { moves.push({ row: row, col: col - 2 }); } } } break;
} return moves;
}
function isValidSquare(row, col) { return row >= 0 && row < 8 && col >= 0 && col < 8; }
function findKing(color, currentBoard) { for (let r = 0; r < 8; r++) { for (let c = 0; c < 8; c++) { const piece = currentBoard[r][c]; if (piece && piece.type === 'king' && piece.color === color) { return { row: r, col: c }; } } } return null; }
function isSquareAttacked(targetRow, targetCol, attackerColor, currentBoard) { for (let r = 0; r < 8; r++) { for (let c = 0; c < 8; c++) { const piece = currentBoard[r][c]; if (piece && piece.color === attackerColor) { const rawMoves = calculateRawAttacks(piece, r, c, currentBoard); if (rawMoves.some(move => move.row === targetRow && move.col === targetCol)) { return true; } } } } return false; }
function calculateRawAttacks(piece, row, col, currentBoard) { const moves = []; const color = piece.color; const addAttack = (r, c) => { if (isValidSquare(r, c)) { moves.push({ row: r, col: c }); return currentBoard[r][c] === null; } return false; }; const addPawnAttack = (r, c) => { if (isValidSquare(r, c)) { moves.push({ row: r, col: c }); } }; switch (piece.type) { case 'pawn': const dir = color === 'white' ? -1 : 1; addPawnAttack(row + dir, col - 1); addPawnAttack(row + dir, col + 1); break; case 'rook': case 'bishop': case 'queen': const dirs = { 'rook': [[-1, 0], [1, 0], [0, -1], [0, 1]], 'bishop': [[-1, -1], [-1, 1], [1, -1], [1, 1]], 'queen': [[-1, 0], [1, 0], [0, -1], [0, 1], [-1, -1], [-1, 1], [1, -1], [1, 1]] }[piece.type]; dirs.forEach(([dr, dc]) => { let r = row + dr; let c = col + dc; if (isValidSquare(r,c)) moves.push({row: r, col: c}); while (currentBoard[r]?.[c] === null && isValidSquare(r + dr, c + dc)) { r += dr; c += dc; moves.push({ row: r, col: c }); } }); break; case 'knight': const knightMoves = [[-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]]; knightMoves.forEach(([dr, dc]) => addAttack(row + dr, col + dc)); break; case 'king': const kingMoves = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]; kingMoves.forEach(([dr, dc]) => addAttack(row + dr, col + dc)); break; } return moves; }
function isKingInCheck(kingColor, currentBoard) { const kingPos = findKing(kingColor, currentBoard); if (!kingPos) return false; const opponentColor = (kingColor === 'white') ? 'black' : 'white'; return isSquareAttacked(kingPos.row, kingPos.col, opponentColor, currentBoard); }
function simulateMove(fromRow, fromCol, toRow, toCol) { const tempBoard = board.map(row => row.map(p => p ? { ...p } : null)); const piece = tempBoard[fromRow][fromCol]; if (piece) { if (piece.type === 'pawn' && enPassantTarget && toRow === enPassantTarget.row && toCol === enPassantTarget.col) { const capPawnRow = piece.color === 'white' ? toRow + 1 : toRow - 1; tempBoard[capPawnRow][toCol] = null; } tempBoard[toRow][toCol] = piece; tempBoard[fromRow][fromCol] = null; if (piece.type === 'king' && Math.abs(toCol - fromCol) === 2) { const rookCol = toCol > fromCol ? 7 : 0; const rookTargetCol = toCol > fromCol ? 5 : 3; if (tempBoard[fromRow][rookCol]) { tempBoard[fromRow][rookTargetCol] = tempBoard[fromRow][rookCol]; tempBoard[fromRow][rookCol] = null; } } } return tempBoard; }
// --- End Existing Rule Calculation Functions ---
function updateCheckStatus() { // (Same as before)
checkStatus.white = isKingInCheck('white', board);
checkStatus.black = isKingInCheck('black', board);
}
function checkGameEnd() { // (Modified slightly to use initialClickablePieces)
// Game ends if the current player has no legal moves.
// We already calculated this when finding initialClickablePieces.
if (initialClickablePieces.length === 0) {
if (checkStatus[currentPlayer]) {
gameOver = `Checkmate! ${currentPlayer === 'white' ? 'Black' : 'White'} wins.`;
} else {
gameOver = "Stalemate! It's a draw.";
}
// If game over, remove the event listener after the final render
chessboardElement.removeEventListener('click', handleSquareClick);
return true;
}
gameOver = false;
return false;
}
// --- Reset ---
resetButton.addEventListener('click', initGame);
// --- Start Game ---
initGame();
</script>
</body>
</html>