8パズルひな型(セルの移動のみ)

JavaScript

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <script src="main.js"></script>
    <title>8puzzuleひな型</title>
</head>
<body>
    <div class="board">
        <div class="cell" data-number="0">1</div>
        <div class="cell" data-number="1">2</div>
        <div class="cell" data-number="2">3</div>
        <div class="cell" data-number="3">4</div>
        <div class="cell" data-number="4">5</div>
        <div class="cell" data-number="5">6</div>
        <div class="cell" data-number="6">7</div>
        <div class="cell" data-number="7">8</div>
        <div class="cell" data-number="8"></div>
    </div>
</body>
</html>

style.css

/* style.css */
@charset "utf-8";

*{
    margin: 0;
    padding: 0;
}

body{
    margin: 1em;
    display: flex;
    justify-content: center;
}

.board{
    display: grid;
    grid-template-rows: 100px 100px 100px;
    grid-template-columns: 100px 100px 100px;
}

.cell{
    background: #555;
    border: solid 1px #999;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #aaa;
}

main.js

// -----------------------------
// 8パズルひな形 main.js
// -----------------------------

let cells = null;   // マス目

// セルを入れ替える
function swapCell(x, y){
    console.log("入れ替え.");
    [ cells[x].textContent, cells[y].textContent ] = [ cells[y].textContent, cells[x].textContent ]
}

// セルが入れ替え可能かチェックする
function checkCell(number){
    // 上下左右が空いていれば入れ替え
    if(number >= 3 && cells[number-3].textContent === ""){
        swapCell(number, number-3);
    }
    if(number <= 5 && cells[number+3].textContent === ""){
        swapCell(number, number+3);
    }
    if(number % 3 != 2 && cells[number+1].textContent === ""){
        swapCell(number, number+1);
    }
    if(number % 3 != 0 && cells[number-1].textContent === ""){
        swapCell(number, number-1);
    }
}

// 起動時の処理
window.addEventListener("load", ()=>{
    // 全てのマス目を取得
    cells = document.querySelectorAll(".cell");

    // セルのイベントを設定
    for(let cell of cells){

        cell.addEventListener("click", (elm)=>{
            // セルの番号を取得(data-numberプロパティ)
            const number = Number(elm.currentTarget.dataset.number);
            console.log("cells[" + number + "] Click.");

            // セルが入れ替え可能か?
            checkCell(number);
        });
    }
});

コメント