I write the game "Life". How to find adjacent cells?

window.onload = function() { var cell = [ 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1 ]; var tableContainer = document.querySelector("table"); var tbodyContainer = tableContainer.querySelector("tbody"); var createdRow = document.createElement("tr"); cell.forEach(function(Onecell, i, arr) { if (i % 4 === 0) { tbodyContainer.appendChild(createdRow); createdRow = document.createElement("tr"); } tbodyContainer.appendChild(createdRow); var createdCell = document.createElement("td"); if (Onecell === 0) { createdCell.classList.add("dead"); } else { createdCell.classList.add("live"); } // добавляем только что созданый элемент в дерево DOM createdRow.appendChild(createdCell); }); } 
 td { margin: 10px; border: 2px solid black; } tr { display: table-row; vertical-align: inherit; border-color: inherit; } .live, .dead { width: 30px; height: 30px; } .live { background-color: #adff2f; } .dead { background-color: #ffffff; } table { border: 4px double black; } 
 <table> <tbody> </tbody> </table> 

  • What cells are we talking about? What is the problem? - Grundy
  • I want all neighboring cells to see each other. - spmpl
  • one
    why do you think that now they do not see each other? - Grundy
  • one
    How then to implement the algorithm. So that cells die from overpopulation or shortage? - spmpl
  • very simple, you first need to decide on the algorithm itself - Grundy

2 answers 2

for a one-dimensional array (I don't know how to say it) ... then to the matrix. function to find all neighboring cells at a specified chec range (index around which to search, distance, matrix width, height), for example, index 2, matrix 4 by 4, depth 1. result [1,3,5,6,7]

 function chec(indx, size, width, height) { var s = [], x = indx % width, y = indx / width | 0; size = size || 1; for (var i = y - size; i <= y + size; i++) { for (var k = x - size; k <= x + size; k++) { var num = k + i * width; i > -1 && i < height && k > -1 && k < width && num < (i * width + width) && num != indx && s.push(num) } } return s } console.log(chec(2, 1, 4, 4) ); 

  • And you can make it easier? Difficult to understand your code. - spmpl

Use the new variable.

 elem.querySelectorAll(value) 

and already work on it. as elem.querySelector(value) interacts with only 1 (first found = [0]) element.

  • Where to use this new variable ? - Grundy