Newer
Older
2022-yuto / dice.js
@Yuto Togashi Yuto Togashi on 17 Nov 2022 2 KB add function judge
(() => {
  function shakeDice() {
    var count,  // 変化しているように見せる回数
    times = 0,  // サイコロを振った回数
    diceA = document.getElementById("diceA"),
    diceB = document.getElementById("diceB"),
    btnA = document.getElementById("btnA"),
    btnB = document.getElementById("btnB"),
    result = document.getElementById("result");
    btnR = document.getElementById("reset");
    /* サイコロの目が同じか違うか */
    function judge() {
        if (diceA.getAttribute("src") == diceB.getAttribute("src")) {   //サイコロの画像が同じとき
            result.innerHTML = "成功!!";
            result.setAttribute("class", "success");
            btnR.setAttribute("class", "");
        } else {
            result.innerHTML = "失敗…";
            result.setAttribute("class", "failure");
            btnR.setAttribute("class", "");
        }
    }
    /* サイコロを振る */
    function shake(dice){
        var num = Math.floor(Math.random()*6)+1;    // 1から6までのランダムな数字
        sai = "image/dice" + num + ".png";  // 画像ファイル名生成
        dice.setAttribute("src", sai);
    }
    /* サイコロのアニメーション */
    function anime(dice, btn){
        if(count > 20){	// 20回ほど振る
            count = 0;
            times++;
            if (times == 2) {
                judge();
            }
            return 0;
        }
        shake(dice);
        count++;
        setTimeout(() => {
            anime(dice, btn)
        }, 200);	// 200ミリ秒間隔で表示切り替え
    }
    /* スタートボタン */
    function start(dice, btn){
        count = 0;
        btn.disabled = "true"; // ボタンを使用不可にする
        anime(dice, btn);
    }
    /* リセットボタン */
    function reset() {
        times = 0;
        diceA.setAttribute("src", "image/dice1.png");
        diceB.setAttribute("src", "image/dice1.png");
        btnA.disabled = ""
        btnB.disabled = ""
        result.innerHTML = "";
        btnR.setAttribute("class", "none");
    }
    btnA.addEventListener("click", () => {
        start(diceA, btnA);
    });
    btnB.addEventListener("click", () => {
        start(diceB, btnB);
    });
    btnR.addEventListener("click", () => {
        reset();
    });
  }
  document.addEventListener("DOMContentLoaded", shakeDice, false);
})();