Create a Chess Game with jQuery Plugin

Create a Chess Game with jQuery Plugin

Chess game is a timeless, strategic board game that has captivated the minds of people for centuries. It is a game of intelligence, requiring players to think ahead, predict moves, and utilize a wide variety of tactics to gain the upper hand. The game’s popularity has transcended geographical boundaries, bringing people together to play, whether in person or online. While traditional chess game is usually played on a physical board, the rise of technology has led to the creation of digital chess platforms, allowing players to compete in virtual spaces with ease.

In the web development world, integrating chess game into websites and applications has become increasingly common. Whether it’s for educational purposes, casual gaming, or as part of a larger project, developers have been leveraging various tools and technologies to create engaging, interactive chess experiences for users. One such solution is the jQuery Chess Plugin, a minimalist plugin designed to provide an easy-to-implement chess game interface for websites. This article delves into the features and functionality of the plugin, exploring its design, customization options, and how it can be integrated into your website or application.

Developing Your Own Chat with Stranger System Using PHP

Follow this video for complete guidance:

What is the jQuery Chess Plugin?

The jQuery Chess Plugin is a lightweight JavaScript library that allows developers to easily embed a fully functional chess game onto their website. With just a few lines of code, developers can initialize the game on any DOM element, customize it, and enable users to play chess directly in their web browsers. The plugin is built on top of jQuery and is designed to be simple, flexible, and customizable.

Click Here to Download jQuery Chess Plugin

Or you can copy this code for chess.js

/**
 * jQuery Chess Plugin
 * A minimalist chess game that can be initialized on any element with customizable options
 * 
 * @author Ritesh
 * @version 1.0.0
 */
