Newer
Older
2023-Yoshimiya / mogura.js
@YOSHIMIYA YOSHIMIYA on 17 Nov 2023 2 KB add comment
#!/usr/bin/env js

(() => {
    var timer = null, count = 10; point = 0; ana=6;
    var hit = ana+1; hit_new = ana+1; //存在しないdivs添字にしたくて+1
    var msgArea = null; ptArea = null;
    function countdown() {
	console.log('countdown');
	msgArea.innerText = `残り ${count}秒`;
	if (count<=0) {
	    stop();
	} else {
	    timer = setTimeout(countdown, 1000);   //1秒待つ
	}
	count --;
    }
    function start() {
	console.log('start');
	startButton.disabled = true;
	rand();
	countdown();
    }
    function stop() {
	console.log('stop');
	alert("しゅーーりょーー");
	ptArea.innerText = `今回のスコア: ${point}回`; 
	ptArea.style.textDecoration = "underline";
	//atari.innerHTML = ""     //もぐら画像削除
    }
    function whack() {     // whack-a-mole(英):モグラ叩き
	console.log('whack');
	if (count>=0) {     // 制限時間すぎたら動かさない
	    point ++;
	    ptArea.innerText = `現在: ${point}回`;
	    ptArea.style.textDecoration = "none";
	    atari.innerHTML = "";     //もぐら画像削除
	    atari.removeEventListener('click', whack);   //イベントリスナー削除
	    // ここで削除しないと一度atariになった空のdivを押してもatari判定になる
	    rand(); 
	}
    }
    function rand() {
	console.log('rand');
	var divs = document.querySelectorAll("div");
	hit_new = Math.floor(Math.random()*ana);
	if (count>=0) {   // 制限時間すぎたら動かさない
	    if (hit == hit_new) {   //数字がかぶったらやり直し
		rand();
	    } else {
		hit = hit_new;
		atari = divs[hit];
		atari.innerHTML = "<img src='mogura3.png'>"; //もぐら画像表示
		atari.addEventListener('click', whack);   //イベントリスナー追加
	    }
	console.log(`${hit}`);
	}
    }
    function init() {
	console.log('init');
	var divs = document.querySelectorAll("div");
	//for (i=0;i<ana;i++) {divs[i].innerText=`${i}`;}   //divs添字確認用
	msgArea = document.getElementById("message");
	ptArea = document.getElementById("point");
	startButton = document.getElementById("start");
	msgArea.innerText = `制限時間: ${count}秒`;
	startButton.addEventListener('click', start);
    };

    document.addEventListener('DOMContentLoaded', init);
})();