1

I'm making a chess board game and I'm new to JavaScript. I was just wondering if someone could look at my Javascript code and see how I can simplify and make it more optimized. I repetitively keep on writing the same code that I'm pretty sure could be simplified. It's where there is some comments that say, "This is where I display my dots."

Here's my JavaScript code:

//dragging white pawns
function allowDrop(event) {
    event.preventDefault();
}

function drag(event) {
    event.dataTransfer.setData("text", event.target.id);
}
  
function drop(event) {
    event.preventDefault();
    var data = event.dataTransfer.getData("text");
    var newNode = document.getElementById(data).cloneNode(true);

    // Clear the drag square of the piece IMG...
    clearChildren( document.getElementById(data).parentNode);
    
    clearChildren(event.target);
    event.target.appendChild(newNode);

    // Finally, remove the "empty_squares5" class from the drop square.
    event.target.classList.remove( 'empty_squares5' );
}

function clearChildren(el) {
    while (el.firstChild) {
      el.removeChild(el.firstChild);
    }  
}

//This is for displaying dots
const dots = document.querySelectorAll(".empty_squares5 img");
const seventhSquares = document.querySelectorAll(".seventh_squares");

let arrayDots = Array.from(dots);
let arraySeventhSquares = Array.from(seventhSquares);


console.log(arrayDots);
console.log(arraySeventhSquares);


function showDots() {
    arraySeventhSquares[0].style.backgroundColor = "#4682B4";
    arrayDots[0].style.display= "inline";
    arrayDots[8].style.display = "inline";
}

function dontShowDots(event) {
    var x = event.buttons;
    if (x == 1) {
        arraySeventhSquares[1].style.backgroundColor = "lightgreen";
        arraySeventhSquares[2].style.backgroundColor = "slategray";
        arraySeventhSquares[3].style.backgroundColor = "lightgreen";
        arraySeventhSquares[4].style.backgroundColor = "slategray";
        arraySeventhSquares[5].style.backgroundColor = "lightgreen";
        arraySeventhSquares[6].style.backgroundColor = "slategray";
        arraySeventhSquares[7].style.backgroundColor = "lightgreen";
        arrayDots[1].style.display = "none";
        arrayDots[9].style.display = "none";
        arrayDots[2].style.display = "none";
        arrayDots[10].style.display = "none";
        arrayDots[3].style.display = "none";
        arrayDots[11].style.display = "none";
        arrayDots[4].style.display = "none";
        arrayDots[12].style.display = "none";
        arrayDots[5].style.display = "none";
        arrayDots[13].style.display = "none";
        arrayDots[6].style.display = "none";
        arrayDots[14].style.display = "none";
        arrayDots[7].style.display = "none";
        arrayDots[15].style.display = "none";
    }
}

function showDots2() {
    arraySeventhSquares[1].style.backgroundColor = "#4682B4";
    arrayDots[1].style.display= "inline";
    arrayDots[9].style.display = "inline";
}

function dontShowDots2(event) {
    var x = event.buttons;
    if (x == 1) {
        arraySeventhSquares[0].style.backgroundColor = "slategray";
        arraySeventhSquares[2].style.backgroundColor = "slategray";
        arraySeventhSquares[3].style.backgroundColor = "lightgreen";
        arraySeventhSquares[4].style.backgroundColor = "slategray";
        arraySeventhSquares[5].style.backgroundColor = "lightgreen";
        arraySeventhSquares[6].style.backgroundColor = "slategray";
        arraySeventhSquares[7].style.backgroundColor = "lightgreen";
        arrayDots[0].style.display = "none";
        arrayDots[8].style.display = "none";
        arrayDots[2].style.display = "none";
        arrayDots[10].style.display = "none";
        arrayDots[3].style.display = "none";
        arrayDots[11].style.display = "none";
        arrayDots[4].style.display = "none";
        arrayDots[12].style.display = "none";
        arrayDots[5].style.display = "none";
        arrayDots[13].style.display = "none";
        arrayDots[6].style.display = "none";
        arrayDots[14].style.display = "none";
        arrayDots[7].style.display = "none";
        arrayDots[15].style.display = "none";
    }
}

function showDots3() {
    arraySeventhSquares[2].style.backgroundColor = "#4682B4";
    arrayDots[2].style.display= "inline";
    arrayDots[10].style.display = "inline";
}

function dontSD3(event) {
    var x = event.buttons;
    if (x == 1) {
        arraySeventhSquares[0].style.backgroundColor = "slategray";
        arraySeventhSquares[1].style.backgroundColor = "lightgreen";
        arraySeventhSquares[3].style.backgroundColor = "lightgreen";
        arraySeventhSquares[4].style.backgroundColor = "slategray";
        arraySeventhSquares[5].style.backgroundColor = "lightgreen";
        arraySeventhSquares[6].style.backgroundColor = "slategray";
        arraySeventhSquares[7].style.backgroundColor = "lightgreen";
        arrayDots[0].style.display = "none";
        arrayDots[8].style.display = "none";
        arrayDots[1].style.display = "none";
        arrayDots[9].style.display = "none";
        arrayDots[3].style.display = "none";
        arrayDots[11].style.display = "none";
        arrayDots[4].style.display = "none";
        arrayDots[12].style.display = "none";
        arrayDots[5].style.display = "none";
        arrayDots[13].style.display = "none";
        arrayDots[6].style.display = "none";
        arrayDots[14].style.display = "none";
        arrayDots[7].style.display = "none";
        arrayDots[15].style.display = "none";
    }
}

function showDots4() {
    arraySeventhSquares[3].style.backgroundColor = "#4682B4";
    arrayDots[3].style.display= "inline";
    arrayDots[11].style.display = "inline";
}

function dontShowDots4(event) {
    var x = event.buttons;
    if (x == 1) {
        arraySeventhSquares[0].style.backgroundColor = "slategray";
        arraySeventhSquares[2].style.backgroundColor = "slategray";
        arraySeventhSquares[1].style.backgroundColor = "lightgreen";
        arraySeventhSquares[4].style.backgroundColor = "slategray";
        arraySeventhSquares[5].style.backgroundColor = "lightgreen";
        arraySeventhSquares[6].style.backgroundColor = "slategray";
        arraySeventhSquares[7].style.backgroundColor = "lightgreen";
        arrayDots[0].style.display = "none";
        arrayDots[8].style.display = "none";
        arrayDots[2].style.display = "none";
        arrayDots[10].style.display = "none";
        arrayDots[1].style.display = "none";
        arrayDots[9].style.display = "none";
        arrayDots[4].style.display = "none";
        arrayDots[12].style.display = "none";
        arrayDots[5].style.display = "none";
        arrayDots[13].style.display = "none";
        arrayDots[6].style.display = "none";
        arrayDots[14].style.display = "none";
        arrayDots[7].style.display = "none";
        arrayDots[15].style.display = "none";
    }
}

function showDots5() {
    arraySeventhSquares[4].style.backgroundColor = "#4682B4";
    arrayDots[4].style.display= "inline";
    arrayDots[12].style.display = "inline";
}

function dontShowDots5(event) {
    var x = event.buttons;
    if (x == 1) {
        arraySeventhSquares[0].style.backgroundColor = "slategray";
        arraySeventhSquares[1].style.backgroundColor = "lightgreen";
        arraySeventhSquares[2].style.backgroundColor = "slategray";
        arraySeventhSquares[3].style.backgroundColor = "lightgreen";
        arraySeventhSquares[5].style.backgroundColor = "lightgreen";
        arraySeventhSquares[6].style.backgroundColor = "slategray";
        arraySeventhSquares[7].style.backgroundColor = "lightgreen";
        arrayDots[0].style.display = "none";
        arrayDots[8].style.display = "none";
        arrayDots[1].style.display = "none";
        arrayDots[9].style.display = "none";
        arrayDots[2].style.display = "none";
        arrayDots[10].style.display = "none";
        arrayDots[3].style.display = "none";
        arrayDots[11].style.display = "none";
        arrayDots[5].style.display = "none";
        arrayDots[13].style.display = "none";
        arrayDots[6].style.display = "none";
        arrayDots[14].style.display = "none";
        arrayDots[7].style.display = "none";
        arrayDots[15].style.display = "none";
    }
}