(function($) {
  $.fn.chess = function(options) {
    // Default options
    const defaults = {
      squareSize: 40,
      darkSquareColor: '#B58863',
      lightSquareColor: '#F0D9B5',
      highlightColor: 'lightblue',
      moveIndicatorColor: 'rgba(0,128,0,0.5)',
      startPosition: 'default',
      pieceScale: 0.75,
      showCoordinates: false,
    };

    // Merge options with defaults
    const settings = $.extend({}, defaults, options);
    
    // Piece mappings
    const pieces = {
      w: {p: '♙', r: '♖', n: '♘', b: '♗', q: '♕', k: '♔'},
      b: {p: '♟', r: '♜', n: '♞', b: '♝', q: '♛', k: '♚'}
    };

    // Initialize each matching element
    return this.each(function() {
      const $container = $(this);
      $container.css({
        textAlign: 'center'
      });
      
      // Create board
      const $board = $('<div>').addClass('chess-board').appendTo($container);
   
      // Game state
      let board = [];
      let turn = 'w';
      let selected = null;
      
      // Set up CSS
      const setupCSS = function() {
        $board.css({
          display: 'grid',
          gridTemplateColumns: `repeat(8, ${settings.squareSize}px)`,
          margin: '0 auto',
          position: 'relative'
        });
        

      
        
        // Add a style tag for square styles
        $('<style>').text(`
          .chess-square {
            width: ${settings.squareSize}px;
            height: ${settings.squareSize}px;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            font-size: ${settings.squareSize * settings.pieceScale}px;
            position: relative;
          }
          .chess-dark { background-color: ${settings.darkSquareColor}; }
          .chess-light { background-color: ${settings.lightSquareColor}; }
          .chess-selected { background-color: ${settings.highlightColor} !important; }
          .chess-move::after {
            content: "";
            position: absolute;
            width: ${settings.squareSize * 0.25}px;
            height: ${settings.squareSize * 0.25}px;
            background-color: ${settings.moveIndicatorColor};
            border-radius: 50%;
          }
          .chess-coord {
            position: absolute;
            font-size: ${settings.squareSize * 0.3}px;
            opacity: 0.8;
            pointer-events: none;
          }
          .chess-file { bottom: 2px; right: 4px; }
          .chess-rank { top: 2px; left: 4px; }
        `).appendTo('head');
      };
      
      // Initial board setup
      const initBoard = function() {
        if (settings.startPosition === 'default') {
          board = [
            ['br','bn','bb','bq','bk','bb','bn','br'],
            ['bp','bp','bp','bp','bp','bp','bp','bp'],
            ['','','','','','','',''],
            ['','','','','','','',''],
            ['','','','','','','',''],
            ['','','','','','','',''],
            ['wp','wp','wp','wp','wp','wp','wp','wp'],
            ['wr','wn','wb','wq','wk','wb','wn','wr']
          ];
        } else if (settings.startPosition === 'empty') {
          board = Array(8).fill().map(() => Array(8).fill(''));
        } else if (Array.isArray(settings.startPosition) && settings.startPosition.length === 8) {
          board = settings.startPosition;
        }
        
        turn = 'w';
        selected = null;
        
      };
      
      // Draw board and pieces
      const drawBoard = function() {
        $board.empty();
        
        const files = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];
        const ranks = ['8', '7', '6', '5', '4', '3', '2', '1'];
        
        for (let r = 0; r < 8; r++) {
          for (let c = 0; c < 8; c++) {
            const squareColor = (r + c) % 2 === 0 ? 'chess-light' : 'chess-dark';
            const $square = $('<div>')
              .addClass(`chess-square ${squareColor}`)
              .attr('data-row', r)
              .attr('data-col', c)
              .appendTo($board);
            
            if (board[r][c]) {
              const color = board[r][c][0];
              const type = board[r][c][1];
              $square.html(pieces[color][type]);
            }
            
            // Add coordinates if enabled
            if (settings.showCoordinates) {
              if (r === 7) {
                $('<span>')
                  .addClass('chess-coord chess-file')
                  .text(files[c])
                  .appendTo($square);
              }
              
              if (c === 0) {
                $('<span>')
                  .addClass('chess-coord chess-rank')
                  .text(ranks[r])
                  .appendTo($square);
              }
            }
          }
        }
      };
      
      
      
      // Get valid moves for a piece
      const getValidMoves = function(r, c) {
        if (!board[r][c] || board[r][c][0] !== turn) return [];
        
        const piece = board[r][c][1];
        const color = board[r][c][0];
        const moves = [];
        
        // Pawn moves
        if (piece === 'p') {
          const direction = color === 'w' ? -1 : 1;
          const startRow = color === 'w' ? 6 : 1;
          
          // Forward move
          if (r + direction >= 0 && r + direction < 8 && !board[r + direction][c]) {
            moves.push([r + direction, c]);
            
            // Initial double move
            if (r === startRow && !board[r + 2 * direction][c]) {
              moves.push([r + 2 * direction, c]);
            }
          }
          
          // Captures
          [-1, 1].forEach(offset => {
            if (c + offset >= 0 && c + offset < 8 && 
                board[r + direction][c + offset] && 
                board[r + direction][c + offset][0] !== color) {
              moves.push([r + direction, c + offset]);
            }
          });
        }
        
        // Rook & Queen moves (horizontal/vertical)
        if (piece === 'r' || piece === 'q') {
          [[0, 1], [1, 0], [0, -1], [-1, 0]].forEach(dir => {
            for (let i = 1; i < 8; i++) {
              const newRow = r + dir[0] * i;
              const newCol = c + dir[1] * i;
              
              if (newRow < 0 || newRow > 7 || newCol < 0 || newCol > 7) break;
              
              if (!board[newRow][newCol]) {
                moves.push([newRow, newCol]);
              } else {
                if (board[newRow][newCol][0] !== color) {
                  moves.push([newRow, newCol]);
                }
                break;
              }
            }
          });
        }
        
        // Bishop & Queen moves (diagonal)
        if (piece === 'b' || piece === 'q') {
          [[1, 1], [1, -1], [-1, 1], [-1, -1]].forEach(dir => {
            for (let i = 1; i < 8; i++) {
              const newRow = r + dir[0] * i;
              const newCol = c + dir[1] * i;
              
              if (newRow < 0 || newRow > 7 || newCol < 0 || newCol > 7) break;
              
              if (!board[newRow][newCol]) {
                moves.push([newRow, newCol]);
              } else {
                if (board[newRow][newCol][0] !== color) {
                  moves.push([newRow, newCol]);
                }
                break;
              }
            }
          });
        }
        
        // Knight moves
        if (piece === 'n') {
          [[2, 1], [1, 2], [-1, 2], [-2, 1], [-2, -1], [-1, -2], [1, -2], [2, -1]].forEach(offset => {
            const newRow = r + offset[0];
            const newCol = c + offset[1];
            
            if (newRow >= 0 && newRow < 8 && newCol >= 0 && newCol < 8 && 
                (!board[newRow][newCol] || board[newRow][newCol][0] !== color)) {
              moves.push([newRow, newCol]);
            }
          });
        }
        
        // King moves
        if (piece === 'k') {
          [[0, 1], [1, 0], [0, -1], [-1, 0], [1, 1], [1, -1], [-1, 1], [-1, -1]].forEach(offset => {
            const newRow = r + offset[0];
            const newCol = c + offset[1];
            
            if (newRow >= 0 && newRow < 8 && newCol >= 0 && newCol < 8 && 
                (!board[newRow][newCol] || board[newRow][newCol][0] !== color)) {
              moves.push([newRow, newCol]);
            }
          });
        }
        
        return moves;
      };
      
      // Highlight valid moves
      const showValidMoves = function(moves) {
        $('.chess-square').removeClass('chess-move');
        moves.forEach(move => {
          $(`.chess-square[data-row="${move[0]}"][data-col="${move[1]}"]`).addClass('chess-move');
        });
      };
      
      // Handle square click
      const handleSquareClick = function() {
        const row = parseInt($(this).attr('data-row'));
        const col = parseInt($(this).attr('data-col'));
        
        $('.chess-square').removeClass('chess-move');
        
        // If no piece is selected
        if (!selected) {
          if (board[row][col] && board[row][col][0] === turn) {
            selected = [row, col];
            $('.chess-square').removeClass('chess-selected');
            $(this).addClass('chess-selected');
            
            const validMoves = getValidMoves(row, col);
            showValidMoves(validMoves);
          }
        } else {
          // If a piece is already selected
          const [selectedRow, selectedCol] = selected;
          $('.chess-square').removeClass('chess-selected');
          
          // If clicking the same square, deselect
          if (row === selectedRow && col === selectedCol) {
            selected = null;
            return;
          }
          
          // If clicking another of your pieces, select that instead
          if (board[row][col] && board[row][col][0] === turn) {
            selected = [row, col];
            $(this).addClass('chess-selected');
            const validMoves = getValidMoves(row, col);
            showValidMoves(validMoves);
            return;
          }
          
          // Check if the move is valid
          const validMoves = getValidMoves(selectedRow, selectedCol);
          const isValidMove = validMoves.some(move => move[0] === row && move[1] === col);
          
          if (isValidMove) {
            // Move piece
            board[row][col] = board[selectedRow][selectedCol];
            board[selectedRow][selectedCol] = '';
            
            // Switch turn
            turn = turn === 'w' ? 'b' : 'w';

            
            // Redraw board
            drawBoard();
          }
          
          selected = null;
        }
      };
      
      // Initialize the game
      const init = function() {
        setupCSS();
        initBoard();
        drawBoard();
        
        // Event handlers
        $container.on('click', '.chess-square', handleSquareClick);
        
        
      };
      
      // Public methods to expose
      $container.data('chess', {
        
        position: function(fen) {
          // Basic FEN parser (only handles piece placement)
          if (typeof fen === 'string') {
            const rows = fen.split('/');
            if (rows.length === 8) {
              board = Array(8).fill().map(() => Array(8).fill(''));
              
              rows.forEach((row, r) => {
                let c = 0;
                for (let i = 0; i < row.length; i++) {
                  const char = row[i];
                  if ('12345678'.includes(char)) {
                    c += parseInt(char);
                  } else {
                    const color = char === char.toUpperCase() ? 'w' : 'b';
                    const type = char.toLowerCase();
                    if ('prnbqk'.includes(type)) {
                      board[r][c] = color + type;
                      c++;
                    }
                  }
                }
              });
              
              drawBoard();
            }
          }
        },
        getBoard: function() {
          return JSON.parse(JSON.stringify(board));
        },
        getTurn: function() {
          return turn;
        },
        setTurn: function(color) {
          if (color === 'w' || color === 'b') {
            turn = color;

          }
        }
      });
      
      // Initialize
      init();
    });
  };
})(jQuery);

 

This plugin offers a clean, minimalistic design, making it ideal for developers who want to provide a smooth and engaging chess experience without overwhelming users with complex interfaces or excess features. It supports basic gameplay mechanics, such as piece movement, turn tracking, and visual indicators of valid moves.

Features of the jQuery Chess Plugin

The plugin comes with several key features that make it easy to integrate and customize:

  1. Customizable Board Size and Colors
    The plugin allows developers to customize the size of the chessboard and the colors of the squares. You can change the appearance of the dark and light squares, adjust the size of each square, and choose different colors for the highlighting and move indicators.

  2. Dynamic Piece Representation
    The plugin uses Unicode characters to represent chess pieces, providing a visually clear way to display the pieces on the board. The plugin includes representations for both white and black pieces, such as pawns, knights, bishops, rooks, queens, and kings.

  3. Turn Indicator
    The plugin keeps track of whose turn it is (either white or black) and ensures that players can only move their respective pieces. The turn is automatically switched after each valid move.

  4. Valid Move Highlighting
    When a player selects a piece, the plugin visually highlights all valid moves for that piece, making it easier for users to understand the available options. Invalid moves are ignored, and the plugin prevents users from making illegal moves.

  5. Piece Movement Logic
    The plugin includes logic for determining the valid moves of each piece, including pawns, rooks, knights, bishops, queens, and kings. It accounts for piece-specific movement rules, such as the pawn’s initial two-square move and en passant captures.

  6. Support for Multiple Board Configurations
    The plugin can initialize the chessboard in a variety of configurations. By default, the board is set up in the traditional starting position, but developers can opt for an empty board or provide a custom position using a FEN (Forsyth-Edwards Notation) string.

  7. Responsive and Scalable
    The plugin is designed to be responsive, adjusting to different screen sizes and ensuring the game can be played on both desktop and mobile devices. The board and pieces automatically scale to fit the container element, making it versatile across different devices.

  8. Customizable Appearance
    With the plugin’s options, you can easily modify the appearance of the chessboard and pieces. You can change the font size of the pieces, modify the square sizes, and even add coordinates to the edges of the board to make it more intuitive for users.

  9. Easy Initialization
    The plugin is easy to initialize on any DOM element. A single line of code is all that is needed to initialize the game. The chess() function can be called on any HTML container element, and it automatically sets up the game with default or custom settings.

