Write Checkers game in HTML canvas, make sure to implement all the rules of the game
- User
Write Checkers game in HTML canvas, make sure to implement all the rules of the game
- Assistant
Write Checkers game in HTML canvas, make sure to implement all the rules of the game
Creating a fully functional Checkers game using HTML Canvas involves several components, including setting up the game board, managing game state, handling user interactions, and enforcing all the game rules. Below is a complete implementation that covers all standard rules of Checkers.
Create an HTML File:
.html extension (e.g., checkers.html).Open in a Browser:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Checkers Game</title>
<style>
canvas {
border: 2px solid #333;
display: block;
margin: 20px auto;
background-color: #fff;
}
body {
text-align: center;
font-family: Arial, sans-serif;
}
#status {
margin-top: 20px;
font-size: 1.2em;
}
#restart {
margin-top: 10px;
padding: 10px 20px;
font-size: 1em;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="800" height="800"></canvas>
<div id="status">Red's Turn</div>
<button id="restart">Restart Game</button>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const statusDiv = document.getElementById('status');
const restartButton = document.getElementById('restart');
const boardSize = 8;
const squareSize = canvas.width / boardSize;
// Players
const players = {
RED: 'red',
BLACK: 'black'
};
// Initialize Game State
let gameState = {
board: [],
currentPlayer: players.RED,
selectedPiece: null,
possibleMoves: [],
mustCaptures: [],
gameOver: false,
winner: null
};
// Initialize the board with pieces
function initBoard() {
gameState.board = [];
for (let row = 0; row < boardSize; row++) {
let currentRow = [];
for (let col = 0; col < boardSize; col++) {
if ((row + col) % 2 === 1) { // playable square
if (row < 3) {
currentRow.push({ player: players.BLACK, king: false });
} else if (row > 4) {
currentRow.push({ player: players.RED, king: false });
} else {
currentRow.push(null);
}
} else {
currentRow.push(null);
}
}
gameState.board.push(currentRow);
}
gameState.currentPlayer = players.RED;
gameState.selectedPiece = null;
gameState.possibleMoves = [];
gameState.mustCaptures = [];
gameState.gameOver = false;
gameState.winner = null;
}
// Draw the board and pieces
function drawBoard() {
for (let row = 0; row < boardSize; row++) {
for (let col = 0; col < boardSize; col++) {
// Draw squares
if ((row + col) % 2 === 0) {
ctx.fillStyle = '#EEE';
} else {
ctx.fillStyle = '#769656';
}
ctx.fillRect(col * squareSize, row * squareSize, squareSize, squareSize);
// Highlight selected square
if (gameState.selectedPiece && row === gameState.selectedPiece.row && col === gameState.selectedPiece.col) {
ctx.fillStyle = 'yellow';
ctx.fillRect(col * squareSize, row * squareSize, squareSize, squareSize);
}
// Highlight possible moves
if (gameState.possibleMoves.some(move => move.to.row === row && move.to.col === col)) {
ctx.fillStyle = 'rgba(0, 255, 0, 0.5)';
ctx.beginPath();
ctx.arc(
col * squareSize + squareSize / 2,
row * squareSize + squareSize / 2,
squareSize / 4,
0,
2 * Math.PI
);
ctx.fill();
}
// Draw pieces
let piece = gameState.board[row][col];
if (piece) {
// Piece color
ctx.beginPath();
ctx.arc(
col * squareSize + squareSize / 2,
row * squareSize + squareSize / 2,
squareSize / 2.5,
0,
2 * Math.PI
);
ctx.fillStyle = piece.player;
ctx.fill();
ctx.strokeStyle = '#000';
ctx.stroke();
// King indication
if (piece.king) {
ctx.fillStyle = 'gold';
ctx.font = `${squareSize / 2}px Arial`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText('K', col * squareSize + squareSize / 2, row * squareSize + squareSize / 2);
}
}
}
}
}
// Get all possible moves for the current player
function getAllPossibleMoves(player) {
let moves = [];
let captures = [];
for (let row = 0; row < boardSize; row++) {
for (let col = 0; col < boardSize; col++) {
let piece = gameState.board[row][col];
if (piece && piece.player === player) {
let pieceMoves = getPieceMoves(row, col, piece);
pieceMoves.forEach(move => {
if (move.capture) {
captures.push(move);
} else {
moves.push(move);
}
});
}
}
}
if (captures.length > 0) {
// If any captures are available, they must be taken
return captures;
} else {
return moves;
}
}
// Get possible moves for a single piece
function getPieceMoves(row, col, piece, prevJumps = []) {
let directions = [];
if (piece.player === players.RED || piece.king) {
directions.push({ row: -1, col: -1 });
directions.push({ row: -1, col: 1 });
}
if (piece.player === players.BLACK || piece.king) {
directions.push({ row: 1, col: -1 });
directions.push({ row: 1, col: 1 });
}
let moves = [];
directions.forEach(direction => {
let newRow = row + direction.row;
let newCol = col + direction.col;
// Normal move
if (isInsideBoard(newRow, newCol) && !gameState.board[newRow][newCol]) {
if (prevJumps.length === 0) { // only allow normal moves if not in the middle of a capture
moves.push({
from: { row, col },
to: { row: newRow, col: newCol },
capture: false
});
}
} else if (isInsideBoard(newRow, newCol)) {
let target = gameState.board[newRow][newCol];
if (target && target.player !== piece.player) {
let jumpRow = newRow + direction.row;
let jumpCol = newCol + direction.col;
if (isInsideBoard(jumpRow, jumpCol) && !gameState.board[jumpRow][jumpCol]) {
// Check if this capture hasn't already been done in this move sequence
if (!prevJumps.some(jump => jump.row === newRow && jump.col === newCol)) {
// Recursive jumps
let newPrevJumps = prevJumps.concat({ row: newRow, col: newCol });
let subsequentJumps = getPieceMoves(jumpRow, jumpCol, piece, newPrevJumps);
if (subsequentJumps.some(move => move.capture)) {
subsequentJumps.forEach(move => {
if (move.capture) {
moves.push({
from: { row, col },
to: move.to,
capture: true,
captured: { row: newRow, col: newCol }
});
}
});
} else {
moves.push({
from: { row, col },
to: { row: jumpRow, col: jumpCol },
capture: true,
captured: { row: newRow, col: newCol }
});
}
}
}
}
}
});
return moves;
}
// Check if the coordinates are inside the board
function isInsideBoard(row, col) {
return row >= 0 && row < boardSize && col >= 0 && col < boardSize;
}
// Handle canvas click
canvas.addEventListener('click', function(event) {
if (gameState.gameOver) return;
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
const col = Math.floor(x / squareSize);
const row = Math.floor(y / squareSize);
if (!isInsideBoard(row, col)) return;
const clickedPiece = gameState.board[row][col];
if (gameState.selectedPiece) {
// Check if clicked square is a possible move
const move = gameState.possibleMoves.find(m => m.to.row === row && m.to.col === col);
if (move) {
makeMove(move);
} else {
// Select a different piece if it's player's own
if (clickedPiece && clickedPiece.player === gameState.currentPlayer) {
selectPiece(row, col);
} else {
// Deselect if clicking elsewhere
gameState.selectedPiece = null;
gameState.possibleMoves = [];
}
}
} else {
if (clickedPiece && clickedPiece.player === gameState.currentPlayer) {
selectPiece(row, col);
}
}
drawBoard();
});
// Select a piece and show possible moves
function selectPiece(row, col) {
gameState.selectedPiece = { row, col };
gameState.possibleMoves = getAllPossibleMoves(gameState.currentPlayer).filter(m => m.from.row === row && m.from.col === col);
}
// Make a move
function makeMove(move) {
const from = move.from;
const to = move.to;
// Move the piece
gameState.board[to.row][to.col] = { ...gameState.board[from.row][from.col] };
gameState.board[from.row][from.col] = null;
// Handle capture
if (move.capture) {
gameState.board[move.captured.row][move.captured.col] = null;
// Check for additional jumps
const piece = gameState.board[to.row][to.col];
let additionalMoves = getPieceMoves(to.row, to.col, piece, [{ row: move.captured.row, col: move.captured.col }])
.filter(m => m.capture);
if (additionalMoves.length > 0) {
// Must continue capturing
gameState.selectedPiece = { row: to.row, col: to.col };
gameState.possibleMoves = additionalMoves;
drawBoard();
return;
}
}
// Promote to king if reaches the end
if (to.row === 0 && gameState.currentPlayer === players.RED && !gameState.board[to.row][to.col].king) {
gameState.board[to.row][to.col].king = true;
}
if (to.row === boardSize - 1 && gameState.currentPlayer === players.BLACK && !gameState.board[to.row][to.col].king) {
gameState.board[to.row][to.col].king = true;
}
// Switch turn
switchPlayer();
// Deselect
gameState.selectedPiece = null;
gameState.possibleMoves = [];
// Redraw and update status
drawBoard();
updateStatus();
}
// Switch to the other player and check for game over
function switchPlayer() {
gameState.currentPlayer = gameState.currentPlayer === players.RED ? players.BLACK : players.RED;
const possibleMoves = getAllPossibleMoves(gameState.currentPlayer);
if (possibleMoves.length === 0) {
gameState.gameOver = true;
gameState.winner = gameState.currentPlayer === players.RED ? players.BLACK : players.RED;
}
}
// Update the status display
function updateStatus() {
if (gameState.gameOver) {
statusDiv.textContent = `${capitalize(gameState.winner)} wins!`;
} else {
statusDiv.textContent = `${capitalize(gameState.currentPlayer)}'s Turn`;
}
}
// Capitalize first letter
function capitalize(word) {
return word.charAt(0).toUpperCase() + word.slice(1);
}
// Restart the game
restartButton.addEventListener('click', function() {
initBoard();
drawBoard();
updateStatus();
});
// Initialize and draw the initial board
initBoard();
drawBoard();
updateStatus();
</script>
</body>
</html>
HTML Structure:
<canvas> element with the ID gameCanvas is used to render the game board and pieces.<div> with the ID status displays the current game status (e.g., whose turn it is or who won).<button> with the ID restart allows players to restart the game at any time.Styling:
status and restart button for better user experience.JavaScript Logic:
Game State:
gameState object keeps track of the board, current player, selected piece, possible moves, captures, and game over status.Initialization:
initBoard() sets up the board with the initial positions of the red and black pieces.Rendering:
drawBoard() handles drawing the board squares, highlighting selected pieces and possible moves, and rendering the pieces. Kings are indicated by a "K" in gold color.Game Mechanics:
getAllPossibleMoves(player) retrieves all possible moves for a given player, prioritizing captures as per standard Checkers rules.getPieceMoves(row, col, piece, prevJumps) calculates possible moves for a specific piece, including handling multiple jumps.isInsideBoard(row, col) ensures that moves stay within the boundaries of the board.User Interaction:
makeMove(move).Move Execution:
makeMove(move) updates the board state, handles capturing opponent pieces, promotes pieces to kings if they reach the opposite end, and checks for additional jumps or game-over conditions.Standard Board Setup: An 8x8 grid with alternating playable squares; red and black pieces are placed on the first three and last three rows, respectively.
Piece Movement:
Capturing:
Promotion to King:
Turn Management:
Game Over Conditions:
User Interaction:
While the above implementation covers all basic rules, here are some ideas for further enhancements:
AI Opponent: Implement an AI to play against, using algorithms like Minimax.
Drag and Drop: Instead of clicking to select and then click to move, allow drag-and-drop functionality for a more intuitive experience.
Move Undo: Allow players to undo their last move in case of mistakes.
Move History: Display a history of moves made during the game.
Responsive Design: Make the canvas responsive to different screen sizes for better accessibility on various devices.
Feel free to enhance the game further based on your requirements!
Not yet included in a published release.
Game Status:
updateStatus() updates the status message to reflect the current player's turn or announce the winner if the game is over.Restart Functionality: