Click here to Skip to main content
15,942,934 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I am trying to build a checkers game with basic CSS, JS and HTML. The code assumes a player one starts and set a Boolean value for that player to be true and the Boolean value for the second player to start to false. I have drawn the Checker Board using a table element and then looped through the table cells while adding checker box styles and pieces using CSS. I have decided to start programming the behavior of the bottom pieces and here is a pseudocode for the expected behavior.

1. Listen for a square tap
2. Check whose turn it is to play
3. If that player has turn first check if there are any pending captures
If there are pending captures then force the player to complete the capture to the last box
4. If the player has no pending capture then just wait for him to make a move

5. update the turn such that it is the turn of the other player to be true and the turn of the current player to be false


I have made some progress with the code below but cannot complete these functions

I need a function to check if a piece is movable before highlighting the potential empty squares it can move to

I also need a function to check for multiple jump overs and listen to jump over multiple pieces to the last box, help me beat this

What I have tried:

HTML
<pre><!DOCTYPE html>
<html>
<head>
    <!--add a bootstrap dependency-->
    <link rel="stylesheet" href="bootstrap/bootstrap.min.css"/>
    <!--add a stylesheet dependency-->
    <link rel="stylesheet" href="styles.css"/>
    <script src="index.js"></script>
</head>
<body>
    <table id="checkertable" class="table">
    </table>
</body>
</html>


CSS
body{
    background: black;
}
.square{
    width:80px;
    height:80px;
    margin:auto;
}
.table{
    width:640px;
    height:640px;
    margin:auto;
    padding:0px;
}
/*css style to define a single square on the board*/

.black {
    background-color: chocolate
        ;
}

.white {
    background-color: white;
}
/*colors for the top pieces*/
.top-piece {
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.5);
    background-color: black;
    width: 80%;
    height: 80%;
    border-radius: 50%;
    margin: 10%;
}
/*colors for the bottom pieces*/
.bottom-piece {
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.5);
    background-color:darkorchid;
    width: 80%;
    height: 80%;
    border-radius: 50%;
    margin: 10%;
}
/*style to highlight a cell*/
.highlight-cell{
    border:2px solid black;
}


