Open In App

Bishop Movement Visualizer on Chessboard

Last Updated : 06 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to create a Bishop Movement Visualizer on a chessboard using HTML, CSS, and JavaScript. The chessboard will consist of alternating black and white cells arranged in an 8×8 matrix. We will implement functionality to visualize the movement of a bishop by highlighting the cells it can move to. Let’s get started!

Approach: To begin, create a new folder named “BishopMovementVisualizer” and open it in your preferred code editor (such as VS Code). Inside the folder, create three files: index.html for HTML code, script.js for JavaScript code, and style.css for CSS code.

HTML Structure: In the index.html file, let’s start with the basic HTML structure. Update the <title> tag to reflect the project, and add a heading (<h1>) with the title “Bishop Movement on Chessboard” inside a green box. We’ll assign the class name “heading” to the heading for styling purposes. Additionally, we’ll create a <table> element to represent the chessboard and give it the class name “chessboard”.

Styling: In the style.css file, let’s apply some styling to the elements. We’ll center the heading text by targeting the class “heading” and setting text-align: center;. We’ll also center the chessboard table by targeting its class name “chessboard” and using the CSS rule margin: 0 auto;.

To represent the cells on the chessboard, we’ll create a CSS class for the boxes. Set the width and height to 70 pixels, apply a gray border with a width of 1 pixel, and use the inset border style. Additionally, we’ll define separate CSS classes for the black and white colors to be used for the cells.

JavaScript Logic: In the script.js file, we’ll write the JavaScript code to populate the rows and columns of the chessboard with the appropriate colors. First, we’ll access the table element using document.getElementById('chessboard') and store it in a variable named table.

Next, we’ll use nested loops to create the rows and columns. We’ll iterate from 0 to 7 for both the row and column indices. Inside the loops, we’ll create table rows (<tr>) and table data cells (<td>) for each row and column. We’ll assign a unique data attribute called “data-index” to each cell, representing its row and column indices.

To alternate the colors, we’ll use a boolean variable called white. If it’s true, we’ll add the “white” class to the cell; otherwise, we’ll add the “black” class.

Visualizing Bishop Movement: To visualize the movement of the bishop, we’ll add an event listener for the click event on each cell. When a cell is clicked, we’ll retrieve its row and column indices from the data attribute using event.target.dataset.index. We’ll then split the value and convert the indices to integers.

With the row and column indices, we’ll calculate the diagonal cells that the bishop can move to. We’ll create a helper function called calculateDiagonalCells that takes the current row and column indices as arguments and returns an array of diagonal cell indices. This function will implement the bishop movement logic.

Next, we’ll iterate through all the cells and check if their row and column indices exist in the array of diagonal cell indices. If they do, we’ll add the “highlight” class to those cells, visually indicating the bishop’s possible movement.

Complete running code example:

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0" />
    <title>Bishop Movement on Chessboard</title>
    <style>
        .heading {
            text-align: center;
        }
  
        .table {
            margin: 0 auto;
            cursor: pointer;
        }
  
        .box {
            width: 70px;
            height: 70px;
            border: 1px solid grey;
            border-style: inset;
        }
  
        .black {
            background-color: black;
        }
  
        .white {
            background-color: white;
        }
  
        .blue {
            background-color: blue;
        }
    </style>
</head>
  
<body>
    <h1 class="heading">Bishop Movement Visualizer</h1>
  
    <table id="table" class="table" cellspacing="0"></table>
      
    <script>
        let table = document.getElementById("table");
  
        for (let i = 0; i < 8; i++) {
            // row
            let tr = document.createElement("tr");
            let white = i % 2 == 0 ? true : false;
            for (let j = 0; j < 8; j++) {
                // col
                let td = document.createElement("td");
                if (white) {
                    td.setAttribute("class", "box white");
                } else {
                    td.setAttribute("class", "box black");
                }
                white = !white;
                td.setAttribute("data-index", `${i}-${j}`);
                tr.appendChild(td);
            }
            table.appendChild(tr);
        }
  
        table.addEventListener("mouseover", function (e) {
            let temp = e.target.dataset.index.split("-")
                .map((val) => parseInt(val));
            let row = temp[0];
            let col = temp[1];
            let str = `${row}-${col}`;
            let hash = {};
            hash[str] = true;
  
            hash = findTopLeft(row, col, hash);
            hash = findTopRight(row, col, hash);
            hash = findBottomLeft(row, col, hash);
            hash = findBottomRight(row, col, hash);
  
            let cells = document.querySelectorAll("td");
  
            for (let i = 0; i < cells.length; i++) {
                cells[i].classList.remove("blue");
            }
  
            for (let i = 0; i < cells.length; i++) {
                let str = `${cells[i].closest("tr")
                    .rowIndex}-${cells[i].cellIndex}`;
                      
                if (hash[str]) {
                    cells[i].classList.add("blue");
                }
            }
        });
  
        table.addEventListener("mouseleave", function (e) {
            const cells = document.querySelectorAll("td");
  
            for (let i = 0; i < cells.length; i++) {
                cells[i].classList.remove("blue");
            }
        });
  
        function findTopLeft(row, col, hash) {
            row--;
            col--;
            while (row >= 0 && col >= 0) {
                let key = `${row}-${col}`;
                hash[key] = true;
                row--;
                col--;
            }
  
            return hash;
        }
  
        function findTopRight(row, col, hash) {
            row--;
            col++;
            while (row >= 0 && col < 8) {
                let key = `${row}-${col}`;
                hash[key] = true;
                row--;
                col++;
            }
  
            return hash;
        }
  
        function findBottomLeft(row, col, hash) {
            row++;
            col--;
            while (row < 8 && col >= 0) {
                let key = `${row}-${col}`;
                hash[key] = true;
                row++;
                col--;
            }
  
            return hash;
        }
  
        function findBottomRight(row, col, hash) {
            row++;
            col++;
            while (row < 8 && col < 8) {
                let key = `${row}-${col}`;
                hash[key] = true;
                row++;
                col++;
            }
  
            return hash;
        }
    </script>
</body>
  
</html>


Output:

screencast-127001_5500-20230616-11_44_32.gif

bishop movement visualizer

Conclusion: In this article, we learned how to create a Bishop Movement Visualizer on a chessboard using HTML, CSS, and JavaScript. We implemented functionality to highlight the cells that a bishop can move to, and we explored the concept of calculating diagonal cells. Feel free to customize and enhance the visualizer further, adding animations or additional chess pieces. Have fun exploring the fascinating world of chess programming!



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads