-3


I'm having some problems with my assignment, which was to make chess pieces move freely across the board without the use of ids in native javascript. I have managed to set them on board and have also tried with getting coordinates from clicking on a piece, then getting coordinates from clicking somewhere on board and assigning the chosen piece those newly acquired coordinates, but nothing seems to work correctly.
I'd really appreciate some help :)

<head>
<meta charset="utf-8">
<style>
body 
    {
    padding: 20px;
    }
h1
    {
    text-align: center
    }
table 
    {
    margin-left:auto;
    margin-right:auto;
    border: 4px solid black;
    border-collapse: collapse;
    }
td
    {
    width: 40px; 
    height: 40px;
    text-align: center;
    }
.up
    {
    border-top-style: hidden;
    border-left-style: hidden;
    border-right-style: hidden;
    border-bottom-style: solid;
    background-color: white;
    font-weight: bold
    }
.down
    {
    border-top-style: solid;
    border-left-style: hidden;
    border-right-style: hidden;
    border-bottom-style: hidden;
    background-color: white;
    font-weight: bold
    }
.left
    {
    border-top-style: hidden;
    border-left-style: hidden;
    border-right-style: solid;
    border-bottom-style: hidden;
    background-color: white;
    font-weight: bold
    }
.right
    {
    border-top-style: hidden;
    border-left-style: solid;
    border-right-style: hidden;
    border-bottom-style: hidden;
    background-color: white;
    font-weight: bold
    }
.gray
    {
    background-color: gray;
    }
.white
    {
    background-color: white;
    }
</style>
</head>
<body>
<script> // chessboard
document.write("<h1>Game</h1>");
document.write("<table><tr class=up><td></td>");
for (var k=0; k<=7; k++){ //letters on top, 97 is a, 104 is h
    document.write("<td>" + String.fromCharCode(k+97) + "</td>");
}
document.write("</tr>");
for (var j=8; j>0; j--){ //numbers dropping on sides
    document.write("<tr onclick='indexRow(this)'><td class=left>" + j + "</td>");
    if((j%2)==0){
        for (var i=0; i<8; i++){
            if((i%2)==0){
                document.write('<td onclick="indexCell(this)" class=white></td>'); //grab index
            } else{
                document.write('<td onclick="indexCell(this)" class=gray></td>'); //grab index
            };
        }
    } else{
        for (var i=0; i<8; i++){
            if((i%2)==0){
                document.write('<td onclick="indexCell(this)" class=gray></td>'); //grab index
            } else{
                document.write('<td onclick="indexCell(this)" class=white></td>'); //grab index
            };
        }
    };
    document.write("<td class=right>" + j + "</td>");
}
document.write("<tr class=down><td></td>");
for (var k=0; k<=7; k++){ //letters on top,97 is a, 104 is h
    document.write("<td>" + String.fromCharCode(k+97) + "</td>");
}
document.write("</tr></table>");

//pieces
var pieces=new Array( //pieces
                new Array(" "," "," "," "," "," "," "," "," "),
                new Array(" ","&#9814"," "," ","&#9812","&#9813","&#9815","&#9816","&#9814"),
                new Array(" ","&#9817","&#9817","&#9817"," "," ","&#9817","&#9817","&#9817"),
                new Array(" "," "," "," "," ","&#9817"," "," "," "),
                new Array(" "," "," "," ","&#9817"," "," "," "," "),
                new Array(" "," "," "," ","&#9816"," "," ","&#9815"," "),
                new Array(" "," "," ","&#9822"," "," "," "," "," "),
                new Array(" ","&#9823","&#9823","&#9823","&#9822","&#9823","&#9823","&#9823","&#9823"),
                new Array(" ","&#9820"," ","&#9821","&#9818","&#9819","&#9821"," ","&#9820")
            );

//sets up the board
function setUp(){
    for (i = 1; i <=8; i++){
        for (j = 1; j <=8; j++){
            document.getElementsByTagName('tr')[j].getElementsByTagName('td')[i].innerHTML = pieces[j][i];
        }
    }
}
setUp();
//attempts with making things move
var clickedon = false;
var save_x = 0;
var save_y = 0;
var piece = 0;
var _x = 0;
var _y = 0;