JavaScript
JavaScript
let playertwo = true;
let playerone = false;
//array to hold the target of a move piece event by player two
let previousplayertwotap = false;
//hold the last clicked purple piece in a dictionary
let lastpurple = {}
function createCheckerboard() {
    const table = document.getElementById('checkertable');
    for (let row = 0; row < 8; row++) {
        const newRow = table.insertRow();
        for (let col = 0; col < 8; col++) {
            const newCell = newRow.insertCell();
            newCell.classList.add('square');
            if ((row + col) % 2 === 0) {
                newCell.classList.add('white');
            } else {
                newCell.classList.add('black');
                //draw on the first three dark contrast cells
                if (row < 3) {
                    // Draw pieces over the dark squares on the first three rows
                    const piece = document.createElement('div');
                    piece.classList.add('top-piece');
                    newCell.appendChild(piece);
                }
                //draw on the last three dark contrast cells
                if (row >= 5) {
                    // Draw pieces over the dark squares on the last three rows
                    const piece = document.createElement('div');
                    piece.classList.add('bottom-piece');
                    newCell.appendChild(piece);
                }
                //add an event listener for new black cell click
                newCell.addEventListener('click', function (event) {
                    //check if the piece is black or purple
                    if (event.target.classList.contains('bottom-piece')) {
                        //check if it is the turn of player two to play
                        if (playertwo) {
                            console.log("player two has clicked a piece and wants to move it");
                            //get the cell to the top left
                            let x1 = row - 1; let y1 = col - 1;
                            //get the cell to the top right
                            let x2 = row - 1; let y2 = col + 1;
                            //get the two cells
                            let cell1 = getTableCell(table, x1, y1);
                            let cell2 = getTableCell(table, x2, y2);
                            //clear all pending highlights
                            const allPieces = document.querySelectorAll('.square');
                            // Loop through each piece
                            allPieces.forEach(function (element) {
                                element.classList.remove('highlight-cell');
                            });
                            //highlight them if the piece can be moved
                            if (purplepieceMovable) {
                                lastpurple["lastpurplemove"] = [row, col];
                                previousplayertwotap = true;
                                if (cell1 != null) {
                                    cell1.classList.add('highlight-cell');
                                }
                                if (cell2 != null) {
                                    cell2.classList.add('highlight-cell');
                                }
                            } else {
                                //means the piece has no free square to move to
                            }
                           
   
                        } else {
                            //it means it is not the turn of player two
                            return;
                        }
                       
                    }
                    //check if a piece on the top has been clicked

                    //check if an empty square has been clicked
                    if (!event.target.classList.contains('top-piece') && !event.target.classList.contains('bottom-piece')) {
                        //an empty square has been clicked
                        //check for the turn
                        if (playertwo) {
                            console.log("it is the turn of player two and an empty square has been clicked");
                            //check if there was a previous piece clicked
                            if (previousplayertwotap) {
                                //get the square tapped before with a purple piece
                                let square = lastpurple["lastpurplemove"];
                                //check if the piece can capture
                                //check if it can capture in both directions
                                if ((square[0]-row) == 2) {
                                    //this is a single piece can capture, check the direction of the capture by comparing the columns
                                    if (square[1] > col) {
                                        //it is a single capture towards the left
                                        //get the cell of the opponent in the middle
                                        let x1 = square[0] - 1; let y1 = square[1] - 1;
                                        let cellBetween = getTableCell(table, x1, y1);
                                        //get the opponent piece and remove it from that cell
                                        let childCell = cellBetween.querySelector('.top-piece');
                                        if (childCell != null) {
                                            cellBetween.removeChild(childCell);
                                            //move the piece to the tapped cell
                                            let targetCell = getTableCell(table, row, col);
                                            const piece = document.createElement('div');
                                            piece.classList.add('bottom-piece');
                                            targetCell.appendChild(piece);
                                        }
                                    }
                                }
                               
                                console.log(square[0] + ":" + square[1]);
                                //the row needs to be less than the original
                                if (square[0] > row) {
                                    //a piece cannot jump over an empty piece
                                    if ((square[0] - row) == 1) {
                                        const piece = document.createElement('div');
                                        piece.classList.add('bottom-piece');
                                        let parentCell = getTableCell(table, row, col);
                                        parentCell.appendChild(piece);
                                        //clear the piece from the original cell
                                        let cellA = getTableCell(table, square[0], square[1]);
                                        let childCell = cellA.querySelector('.bottom-piece');
                                        cellA.removeChild(childCell);
                                        //clear all the square hughlights
                                        const allPieces = document.querySelectorAll('.square');
                                        // Loop through each piece
                                        allPieces.forEach(function (element) {
                                            element.classList.remove('highlight-cell');
                                        });
                                        playerone = true;
                                        playertwo = false;
                                    } else {
                                        console.log("a piece cannot jump over an empty square unless it is capturing");
                                    }
                                  
                                } else {
                                    console.log("a piece cannot be moved backwards");
                                }
                            } else {
                                console.log("no previous square piece square clicked");
                            }
                        } else {
                            console.log("player two tries to play when it is the turn of player one");
                        }
                    }
                });
            }
           
        }
    }
}
//function to check if a piece can be moved to other cells
//it accepts the co ordinates of the original cell and the table

function purplepieceMovable(table, row, col) {
    //get the top left co ordinate
    let x1 = row - 1; let y1 = col - 1;
    let x2 = row - 1; let y2 = col + 1;
    //check if the cells are empty
    let cell1 = getTableCell(table, x1, y1);
    let cell2 = getTableCell(table, x2, y2);
    //even if one cell is empty then the piece can be moved to it
    if (cell1.classList.contains('.top-piece')) {

    }
}
function getTableCell(table, rowIndex, colIndex) {
    // Check if the table exists and if the row index is valid
    if (table && rowIndex >= 0 && rowIndex < table.rows.length) {
        // Get the row
        const row = table.rows[rowIndex];

        // Check if the row contains cells and if the column index is valid
        if (row && colIndex >= 0 && colIndex < row.cells.length) {
            // Return the cell at the specified row and column indices
            return row.cells[colIndex];
        }
    }

    // If the table, row, or cell doesn't exist or the indices are invalid, return null
    return null;
}
//call the function to draw the board
window.onload = () => createCheckerboard();
Posted
Comments
[no name] 11-Jun-24 12:01pm    
Perhaps a question to post in the Discussions forum?
Tim the Gamer 11-Jun-24 13:49pm    
What's wrong with posting it here? I needed help from enthusiastic and professional developers

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900