function showDots6() {
    arraySeventhSquares[5].style.backgroundColor = "#4682B4";
    arrayDots[5].style.display= "inline";
    arrayDots[13].style.display = "inline";
}

function dontShowDots6(event) {
    var x = event.buttons;
    if (x == 1) {
        arraySeventhSquares[0].style.backgroundColor = "slategray";
        arraySeventhSquares[1].style.backgroundColor = "lightgreen";
        arraySeventhSquares[2].style.backgroundColor = "slategray";
        arraySeventhSquares[3].style.backgroundColor = "lightgreen";
        arraySeventhSquares[4].style.backgroundColor = "slategray";
        arraySeventhSquares[6].style.backgroundColor = "slategray";
        arraySeventhSquares[7].style.backgroundColor = "lightgreen";
        arrayDots[0].style.display = "none";
        arrayDots[8].style.display = "none";
        arrayDots[1].style.display = "none";
        arrayDots[9].style.display = "none";
        arrayDots[2].style.display = "none";
        arrayDots[10].style.display = "none";
        arrayDots[3].style.display = "none";
        arrayDots[11].style.display = "none";
        arrayDots[4].style.display = "none";
        arrayDots[12].style.display = "none";
        arrayDots[6].style.display = "none";
        arrayDots[14].style.display = "none";
        arrayDots[7].style.display = "none";
        arrayDots[15].style.display = "none";
    }
}

function showDots7() {
    arraySeventhSquares[6].style.backgroundColor = "#4682B4";
    arrayDots[6].style.display= "inline";
    arrayDots[14].style.display = "inline";
}

function dontShowDots7(event) {
    var x = event.buttons;
    if (x == 1) {
        arraySeventhSquares[0].style.backgroundColor = "slategray";
        arraySeventhSquares[1].style.backgroundColor = "lightgreen";
        arraySeventhSquares[2].style.backgroundColor = "slategray";
        arraySeventhSquares[3].style.backgroundColor = "lightgreen";
        arraySeventhSquares[4].style.backgroundColor = "slategray";
        arraySeventhSquares[5].style.backgroundColor = "lightgreen";
        arraySeventhSquares[7].style.backgroundColor = "lightgreen";
        arrayDots[0].style.display = "none";
        arrayDots[8].style.display = "none";
        arrayDots[1].style.display = "none";
        arrayDots[9].style.display = "none";
        arrayDots[2].style.display = "none";
        arrayDots[10].style.display = "none";
        arrayDots[3].style.display = "none";
        arrayDots[11].style.display = "none";
        arrayDots[4].style.display = "none";
        arrayDots[12].style.display = "none";
        arrayDots[5].style.display = "none";
        arrayDots[13].style.display = "none";
        arrayDots[7].style.display = "none";
        arrayDots[15].style.display = "none";
    }
}

function showDots8() {
    arraySeventhSquares[7].style.backgroundColor = "#4682B4";
    arrayDots[7].style.display= "inline";
    arrayDots[15].style.display = "inline";
}

function dontShowDots8(event) {
    var x = event.buttons;
    if (x == 1) {
        arraySeventhSquares[0].style.backgroundColor = "slategray";
        arraySeventhSquares[1].style.backgroundColor = "lightgreen";
        arraySeventhSquares[2].style.backgroundColor = "slategray";
        arraySeventhSquares[3].style.backgroundColor = "lightgreen";
        arraySeventhSquares[4].style.backgroundColor = "slategray";
        arraySeventhSquares[5].style.backgroundColor = "lightgreen";
        arraySeventhSquares[6].style.backgroundColor = "slategray";
        arrayDots[0].style.display = "none";
        arrayDots[8].style.display = "none";
        arrayDots[1].style.display = "none";
        arrayDots[9].style.display = "none";
        arrayDots[2].style.display = "none";
        arrayDots[10].style.display = "none";
        arrayDots[3].style.display = "none";
        arrayDots[11].style.display = "none";
        arrayDots[4].style.display = "none";
        arrayDots[12].style.display = "none";
        arrayDots[5].style.display = "none";
        arrayDots[13].style.display = "none";
        arrayDots[6].style.display = "none";
        arrayDots[14].style.display = "none";
    }
} 