//gets cell index
function indexCell(x)
{
//alert("Cell index is: " + x.cellIndex);
_x = x.cellIndex;
if(clickedon == false)
{
if(pieces[_x][_y] != " ")
{  
    figura = pieces[_x][_y];
    save_x = _x;
    save_y = _y;
    clickedon = true;
    alert(piece)    
}  
}
else
{
if(pieces[_x][_y] == " ")
{
    pieces[save_x][save_y] = " ";
    pieces[_x][_y] = piece;
    setUp();
    clickedon = false
}       
}
}
//grabs row index
function indexRow(y){
//alert("Row index is: " + x.rowIndex);
_y = y.rowIndex;
}

</script>
</body>

Edit: I've now posted the version with my attempts at making pieces move and with numbers and letters around.

Resource2357
  • 3
  • 1
  • 3
  • 5
    "nothing seems to work correctly" isn't much of a hint. **HOW** does this not work? – Marc B Dec 17 '14 at 18:14
  • Look for css `position:absolute` in google. That would be required to move any DOM element to a given coordinate. This is all the help you can get with the code and information you have posted. – gp. Dec 17 '14 at 18:15
  • I don't see any code related to capturing clicks. – rfornal Dec 17 '14 at 18:15
  • do these pieces have to be animated or can they just disappear and reappear? – Adjit Dec 17 '14 at 18:18

2 Answers2

1

What you need to do is set an onclick event for each of the table cells, and have several global variables to hold the state of the chess board.

So here is what I would suggest trying:

var state = false //false if no piece has been selected
var currentPiece;
var currentCell;

var cells = document.getElementsByTagName("td"); 
for (var i = 0; i < cells.length; i++) { 
   cells[i].onclick = function(){
       getCell(this);
   };
}

function getCell(that) {
    if(!state) { //this means if the state is false (i.e. no piece selected
        state = true; //piece has been selected
        currentPiece = that.innerHTML; //get the current piece selected
        currentCell = that; //get the current cell selection
    }
    else { //else, you are moving a piece
        that.innerHTML = currentPiece; //Set the selected space to the piece that was grabbed
        currentCell.innerHTML = ""; //remove the piece from its old location
        state = false; //piece has been placed, so set state back to false
    }
}

Keep in mind this is just a rough layout of how I would handle this. I didn't take into account type of pieces or certain exceptions or anything like that.

Adjit
  • 10,134
  • 12
  • 53
  • 98
0

document.addEventListener("DOMContentLoaded", function () {
 var restartBtn = document.createElement("BUTTON"),
  mainDiv = document.createElement("DIV");

 restartBtn.innerHTML = "RESTART";
 restartBtn.id = "restartBtn";
 mainDiv.id = "chessboard";
 document.body.appendChild(restartBtn);
 document.body.appendChild(mainDiv);
 restartBtn.addEventListener("click", function () {
  reset();
 });

 function reset() {
  document.getElementById("chessboard").innerHTML = "";
  chessboardGame();
 }


 var chessboardGame = function () {
  for (var i = 1; i <= 8; i++) {
   var colorClass, child, grandChild;

   for (var j = 1; j <= 8; j++) {
    if ((i + j) % 2 === 0) {
     colorClass = "black";
    } else {
     colorClass = "white";
    }

    child = document.createElement("DIV");
    child.id = "column-" + i + j;
    grandChild = document.createElement("DIV");
    child.classList.add("box");
    child.classList.add(colorClass);
    child.classList.add("chess-column");
    grandChild.id = "coin-" + i + j;
    grandChild.classList.add("border-column");

    document.getElementById("chessboard").appendChild(child);


    if (i < 3) {
     document.getElementById("column-" + i + j).appendChild(grandChild);
     grandChild.classList.add("white-coin");
     grandChild.classList.add("black-border");
    } else if (i > 6) {
     document.getElementById("column-" + i + j).appendChild(grandChild);
     grandChild.classList.add("black-coin");
     grandChild.classList.add("white-border");
    }
   }

  }
  var chessColumns = document.getElementsByClassName("chess-column");
  for (var k = 0; k < chessColumns.length; k++) {

   chessColumns[k].onclick = function (e) {

    var el = chessColumns[0];
    while (el) {
     if (el.tagName === "DIV") {
      el.classList.remove("red-border");
     }
     el = el.nextSibling;
    }
    onColumnClick(e, this);
   };
  }

 };




 function onColumnClick(e, el) {
  el.classList.add("red-border");
  if (el.children[0]) {

   var currentActiveColumn = getActiveColumn();
   if (currentActiveColumn && currentActiveColumn !== el) {
    setActiveColumn(currentActiveColumn);
    setActiveCoin(currentActiveColumn.children[0]);
   } else {
    setActiveColumn(el);
    setActiveCoin(el.children[0]);
   }
  }

  var activeColumn = getActiveColumn(),
   activeCoin = getActiveCoin();

  if (activeColumn && activeColumn !== e.currentTarget) {
   if (Math.abs(activeColumn.offsetLeft - e.currentTarget.offsetLeft) > 80 || Math.abs(activeColumn.offsetTop - e.currentTarget.offsetTop) > 80) {
    alert("Move not allowed!");
    e.currentTarget.classList.remove("red-border");
    activeCoin.parentNode.classList.add("red-border");
   } else {
    moveCoin(activeColumn, el, activeCoin);

   }

  }
 }
 chessboardGame();
 function moveCoin(activeItem, targetItem, coin) {
  if (targetItem.firstChild) {
   var activeItemClassList = coin.classList,
    targetItemClassList = targetItem.firstChild.classList;

   if (activeItemClassList[1] === targetItemClassList[1]) {
    alert("Move not allowed!");
    targetItem.classList.remove("red-border");
    activeItem.classList.add("red-border");
    return;
   }
  }

  while (activeItem.firstChild) {
   activeItem.removeChild(activeItem.firstChild);
  }
  while (targetItem.firstChild) {
   alert("Good Move there!");
   targetItem.removeChild(targetItem.firstChild);
  }
  targetItem.appendChild(coin);
  setActiveColumn(targetItem);
 }

 function setActiveColumn(el) {
  this.activeColumn = el;
 }

 function getActiveColumn() {
  return this.activeColumn;
 }

 function setActiveCoin(coin) {
  this.activeCoin = coin;
 }

 function getActiveCoin() {
  return this.activeCoin;
 }
});
#chessboard {
    width: 640px;
    height: 640px;
    margin: 20px;
    border: 2px solid #333;
    position: relative;

}
.black {
    float: left;
    width: 80px;
    height: 80px;
    background-color: #333333;
    font-size:50px;
    text-align:center;
    display: table-cell;
    vertical-align:middle;
    cursor:pointer;
    font-weight:bold;
}
.white {
    float: left;
    width: 80px;
    height: 80px;
    background-color: #ffffff;
    font-size:50px;
    text-align:center;
    display: table-cell;
    vertical-align:middle;
    cursor:pointer;
}

.black-coin{
    background: black;
    width: 20px;
    height: 20px;
    cursor:pointer;
    position: relative;
    margin: 37% auto;
    transition: left .5s ease-in, top .5s ease-in;
}

.white-border{
    border: 2px solid white;
}

.white-coin{
    background: white;
    width: 20px;
    height: 20px;
    position: relative;
    margin: 37% auto;
    cursor:pointer;
    transition: left .5s ease-in, top .5s ease-in;
}

.black-border{
    border: 2px solid black;
}


.red-border{border: 2px solid red; box-sizing: border-box;}
<html lang="en">
<head>
    <link rel="stylesheet" href="css/style.css">
    <title>CHESSBOARD</title>

</head>
<script src="js/script.js"></script>
</html>
  • I Have created a chessboard with pieces using javascript,where you can move the pieces restricted to 2 steps and also i have created a restart button to move the pieces to there initial places on clicking the button i.e it restarts the game. – Priyanka Khatawate Mar 07 '19 at 10:30