We Blog Weblog

8パズル

Web

2025年2月25日

みなさんこんにちは。
ケミストのWeb担当みやのです。

「Web」記事では、これまでに得たWebに関する知識を記録として残していきたいと思います。

今回は前回の「15パズル」をもとに「8パズル」を作ってみました。順番逆じゃね?

こんな感じになればクリアです。さあレッツプレイ!

おめでとう!完成です!

HTML

まずは枠組みを作っていきます。

<div id="eight">
  <div class="tile" id="tile-0"></div>
  <div class="tile" id="tile-1"></div>
  <div class="tile" id="tile-2"></div>
  <div class="tile" id="tile-3"></div>
  <div class="tile" id="tile-4"></div>
  <div class="tile" id="tile-5"></div>
  <div class="tile" id="tile-6"></div>
  <div class="tile" id="tile-7"></div>
  <div class="tile empty" id="tile-8"></div>
</div>
<button id="shuffle" onclick="shuffleAndSetColors()">シャッフル</button>
<h4 id="victory-message">おめでとう!完成です!</h4>

タイルは9個(最後の1個は空白タイル)にします。

CSS

CSSは以下の通りです。

#eight {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
  gap: 5px;
  width: 100%;
  max-width: 300px;
  aspect-ratio: 1 / 1;
  margin: 20px auto;
}
.tile {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #4CAF50;
  color: white;
  border-radius: 5px;
  cursor: pointer;
  transition: transform 0.2s ease;
  width: 100%;
  height: 100%;
  font-size: 3rem;
  font-weight: 700;
}
.empty {
  background-color: transparent;
  cursor: default;
}
#victory-message {
  margin-top: 20px;
  display: none;
}

3×3で配置します。

JavaScript

スクリプトは以下の通りです。

function shuffleTiles() {
  const order = Array.from({ length: 9 }, (_, i) => i);
  let emptyRow = 2, emptyCol = 2;
  for (let i = 0; i < 1000; i++) {
    const direction = ['up', 'down', 'left', 'right'];
    const moves = direction.map(dir => getMove(emptyRow, emptyCol, dir)).filter(move => move !== null);
    const move = moves[Math.floor(Math.random() * moves.length)];
    if (move) {
      const [newRow, newCol, index] = move;
      [order[emptyRow * gridSize + emptyCol], order[newRow * gridSize + newCol]] = [order[newRow * gridSize + newCol], order[emptyRow * gridSize + emptyCol]];
      emptyRow = newRow;
      emptyCol = newCol;
    }
  }
  order.forEach((value, index) => {
    if (value < 8) {
      tiles.eq(index).text(value + 1).removeClass('empty');
      tiles.eq(index).css('background-color', tileColors[value]);
    } else {
      tiles.eq(index).text('').addClass('empty');
      emptyIndex = index;
      tiles.eq(index).css('background-color', 'transparent');
    }
  });
  victoryMessage.hide();
  stopFireworks();
}
function getMove(row, col, direction) {
  switch (direction) {
    case 'up': return row > 0 ? [row - 1, col, (row - 1) * gridSize + col] : null;
    case 'down': return row < gridSize - 1 ? [row + 1, col, (row + 1) * gridSize + col] : null;
    case 'left': return col > 0 ? [row, col - 1, row * gridSize + col - 1] : null;
    case 'right': return col < gridSize - 1 ? [row, col + 1, row * gridSize + col + 1] : null;
    default: return null;
  }
}
function setRandomTileColor() {
  const colors = ['#007bff', '#28a745', '#dc3545', '#ffc107'];
  const randomColor = colors[Math.floor(Math.random() * colors.length)];
  tiles.each(function(index) {
    if (!$(this).hasClass('empty')) {
      tileColors[index] = randomColor;
      $(this).css('background-color', randomColor);
    } else {
      $(this).css('background-color', 'transparent');
    }
  });
}
function shuffleAndSetColors() {
  shuffleTiles();
  setRandomTileColor();
}
function slideTile(index) {
  if (isAnimating) return;
  const [emptyRow, emptyCol] = [Math.floor(emptyIndex / gridSize), emptyIndex % gridSize];
  const [tileRow, tileCol] = [Math.floor(index / gridSize), index % gridSize];
  const isAdjacent = (Math.abs(emptyRow - tileRow) === 1 && emptyCol === tileCol) || (Math.abs(emptyCol - tileCol) === 1 && emptyRow === tileRow);
  if (isAdjacent) {
    isAnimating = true;
    const tileToMove = tiles.eq(index);
    const emptyTile = tiles.eq(emptyIndex);
    tileToMove.animate({ 
      left: `${(emptyCol - tileCol) * 100}%`,
      top: `${(emptyRow - tileRow) * 100}%`
    }, 200, function() {
      emptyTile.text(tileToMove.text()).removeClass('empty').css('background-color', tileToMove.css('background-color'));
      tileToMove.text('').addClass('empty').css('background-color', 'transparent');
      emptyIndex = index;
      tileToMove.css({ left: 0, top: 0 });
      isAnimating = false;
      if (isWinningCondition()) {
        setTimeout(() => {
          victoryMessage.show();
          fireworks();
        }, 200);
      }
    });
    tileToMove.css({
      position: 'relative',
      left: 0,
      top: 0
    }).css('z-index', 1);
  }
}
function isWinningCondition() {
  for (let i = 0; i < 8; i++) {
    if (parseInt(tiles.eq(i).text()) !== i + 1) {
      return false;
    }
  }
  return true;
}
tiles.each(function(index) {
  $(this).on('click', () => slideTile(index));
});
$(document).ready(function() {
  setRandomTileColor();
  shuffleTiles();
});

数値をちょこっと変えるだけですね。

まとめ

なんかこっちの方が難しい気がするのは気のせいでしょうか。

この記事を書いた人
みやの
Web・DTP担当

Contact Us

ご意見、ご相談、料金のお見積もりなど、お気軽にお問い合わせください。

お問い合わせはこちら

TOP