Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Chessboard with Javascript

I am creating a chessboard with Javascript. I already managed to create the board itself, but I'm having trouble giving every field its fitting class (black or white).

I managed to correctly assign the classes for the first row, but am having trouble with the rest of the board. I know there are probably easier solutions to this.

<!DOCTYPE html>
<html>
<head>
    <title>Chess</title>
    <link rel="stylesheet" type="text/css" href="assets/css/chess.css">
    <script type="text/javascript" src="assets/js/lib/jquery.js"></script>

</head>
<body onload="initGame()">
<h1>Chess</h1>
<div id="board">

</div>

<script type="text/javascript" src="assets/js/chess.js"></script>
</body>
</html>
body{
    text-align: center;
    background-color: rgb(30, 30, 30);
}
#board{
    margin: 0 auto;
    width: 800px;
    height: 800px;
    background-color: white;
}
#board div{
    width: 100px;
    height: 100px;
    float: left;
}
.white{
    background-color: white;
    border: 1px solid black;
}
.black{
    background-color: black;
    border: 1px solid white;
}
const board = [];
const boardElement = document.getElementById("board");


function initGame(){
    for(var y = 0; y < 8; y++){
        var row = [];
        for(var x = 0; x < 8; x++){
            var cell = {};
            cell.element = document.createElement("div")
            boardElement.appendChild(cell.element);
            row.push(cell);
        }
        board.push(row);
    }
    $("#board div").addClass("field white");
    for(var i = 0; i < board.length * 8; i++){
        if((i % 7) == 0 && i != 0){
            $(".field")[i].className = "field black";
            i++;
        }
        else if((i % 7) == 0){
            i++;
        }
        $(".field")[i].className = "field black";
        i++;
    }
    startGame();
}
function startGame(){

}

The current output:

like image 395
Roehrich1004 Avatar asked Sep 07 '19 19:09

Roehrich1004


People also ask

Can you make chess with JavaScript?

chess. js is a Javascript chess library that is used for chess move generation/validation, piece placement/movement, and check/checkmate/stalemate detection - basically everything but the AI. chess. js has been extensively tested in node.

What is chessboard JS?

chessboard. js is a standalone JavaScript Chess Board. It is designed to be "just a board" and expose a powerful API so that it can be used in different ways.


3 Answers

You can cut down your initGame logic to just add white class when y and x are either both odd or both even. You can do this by y%2 == x%2. You won't need the extra for loop.!

function initGame(){
    for(var y = 0; y < 8; y++){
        var row = [];
        for(var x = 0; x < 8; x++){
            var cell = {};
            cell.element = document.createElement("div")
            if(y%2 ==  x%2)
            {
                cell.element.className = "field white";
            }
            else 
            {
                cell.element.className = "field black";
            }
            boardElement.appendChild(cell.element);
            row.push(cell);
        }
        board.push(row);
    }

    startGame();
}
like image 63
Karthik Avatar answered Oct 23 '22 23:10

Karthik


Not sure what other functionality you'd need, but for generating the board you could do something like this:

const md = () => document.createElement('div');

function makeBoard (container, length = 8) {
	for ( let i = 0; i < length; i++) {
  	const row = md();
		Array.from({length}).forEach(() => row.appendChild(md()));
    container.appendChild(row);
  }
}

makeBoard(document.getElementById('board'));
#board > div {
  display: flex;
  min-height: 32px;
}

#board > div > div {
  flex: 0 0 32px;
  background: tomato;
}

#board > div:nth-child(even) > div:nth-child(even) {
  background: bisque;
}

#board > div:nth-child(odd) > div:nth-child(odd) {
  background: bisque;
}
<div id="board"></div>
like image 35
ray hatfield Avatar answered Oct 23 '22 23:10

ray hatfield


A solution with swapping array:

var colors = ['white', 'black'];

$("#board div").each(function(i) {
  if((i % 2) == 0)
    $(this).addClass(colors[0]);
  else 
    $(this).addClass(colors[1]);
  if([8,16,24,32,40,48,56,64].indexOf((i + 1)) > -1)
    colors = colors.reverse();
});

const board = [];
const boardElement = document.getElementById("board");


function initGame(){
    for(var y = 0; y < 8; y++){
        var row = [];
        for(var x = 0; x < 8; x++){
            var cell = {};
            cell.element = document.createElement("div")
            boardElement.appendChild(cell.element);
            row.push(cell);
        }
        board.push(row);
    }
    
    $("#board div").addClass('field');
    
    var colors = ['white', 'black'];
    
    $("#board div").each(function(i) {
      if((i % 2) == 0)
        $(this).addClass(colors[0]);
      else 
        $(this).addClass(colors[1]);
      if([8,16,24,32,40,48,56,64].indexOf((i + 1)) > -1)
        colors = colors.reverse();
    });
    
    // startGame();
}
body{
    text-align: center;
    background-color: rgb(30, 30, 30);
}
#board{
    margin: 0 auto;
    width: 400px;
    height: 400px;
    background-color: white;
}
#board div{
    width: 50px;
    height: 50px;
    float: left;
    box-sizing: border-box;
}
.white{
    background-color: white;
    border: 1px solid black;
}
.black{
    background-color: black;
    border: 1px solid white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
    <title>Chess</title>
    <link rel="stylesheet" type="text/css" href="assets/css/chess.css">
    <script type="text/javascript" src="assets/js/lib/jquery.js"></script>

</head>
<body onload="initGame()">
<h1>Chess</h1>
<div id="board">

</div>

<script type="text/javascript" src="assets/js/chess.js"></script>
</body>
</html>
like image 32
ztom Avatar answered Oct 24 '22 00:10

ztom