如何制作嵌套循环来制作棋盘?

时间:2017-02-15 22:59:54

标签: javascript jquery loops nested

嘿,伙计们我是JS的新手,我想学习这门语言,但有一点我坚持,那就是让嵌套循环工作,这样我就可以制作一个棋盘游戏出现。这是我到目前为止所得到的:

while (y <= 7) {
  if (y % 2 == 0) {
    document.write("<div class=sq2> </div>")
      ++y;
  } else {
    document.write("<div class=sq1> </div>")
      ++y;
  }
}

sq1制作白色瓷砖 sq2制作黑色瓷砖。 每一行他们应该是不同的,这就是为什么我得到了IF声明。 这从左到右完美地排成一行。 但我似乎无法使嵌套循环工作,从而从上到下产生8行。这就是我所拥有的:

var x = 0;
var y = 0;

while (x <= 8) {
  while (y <= 7) {
    if (y % 2 == 0) {
      document.write("<div class=sq2> </div>")
        ++y;
    } else {
      document.write("<div class=sq1> </div>")
        ++y;
    }
  }
  ++x;
}

由于

TheOne

4 个答案:

答案 0 :(得分:1)

我使用了<table>(是的,我完全清楚使用<table>会让小猫哭泣)。棋子在加载时与#chessBoard一起生成。它们由一组字体符号组成,每个字符符号代表黑色或白色棋子。详细信息在源中进行了评论。源代码位于 PLUNKER 和一个代码段。

&#13;
&#13;
<!DOCTYPE html>
<html>

<head>
  <style>
    body {
      overflow-y: scroll;
    }
    /* BOARD */
    /* 
    || Despite what everyone says not to use the <table> for
    || layout purposes, I'm doing it anyway. The display:
    || table-* properties are useful but takes too much effort 
    || to use on larger projects.
    */
    
    table#ChessBoard {
      width: 420px;
      height: 420px;
      table-layout: fixed;
      border: 3px ridge gray;
      border-collapse: separate;
      border-spacing: 2px;
    }
    
    tr.rank {
      width: 420px;
      height: 45px;
    }
    
    td.cell {
      width: 45px;
      height: 45px;
      border-left: 1px solid red;
      border-right: 1px solid red;
      border-top: 1px solid blue;
      border-bottom: 1px solid blue;
    }
    
    .white {
      background: white;
      color: red;
    }
    
    .black {
      background: black;
      color: blue;
    }
    /* This is a number/letter in the top left corner of 
    || every cell.
    */
    
    sup {
      text-align: left;
      vertical-align: top;
      font-size: 8px;
      font-weight: 700;
      font-family: Verdana;
      position: relative;
      z-index: 1;
      line-height: .3
    }
    /* PIECES */
    /*
    || This is the common styles for a game piece
    */
    
    div.piece.piece {
      max-width: 45px;
      max-height: 45px;
      font-size: 35px;
      font-weight: 100;
      text-align: center;
      vertical-align: middle;
      display: block;
      line-height: .3;
      margin: 0 auto;
      background: transparent;
      padding-bottom: 5px;
    }
    /*~~~~~~~~~~< PIECES >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
    /* These classes each have a unicode of a chess piece
    || in the content of an :after pseudo-element.
    */
    
    .wK:after {
      content: '\2654';
    }
    
    .wQ:after {
      content: '\2655';
    }
    
    .wR:after {
      content: '\2656';
    }
    
    .wB:after {
      content: '\2657';
    }
    
    .wN:after {
      content: '\2658';
    }
    
    .wP:after {
      content: '\2659';
    }
    
    .bK:after {
      content: '\265a';
    }
    
    .bQ:after {
      content: '\265b';
    }
    
    .bR:after {
      content: '\265c';
    }
    
    .bB:after {
      content: '\265d';
    }
    
    .bN:after {
      content: '\265e';
    }
    
    .bP:after {
      content: '\265f';
    }
  </style>
</head>

<body>
  <table id="chessBoard"></table>

  <script>
    /* BOARD */
    var brd = document.getElementById("chessBoard");
    /*
    || 4 Arrays that have the initial position of each chess piece
    || pre-arranged.
    */
    var black = ['bR', 'bN', 'bB', 'bQ', 'bK', 'bB', 'bN', 'bR'];
    var bPawn = ['bP', 'bP', 'bP', 'bP', 'bP', 'bP', 'bP', 'bP'];

    var white = ['wR', 'wN', 'wB', 'wQ', 'wK', 'wB', 'wN', 'wR'];
    var wPawn = ['wP', 'wP', 'wP', 'wP', 'wP', 'wP', 'wP', 'wP'];

    // First a rank (a row on a chessboard) must be made
    for (var i = 0; i < 8; i++) {

      var rank = brd.insertRow(i);
      rank.classList.add('rank');
      rank.id = 8 - i;

      for (var j = 0; j < 8; j++) {
        /*
        || On every iteration, a <td> is inserted...
        || ...then it's colors are given if it's odd/even.
        */
        var cell = rank.insertCell(j);
        var color = parseInt((i + j) % 2, 10) === 0 ? 'white' : 'black';
        /* The array is for establishing a horizontal guide for
        || the chessboard. 
        || The <sup> is for that previously mentioned feature 
        || of coordinates on each square.
        || The cell is further prepared with classes, id, etc.
        || The last line of this block calls a function
        || called pieces.
        */
        var col = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];
        var coord = document.createElement('sup');
        coord.textContent = parseInt(8 - i, 10) + col[j];
        cell.appendChild(coord);
        cell.classList.add('cell');
        cell.classList.add(color);
        pieces(i);
      }
    }
    /* pieces will:
    || check to see of we are on the 2 ranks for each side.
    || If so, then it determines which rank of pieces needs
    || to be created.
    */
    function pieces(i) {
      var row = brd.rows[i].querySelectorAll('td');
      var piece = document.createElement('div');
      piece.setAttribute('draggable', true);
      switch (i) {
        case 0:
          piece.classList.add('piece');
          piece.classList.add('black');
          piece.classList.add(black[j]);
          cell.appendChild(piece);
          break;
        case 1:
          piece.classList.add('piece');
          piece.classList.add('black');
          piece.classList.add('wP');
          cell.appendChild(piece);
          break;
        case 6:
          piece.classList.add('piece');
          piece.classList.add('white');
          piece.classList.add('bP');
          cell.appendChild(piece);
          break;
        case 7:
          piece.classList.add('piece');
          piece.classList.add('white');
          piece.classList.add(white[j]);
          cell.appendChild(piece);
          break;
        default:
          break;
      }
    }
    /* This is a group of drag and drop functions that are not          
    || finished but it's a good start should you decide that drag
    || and drop is needed.
    is 
    function drag(ev) {
      ev.dataTransfer.setData("text/html", ev.target.id);
    }

    function dropHandler(ev) {
      ev.preventDefault();
      var id = ev.dataTransfer.getData("text/html");

      if (id == "srcMove" && ev.target.id == "destMove") {
        ev.target.appendChild(document.getAttribute(id));
      }
    }
  */
  </script>
</body>

</html>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

注意: CSS不是最好的(我讨厌CSS)。所以CSS就是你的问题!

var board = document.getElementById("board");  // get the board element

for(var i = 0; i < 8; i++) {                   // to create rows
  var row = document.createElement("div");     // create this row
  for(var j = 0; j < 8; j++) {                 // to create cells
    var cell = document.createElement("div");  // create this cell
    if(i % 2 == j % 2)                         // do the math
      cell.className = "white";
    else
      cell.className = "black";
    row.appendChild(cell);                     // add this cell to the row
  }
  board.appendChild(row);                      // add this row to the board
}
#board > div {
  height: 20px;
}

.white, .black {
  display: inline-block;
  width: 20px;
  height: 20px;
}

.white {
  background-color: white;
}

.black {
  background-color: black;
}
<div id="board"></div>

答案 2 :(得分:0)

您需要重置y,以便在外循环的第一次迭代后再次执行内循环。

var x = 0;
var y = 0;

while (x <= 8) {
    while (y <= 7) {
        if (y % 2 == 0) {
            document.write("<div class=sq2> </div>")
            ++y;
        }
        else {
            document.write("<div class=sq1> </div>")
            ++y;
       }
   }
   y = 0;
   ++x;
}

答案 3 :(得分:0)

大部分内容都是通过CSS完成的,即你必须告诉每个div不要占用整行(显示:内联块)并给它们一个宽度和高度:

.sq1 {
    width: 20px;
    height: 20px;
    background-color: white;
    display: inline-block;
}
.sq2 {
    width: 20px;
    height: 20px;
    background-color: black;
    display: inline-block;
}

你想要添加某种中断(你可以使用&#34; br&#34;标签,但还有其他方法)每次&#39; x&#39;循环重新启动,以便可以进行后续行。

您还需要将y重置为

var x = 0;

// declare y here since there is no "block scope" prior to es6.
var y;

// stop at 7 since you are starting at 0.
while (x <= 7) {
  // reset y to 0 each time the 'x' loop restarts.
  y = 0;

  // add a break dom node to create each new row.
  document.write('<br/>');

  while (y <= 7) {
    if (y % 2 == 0) {
      // classes should be in quotes.
      document.write('<div class="sq2"></div>');
    } else {
      document.write('<div class="sq1""></div>');
    }

    // you only need to include this once since both paths of the if-conditional were calling it.
    ++y;
  }
  ++x;
}

这将为您提供8行交替的彩色方块,但每行将完全相同。您现在需要考虑每隔一行以替换颜色开始的事实。要做到这一点,您可以使用% 2只返回0或1并采用y加x的模数这一事实。对于第一行,这将给出0 + 0 = 0 =&gt; &#34; SQ2&#34;对于第一个正方形并且1 + 0 = 1 =&gt; &#34; SQ1&#34;对于第二行的第一个方格。

 if ((y + x) % 2 == 0) {...}

Live Demo