<html lang="en">
    <script src="main.js"></script>
    <style>
      .card {
        width: 80px;
        height: 80px;
        font-size: 40px;
        border: 2px solid;
        color: #000;
        text-align: center;
      }
    </style>
  </head>
  <body>
    <table id="table"></table>
  </body>
</html>
const cards = [];

function init() {
  let table = document.getElementById("table");

  for (let i = 0; i < 4; i++) {
    let yokoretu = document.createElement("tr");
    for (let j = 0; j < 4; j++) {
      let itimai = document.createElement("td");
      let index = i * 4 + j;
      itimai.index = index;
      itimai.value = index;
      itimai.textContent = index === 0 ? " " : index;
      itimai.className = "card";
      itimai.onclick = moveCard;
      cards.push(itimai);
      yokoretu.appendChild(itimai);
    }
    table.appendChild(yokoretu);
  }

  for (let i = 0; i < 500; i++) {
    moveCard({ target: { index: Math.floor(Math.random() * 16) } });
  }
}

function moveCard(e) {
  let i = e.target.index;

  if (i - 4 >= 0 && cards[i - 4].value === 0) {
    change(i, i - 4);
  } else if (i + 4 < 16 && cards[i + 4].value === 0) {
    change(i, i + 4);
  } else if (i % 4 !== 0 && cards[i - 1].value === 0) {
    change(i, i - 1);
  } else if (i % 4 !== 3 && cards[i + 1].value === 0) {
    change(i, i + 1);
  }
}

function change(i, j) {
  let tmp = cards[i].value;
  cards[i].textContent = cards[j].textContent;
  cards[i].value = cards[j].value;
  cards[j].textContent = tmp;
  cards[j].value = tmp;
}

window.addEventListener("load", init);

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.