html code:

<!DOCTYPE html>
<html>
    <head>
        <title>Title of the document</title>
        <link rel="stylesheet" href="style.css">
    </head>

    <body>
        <div id="board">
          
            <!-- 1st row -->
            <div><img src="images/black_rook.png" draggable="true" ondragstart="drag(event)" height="65px" width="65px"></div>
            <div><img src="images/black_knight.png" draggable="true" ondragstart="drag(event)" height="65px" width="65px"></div>
            <div><img src="images/black_bishop.png" draggable="true" ondragstart="drag(event)" height="65px" width="65px"></div>
            <div><img src="images/black_queen.png" draggable="true" ondragstart="drag(event)" height="65px" width="65px"></div>
            <div><img src="images/black_king.png" draggable="true" ondragstart="drag(event)" height="65px" width="65px"></div>
            <div><img src="images/black_bishop.png" draggable="true" ondragstart="drag(event)" height="65px" width="65px"></div>
            <div><img src="images/black_knight.png"  draggable="true" ondragstart="drag(event)"height="65px" width="65px"></div>
            <div><img src="images/black_rook.png" draggable="true" ondragstart="drag(event)" height="65px" width="65px"></div>
          
            <!-- 2nd row-->
            <div><img src="images/black_pawn.png" draggable="true" ondragstart="drag(event)" class="black_pawns" height="65px" width="65px"></div>
            <div><img src="images/black_pawn.png" draggable="true" ondragstart="drag(event)" class="black_pawns" height="65px" width="65px"></div>
            <div><img src="images/black_pawn.png" draggable="true" ondragstart="drag(event)" class="black_pawns" height="65px" width="65px"></div>
            <div><img src="images/black_pawn.png" draggable="true" ondragstart="drag(event)" class="black_pawns" height="65px" width="65px"></div>
            <div><img src="images/black_pawn.png" draggable="true" ondragstart="drag(event)" class="black_pawns" height="65px" width="65px"></div>
            <div><img src="images/black_pawn.png" draggable="true" ondragstart="drag(event)" class="black_pawns" height="65px" width="65px"></div>
            <div><img src="images/black_pawn.png" draggable="true" ondragstart="drag(event)" class="black_pawns" height="65px" width="65px"></div>
            <div><img src="images/black_pawn.png" draggable="true" ondragstart="drag(event)" class="black_pawns" height="65px" width="65px"></div>
            
            <!-- 3rd row empty-->
            <div class="empty_squares"></div>
            <div class="empty_squares"></div>
            <div class="empty_squares"></div>
            <div class="empty_squares"></div>
            <div class="empty_squares"></div>
            <div class="empty_squares"></div>
            <div class="empty_squares"></div>
            <div class="empty_squares"></div>
          
            <!-- 4th row empty-->
            <div class="empty_squares"></div>
            <div class="empty_squares"></div>
            <div class="empty_squares"></div>
            <div class="empty_squares"></div>
            <div class="empty_squares"></div>
            <div class="empty_squares"></div>
            <div class="empty_squares"></div>
            <div class="empty_squares"></div>
          
            <!-- 5th row empty-->
            <div class="empty_squares5" ondrop="drop(event)" ondragover="allowDrop(event)"><img src="images/greenDot.png" height="40px" width="60px"></div>
            <div class="empty_squares5" ondrop="drop(event)" ondragover="allowDrop(event)"><img src="images/greenDot.png" height="40px" width="60px"></div>
            <div class="empty_squares5" ondrop="drop(event)" ondragover="allowDrop(event)"><img src="images/greenDot.png" height="40px" width="60px"></div>
            <div class="empty_squares5" ondrop="drop(event)" ondragover="allowDrop(event)"><img src="images/greenDot.png" height="40px" width="60px"></div>
            <div class="empty_squares5" ondrop="drop(event)" ondragover="allowDrop(event)"><img src="images/greenDot.png" height="40px" width="60px"></div>
            <div class="empty_squares5" ondrop="drop(event)" ondragover="allowDrop(event)"><img src="images/greenDot.png" height="40px" width="60px"></div>
            <div class="empty_squares5" ondrop="drop(event)" ondragover="allowDrop(event)"><img src="images/greenDot.png" height="40px" width="60px"></div>
            <div class="empty_squares5" ondrop="drop(event)" ondragover="allowDrop(event)"><img src="images/greenDot.png" height="40px" width="60px"></div>
          
            <!-- 6th row empty-->
            <div class="empty_squares5" ondrop="drop(event)" ondragover="allowDrop(event)"><img src="images/greenDot.png" height="40px" width="60px"></div>
            <div class="empty_squares5" ondrop="drop(event)" ondragover="allowDrop(event)"><img src="images/greenDot.png" height="40px" width="60px"></div>
            <div class="empty_squares5" ondrop="drop(event)" ondragover="allowDrop(event)"><img src="images/greenDot.png" height="40px" width="60px"></div>
            <div class="empty_squares5" ondrop="drop(event)" ondragover="allowDrop(event)"><img src="images/greenDot.png" height="40px" width="60px"></div>
            <div class="empty_squares5" ondrop="drop(event)" ondragover="allowDrop(event)"><img src="images/greenDot.png" height="40px" width="60px"></div>
            <div class="empty_squares5" ondrop="drop(event)" ondragover="allowDrop(event)"><img src="images/greenDot.png" height="40px" width="60px"></div>
            <div class="empty_squares5" ondrop="drop(event)" ondragover="allowDrop(event)"><img src="images/greenDot.png" height="40px" width="60px"></div>
            <div class="empty_squares5" ondrop="drop(event)" ondragover="allowDrop(event)"><img src="images/greenDot.png" height="40px" width="60px"></div>
          
            <!-- 7th row-->
            <div class="seventh_squares"><img src="images/white_pawn.png" draggable="true" id="item1" ondragstart="drag(event)" onmousedown="dontShowDots(event)" onclick="showDots()" height="65px" width="65px"></div>
            <div class="seventh_squares"><img src="images/white_pawn.png" draggable="true" id="item2" onmousedown="dontShowDots2(event)" onclick="showDots2()" height="65px" width="65px"></div>
            <div class="seventh_squares"><img src="images/white_pawn.png" draggable="true" id="item3" onmousedown="dontSD3(event)" onclick="showDots3()" height="65px" width="65px"></div>
            <div class="seventh_squares"><img src="images/white_pawn.png" draggable="true" id="item4" onmousedown="dontShowDots4(event)" onclick="showDots4()" height="65px" width="65px"></div>
            <div class="seventh_squares"><img src="images/white_pawn.png" draggable="true" id="item5" onmousedown="dontShowDots5(event)" onclick="showDots5()" height="65px" width="65px"></div>
            <div class="seventh_squares"><img src="images/white_pawn.png" draggable="true" id="item6" onmousedown="dontShowDots6(event)" onclick="showDots6()" height="65px" width="65px"></div>
            <div class="seventh_squares"><img src="images/white_pawn.png" draggable="true" id="item7" onmousedown="dontShowDots7(event)" onclick="showDots7()" height="65px" width="65px"></div>
            <div class="seventh_squares"><img src="images/white_pawn.png" draggable="true" id="item8" onmousedown="dontShowDots8(event)" onclick="showDots8()" height="65px" width="65px"></div>
          
            <!-- 8th row-->
            <div><img src="images/white_rook.png" draggable="true" ondragstart="drag(event)" height="65px" width="65px"></div>
            <div><img src="images/white_knight.png" draggable="true" ondragstart="drag(event)" height="65px" width="65px"></div>
            <div><img src="images/white_bishop.png" draggable="true" ondragstart="drag(event)" height="65px" width="65px"></div>
            <div><img src="images/white_queen.png" draggable="true" ondragstart="drag(event)" height="65px" width="65px"></div>
            <div><img src="images/white king.png" draggable="true" ondragstart="drag(event)" height="65px" width="65px"></div>
            <div><img src="images/white_bishop.png" draggable="true" ondragstart="drag(event)" height="65px" width="65px"></div>
            <div><img src="images/white_knight.png" draggable="true" ondragstart="drag(event)" height="65px" width="65px"></div>
            <div><img src="images/white_rook.png" draggable="true" ondragstart="drag(event)" height="65px" width="65px"></div>

            <script src="interactive.js"></script>
        </div>
    </body>
</html> 
2
  • 1
    Ok I will go ahead and do that. @anatolhiman Commented Aug 29, 2021 at 20:58
  • A next challenge for you to improve the code could be to create a helper function that iterates (map, for, forEach etc.) over your arrayDots[i] and sets style=display none only on those that are appropriate in each main function. You could for example use consts that keep an array of numbers representing each group of numbers you need to use as i's in each arrayDot[i] to get to the correct dot. This way you'll be able to reuse some code and just change the numbers you use to select each dot. You could also use if/else/switch logic if there is any particular logic to which dots you select. Commented Aug 29, 2021 at 21:06

2 Answers 2

2

Concur with @pelmetennui in that it is best to segregate the internal representation of the game board from the presentation tier. Towards that end, have framed out a representation of the board, which can act as a springboard for generating the HTML DOM representation...

Note that in this particular representation, the board is a single dimensional array and includes a twice thick border. This is a standard board representation technique for some enthusiast chess engines, as it provides an easy method for generating moves, including Knights which can make an initial jump of 2 files and/or 2 ranks, and hence the twice thick border. (See the pieces object which lists the possible moves as relative changes to the current index in the single dimensional array.) This border then obviates the need to check array boundaries when generating candidate move lists...

let pieces = {

  'k': { name: 'King',   color: 'Black', moves: [ +1, -11, -12, -13, -1, +11, +12, +13 ],   moveMax: 1, img: 'black_king.png' },
  'q': { name: 'Queen',  color: 'Black', moves: [ +1, -11, -12, -13, -1, +11, +12, +13 ],   moveMax: 7, img: 'black_queen.png' },
  'r': { name: 'Rook',   color: 'Black', moves: [ +1, -12, -1, +12 ],                       moveMax: 7, img: 'black_rook.png' },
  'b': { name: 'Bishop', color: 'Black', moves: [ -11, -13, +11, +13 ],                     moveMax: 7, img: 'black_bishop.png' },
  'n': { name: 'Knight', color: 'Black', moves: [ -10, -23, -25, -14, +10, +23, +25, +14 ], moveMax: 1, img: 'black_knight.png' },
  'p': { name: 'Pawn',   color: 'Black', moves: [ +12 ],                                    moveMax: 1, specialRank: 7, img: 'black_pawn.png'},
  'K': { name: 'King',   color: 'White', moves: [ +1, -11, -12, -13, -1, +11, +12, +13 ],   moveMax: 1, img: 'white_king.png' },
  'Q': { name: 'Queen',  color: 'White', moves: [ +1, -11, -12, -13, -1, +11, +12, +13 ],   moveMax: 7, img: 'white_queen.png' },
  'R': { name: 'Rook',   color: 'White', moves: [ +1, -12, -1, +12 ],                       moveMax: 7, img: 'white_rook.png' },
  'B': { name: 'Bishop', color: 'White', moves: [ -11, -13, +11, +13 ],                     moveMax: 7, img: 'white_bishop.png' },
  'N': { name: 'Knight', color: 'White', moves: [ -10, -23, -25, -14, +10, +23, +25, +14 ], moveMax: 1, img: 'white_knight.png'  },
  'P': { name: 'Pawn',   color: 'White', moves: [ -12 ],                                    moveMax: 1, specialRank: 2, img: 'white_pawn.png'}

}

