如何在javascript中创建扫雷板?

时间:2018-02-23 19:31:18

标签: javascript coordinates minesweeper

我正在使用div元素来创建扫雷板(8 x 8或其他)。我使用2 for循环来创建div的板

window.onload = function () {
    var container = document.getElementById('container');
    for (var i = 0; i < 8; i++) {
        for (var j = 0; j < 8; j++) {
            var elem = document.createElement('div');
            container.appendChild(elem);
            elem.className = 'myclass';
        }
        var breaker = document.createElement('div');
        container.appendChild(breaker);
        breaker.className = 'clear';
    }
}

一切都很好地显示但是我无法弄清楚如何跟踪每个瓦片(div)的位置,就像(x,y)坐标系一样,所以稍后我可以根据这些坐标来做游戏逻辑。 那么我该如何映射这个网格系统?

6 个答案:

答案 0 :(得分:1)

我为一个项目做了类似的工作,我使用数据属性来保存&#34;坐标&#34;并且每当我需要coords时都会引用data-attribute。这是我的功能。

根据maxRow和maxColumn

创建div
function createDivs(maxRow) {

var wrapperDiv = document.getElementById("mazeWrapper");
var rowDiv;
  for (var i=0; i < maxRow; i++) {
      var thisDiv = document.createElement("div");
  thisDiv.id = "mazeRow-" + i;
  thisDiv.className = "row";
    wrapperDiv.appendChild(thisDiv);
    for (var j=0; j < maxColumn; j++) {
      rowDiv = document.getElementById("mazeRow-" + i);
          var thisColumnDiv = document.createElement("div");
            thisColumnDiv.id = (i*maxRow)+j;               
            thisColumnDiv.className = "mazehole";
            rowDiv.appendChild(thisColumnDiv);
            //Adding in a html data-set to hold X,Y values for coordinate system
            var elemID = (thisColumnDiv.id).toString();
            var elem = document.getElementById(elemID);
            var att = document.createAttribute("data-coords");
            att.value = j+","+i;
            elem.setAttributeNode(att);
    }
  }  
}

答案 1 :(得分:1)

您可以使用Element.setAttribute MDN向元素添加自定义属性:

window.onload = function() {
  var container = document.getElementById('container');
  for (var i = 0; i < 8; i++) {
    for (var j = 0; j < 8; j++) {
      var elem = document.createElement('div');
      container.appendChild(elem);
      elem.className = 'myclass';
      elem.setAttribute('data-row', i);
      elem.setAttribute('data-col', j);
    }
    var breaker = document.createElement('div');
    container.appendChild(breaker);
    breaker.className = 'clear';
  }
}
.myclass{
    width: 20px;
    height: 20px;
    display: block;
    float: left;
    border: 1px solid red;
}
.clear{
  clear: left;
}
<html>
   <body>
       <div id="container">
       </div>
   </body>
</html>

答案 2 :(得分:1)

Yo可以将每个<div>元素(x和y坐标)的位置存储为&#39;数据&#39;属性。

示例:

elem.setAttribute('data-x', i);
elem.setAttribute('data-y', j);

您可以稍后使用getAttribute()来读取数据属性的值。

示例:

var x = elem.getAttribute('data-x');
var y = elem.getAttribute('data-y');

甚至以更简单的方式:

var x = elem.dataset.x;
var y = elem.dataset.y;

有关详细信息,请参阅MDN的Using data attributes

答案 3 :(得分:0)

在创建元素时,为每个元素指定一个唯一的名称。例如elem.id = 'row' + i + 'col' + j;

稍后您可以使用document.getElementById( ... )

答案 4 :(得分:0)

您可以使用它的坐标(x:y)作为每个块的id 你也可以用一个循环来编写它。

function blockClick(event){
  const selected = document.querySelector('#board .block.selected');
  if(selected != null){
    selected.classList.remove('selected');
  }
  document.querySelector('#coords').innerHTML = this.id;
  this.classList.add('selected');
}

function createBoard(cols, rows, blockSize){

  this._boardDom = document.getElementById('board');
  const noBlocks = cols * rows;
  
  for(let i = 0; i < noBlocks; i++){
    
    const block = document.createElement('div');
    const y = Math.ceil((i + 1)/rows);
    const x = (i + 1) - ((y - 1)*rows);
    block.id = `${x}:${y}`
    // block.innerHTML = `${x}:${y}`; // uncomment this to render x:y
    block.style.width = `${blockSize}px`;
    block.style.height = `${blockSize}px`;
    block.classList.add('block');
    
    block.addEventListener('click', blockClick);
    
    this._boardDom.appendChild(block);
  
  }
  
  this._boardDom.style.width = `${(blockSize*cols) + 2*(rows)}px`

}

createBoard(8,8,30)
#board{
  background-color: #eee;
  display: flex;
  flex-flow: row wrap;
}

#board .block{
  border: solid gray 1px;
}

#board .block.selected{
  border: solid gray 1px;
  background-color: red;
}
<div>
  Click on an element to see its coordinates
</div>
<div id="coords">
</div>
<div id="board"></div>

答案 5 :(得分:0)

我最近很开心创建这个,所以我想分享。我之所以使用SVG,是因为它们灵活且易于生成。

这些是BaseBoard循环:

https://bgwest.github.io/websweeper/

let ChatEngine = ChatEngineCore.create({
    publishKey: 'pub-c-bcc15813-f77d-4c89-a56a-18ac89bc8ad5',
    subscribeKey: 'sub-c-8a4f7218-67db-11e8-9683-aecdde7ceb31'
});

// Provide a unique id and other profile information for your user here.
const uuid = String(new Date().getTime());
ChatEngine.connect(uuid, {
    nickName: "YourUsersNickNameHere",
    favoriteColor: "Red"
});
ChatEngine.on('$.ready', function(data) {
    console.log('ChatEngine ready to go!');
});

https://github.com/bgwest/websweeper/blob/master/components/MakeBaseBoard.js

炸弹和炸弹然后放置在SetBoard.js中。其他模块(组件)可以在下面的链接中找到。

https://github.com/bgwest/websweeper