How the jQuery Chess Plugin Works

To get started with the jQuery Chess Plugin, you need to follow a few simple steps. Let’s break down the process of integrating the plugin into your website or web application.

Step 1: Include jQuery and the Plugin Script

To use the jQuery Chess Plugin, you must first include the jQuery library and the plugin’s script in your HTML file. You can link to the jQuery library from a CDN (Content Delivery Network) and add the plugin script.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> 
<script src="path/to/chess.js"></script>

Step 2: Create a Container for the Chessboard

Next, create a div element in your HTML where the chessboard will be rendered. This container element will hold the chess game interface.

<div id="chess1"></div>

Step 3: Initialize the Chessboard

After the page has loaded, you can initialize the chess game by calling the chess() function on the container element. This will render the chessboard and allow users to interact with the game.

$('#chess1').chess();

Step 4: Customize the Chessboard (Optional)

You can customize the chessboard by passing an options object to the chess() function. This object can contain various settings such as the board’s square size, colors, and whether or not to display coordinates.

$('#chess1').chess({ 
  squareSize: 50, 
  darkSquareColor: '#4A2C2A', 
  lightSquareColor: '#F5D59E', 
  highlightColor: 'yellow', 
  showCoordinates: true 
});

This will initialize the board with the specified piece layout.

The jQuery Chess Plugin is a simple yet powerful tool for adding a fully functional chess game to your website or web application. With its customizable options, minimalistic design, and intuitive interface, it offers a great solution for developers who want to integrate chess gameplay without the need for complex development. Whether you’re building an online chess platform, a chess tutorial site, or a casual game, the jQuery Chess Plugin can help you create a seamless chess experience for your users.

By using this plugin, developers can focus on their project’s other aspects while offering an engaging, interactive chess experience that users can enjoy. With the flexibility to customize the game to suit their needs, the plugin opens up endless possibilities for creating engaging chess games that can be embedded on any website.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *