Creating a fully functional chess game with a sleek and modern UI using only a single HTML file (including embedded CSS and JavaScript) is a comprehensive task. Below is a simplified version that includes:
- A chessboard with pieces.
- Basic move validation (legal moves per piece type).
- Turn-based play for two local players.
- Simple animations for piece movement.
Note: This implementation covers the foundational aspects of a chess game. Advanced features like check/checkmate detection, castling, en passant, pawn promotion, and draw conditions are not included but can be added with further development.
You can copy the entire code below into a .html file and open it in your browser to play the game.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple Chess Game</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f0f0f0;
margin: 0;
font-family: Arial, sans-serif;
}
#chess-board {
display: grid;
grid-template-columns: repeat(8, 60px);
grid-template-rows: repeat(8, 60px);
border: 2px solid #333;
box-shadow: 0 0 10px rgba(0,0,0,0.5);
background-color: #333;
position: relative;
}
.square {
width: 60px;
height: 60px;
box-sizing: border-box;
position: relative;
}
.light {
background-color: #f0d9b5;
}
.dark {
background-color: #b58863;
}
.piece {
width: 100%;
height: 100%;
cursor: pointer;
user-select: none;
font-size: 48px;
text-align: center;
line-height: 60px;
transition: transform 0.2s;
}
.piece.selected {
transform: scale(1.2);
}
#status {
margin-top: 20px;
text-align: center;
font-size: 20px;
}
</style>
</head>
<body>
<div>
<div id="chess-board"></div>
<div id="status">White's turn</div>
</div>
<script>
const boardElement = document.getElementById('chess-board');
const statusElement = document.getElementById('status');
const pieceUnicode = {
'wP': '♙',
'wR': '♖',
'wN': '♘',
'wB': '♗',
'wQ': '♕',
'wK': '♔',
'bP': '♟︎',
'bR': '♜',
'bN': '♞',
'bB': '♝',
'bQ': '♛',
'bK': '♚',
};
let board = [];
let currentTurn = 'w';
let selectedPiece = null;
let selectedPos = null;
// Initialize the board
function initBoard() {
board = [
['bR','bN','bB','bQ','bK','bB','bN','bR'],
['bP','bP','bP','bP','bP','bP','bP','bP'],
[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],
['wP','wP','wP','wP','wP','wP','wP','wP'],
['wR','wN','wB','wQ','wK','wB','wN','wR']
];
renderBoard();
}
// Render the board
function renderBoard() {
boardElement.innerHTML = '';
for(let row=0; row<8; row++) {
for(let col=0; col<8; col++) {
const square = document.createElement('div');
square.classList.add('square');
if((row + col) % 2 === 0){
square.classList.add('light');
}
else{
square.classList.add('dark');
}
square.dataset.row = row;
square.dataset.col = col;
if(board[row][col]){
const piece = document.createElement('div');
piece.classList.add('piece');
piece.textContent = pieceUnicode[board[row][col]];
piece.dataset.piece = board[row][col];
piece.dataset.row = row;
piece.dataset.col = col;
piece.addEventListener('click', onPieceClick);
square.appendChild(piece);
}
boardElement.appendChild(square);
}
}
}
// Handle piece click
function onPieceClick(e) {
const piece = e.target;
const row = parseInt(piece.dataset.row);
const col = parseInt(piece.dataset.col);
const pieceColor = piece.dataset.piece.charAt(0);
if(pieceColor !== currentTurn){
return;
}
if(selectedPiece){
// Attempt to move
const moves = getLegalMoves(selectedPos.row, selectedPos.col);
if(moves.some(m => m.row === row && m.col === col)){
board[row][col] = board[selectedPos.row][selectedPos.col];
board[selectedPos.row][selectedPos.col] = null;
currentTurn = currentTurn === 'w' ? 'b' : 'w';
statusElement.textContent = (currentTurn === 'w' ? "White's turn" : "Black's turn");
}
selectedPiece.classList.remove('selected');
selectedPiece = null;
selectedPos = null;
renderBoard();
}
else{
selectedPiece = piece;
selectedPiece.classList.add('selected');
selectedPos = {row, col};
}
}
// Get legal moves for a piece at (row, col)
function getLegalMoves(row, col){
const piece = board[row][col];
if(!piece) return [];
const color = piece.charAt(0);
const type = piece.charAt(1);
let moves = [];
const directions = {
'P': color === 'w' ? -1 : 1,
'R': [[-1,0],[1,0],[0,-1],[0,1]],
'N': [[-2,-1],[-2,1],[-1,-2],[-1,2],[1,-2],[1,2],[2,-1],[2,1]],
'B': [[-1,-1],[-1,1],[1,-1],[1,1]],
'Q': [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1]],
'K': [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1]]
};
switch(type){
case 'P':
const forwardRow = row + directions['P'];
if(isInside(forwardRow, col) && !board[forwardRow][col]){
moves.push({row: forwardRow, col});
// Initial double move
if((color === 'w' && row ===6) || (color === 'b' && row ===1)){
const doubleForward = forwardRow + directions['P'];
if(!board[doubleForward][col]){
moves.push({row: doubleForward, col});
}
}
}
// Captures
for(let dc of [-1, 1]){
const captureCol = col + dc;
if(isInside(forwardRow, captureCol) && board[forwardRow][captureCol] && board[forwardRow][captureCol].charAt(0) !== color){
moves.push({row: forwardRow, col: captureCol});
}
}
break;
case 'R':
case 'B':
case 'Q':
const dirs = directions[type];
for(let dir of dirs){
let r = row + dir[0];
let c = col + dir[1];
while(isInside(r, c)){
if(board[r][c]){
if(board[r][c].charAt(0) !== color){
moves.push({row: r, col: c});
}
break;
}
moves.push({row: r, col: c});
if(type === 'K') break; // King moves only one square
r += dir[0];
c += dir[1];
}
}
break;
case 'N':
const knightMoves = directions['N'];
for(let m of knightMoves){
const r = row + m[0];
const c = col + m[1];
if(isInside(r, c)){
if(!board[r][c] || board[r][c].charAt(0) !== color){
moves.push({row: r, col: c});
}
}
}
break;
case 'K':
const kingMoves = directions['K'];
for(let m of kingMoves){
const r = row + m[0];
const c = col + m[1];
if(isInside(r, c)){
if(!board[r][c] || board[r][c].charAt(0) !== color){
moves.push({row: r, col: c});
}
}
}
break;
}
return moves;
}
function isInside(row, col){
return row >=0 && row <8 && col >=0 && col <8;
}
// Initialize the game
initBoard();
</script>
</body>
</html>
Explanation of the Code
-
HTML Structure:
- The
#chess-board div represents the chessboard.
- The
#status div displays the current player's turn.
-
CSS Styling:
- The chessboard is styled as an 8x8 grid with alternating light and dark squares.
- Pieces are represented using Unicode chess symbols and styled for better visibility.
- A simple animation enlarges the selected piece for visual feedback.
-
JavaScript Functionality:
- Board Representation: The
board array holds the current state of the game, initializing with the standard chess setup.
- Rendering:
renderBoard() creates the visual chessboard based on the board array.
- Piece Selection & Movement:
- Clicking on a piece selects it if it's the current player's turn.
- Clicking on a valid destination moves the piece, updates the board state, and switches turns.
- Move Validation: The
getLegalMoves() function calculates possible moves based on the piece type. It includes basic move rules for pawns, knights, bishops, rooks, queens, and kings.
- Utility Functions:
isInside() ensures move calculations stay within the board boundaries.
Potential Improvements
To make this chess game more robust and closer to a full-featured chess application, consider implementing:
- Check and Checkmate Detection: Identify when a king is under threat and determine game termination conditions.
- Castling: Allow kings and rooks to perform castling moves under standard rules.
- En Passant: Implement the en passant capture for pawns.
- Pawn Promotion: Enable pawns to promote to another piece upon reaching the far row.
- Move History: Keep track of all moves made during the game.
- Undo/Redo Functionality: Allow players to revert and reapply moves.
- Responsive Design: Make the UI adapt to different screen sizes and devices.
- AI Opponent: Incorporate a basic AI for single-player mode.
This foundational code provides a starting point for building a more comprehensive chess game. Enhancing it with the features mentioned above will result in a more complete and engaging user experience.