class ChessBoard {
  constructor( FEN ) {
    this.board = [
      'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X',
      'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X',
      'X', 'X', '.', '.', '.', '.', '.', '.', '.', '.', 'X', 'X',
      'X', 'X', '.', '.', '.', '.', '.', '.', '.', '.', 'X', 'X',
      'X', 'X', '.', '.', '.', '.', '.', '.', '.', '.', 'X', 'X',
      'X', 'X', '.', '.', '.', '.', '.', '.', '.', '.', 'X', 'X',
      'X', 'X', '.', '.', '.', '.', '.', '.', '.', '.', 'X', 'X',
      'X', 'X', '.', '.', '.', '.', '.', '.', '.', '.', 'X', 'X',
      'X', 'X', '.', '.', '.', '.', '.', '.', '.', '.', 'X', 'X',
      'X', 'X', '.', '.', '.', '.', '.', '.', '.', '.', 'X', 'X',
      'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X',
      'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'
    ];
    
    if ( FEN ) {
      this.setToFen( FEN );
    }
  
  }
  
  print() {
    let charBoard = '';
    for ( let rank = 8; 1 <= rank; rank-- ) {
      charBoard += ' ';
      for ( let file = 1; file <= 8; file++ ) {
        charBoard += this.board[ this.fileRankToIndex( file, rank ) ] + ' ';
      }
      charBoard += '\n';
    }
    return charBoard;
  }
  
  
  setToFen( FEN ) {
    // See https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation
    let file = 1;
    let rank = 8;
    for ( let i = 0; i < FEN.length; i++ ) {
      let fenChar = FEN[ i ];
      if ( fenChar === ' ') {
        break;
      } else if ( fenChar === '/' ) {
        rank--;
        file = 1;
      } else if ( '0' <= fenChar && fenChar <= '8' ) {
        file = file + parseInt( fenChar );
      } else if ( pieces[ fenChar ] ) {
        this.board[ this.fileRankToIndex( file, rank ) ] = fenChar;
        file++;
      }
    }
  }
  
  indexToFileRank( i ) {
    return { file: i % 12 - 1, rank: 10 - ( i / 12 |0 ) };
  }
  
  fileRankToIndex( file, rank ) {
    return ( 24 + ( 8 - rank ) * 12 + file + 1 );
  }
  
}

// Let's test our ChessBoard class!

let cb = new ChessBoard( 'rnbqkbnr/pppppppp/8/8/8/2N5/PPPPPPPP/R1BQKBNR w KQkq - 0 1' );

console.log( cb.print() + '\n' );
console.log( `Piece at d1 (file 4, rank 1) is: ${cb.board[ cb.fileRankToIndex( 4, 1 ) ]}\n` );

console.log( `Where can N at c3 move to?` );
let c3 = cb.fileRankToIndex( 3, 3 );
let result = '';
debugger;
for ( let move of pieces[ 'N' ].moves ) {
  let possibleMove = c3 + move;
  if ( cb.board[ possibleMove ] === '.' ) {
    let square = cb.indexToFileRank( possibleMove );
    result += ' abcdefgh'[ square.file ] + square.rank + ' ';
  }
}
console.log( `N at c3 can move to: ${result}` );

Hopefully this gives you a head start reducing redundancy of code, and in writing a method to generate the HTML DOM, a method which should be similar to the print() method, except of course, generating <div> and <img...> nodes. Note that the pieces object contains attribute img referencing the PNG image name for the piece in question, which can be used to populate the <img src=... node when looping over the file and rank of this.board...

Sign up to request clarification or add additional context in comments.

1 Comment

Note: Tweaked setToFen method to terminate when finding space rather than period. Specifically, if ( fenChar === '.') was adjusted to if ( fenChar === ' ')...
2

You should separate your presentation and your model for the game. Your model for the game should encode the state of the board as some convenient data structure. There are multiple potential data structures that would make sense:

Using an object as a map:

const chessboard = {"A4": "BLACK_ROOK", "C6": "WHITE_KNIGHT"};

Using a multidimensional array:

const chessboard = [
    [null, null, null, "BLACK_KNIGHT", "BLACK_KING", null, null, null],
    [null, null, null, null, "BLACK_PAWN", 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, null, null, null],
    [null, null, null, null, null, null, null, null],
    [null, null, null, "WHITE_KNIGHT", "WHITE_KING", null, null, null],
];

Then you would define some function that converts the internal model of the game into a presentation, by e.g. iterating over these data structures and mapping them to divs.

This would let you parameterize calls from your various onmouseover/onclick functions, so that instead of calling separate functions, they'd call e.g. onmouseover = "hideDot('A4')" or onclick = "hideDot(3, 4)". You could then have a single function that implements whatever logic you need.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.