//javaScriptで数字タッチゲームを作成する
//class構文で処理をひとまとまりにして管理する
//classはBoardクラスとPanelクラスを作成して処理を分けて考える※チーム開発する上で役割を決めておく
//Boardクラスは4つ持ったボードを表している
//Panelクラスはパネルがどのように配置するか担っている。Panelクラスはパネルの内に責任をもつ
class Panel {
//インスタンスした際の初期化処理
constructor(game) {
this.game = game;
//li要素を生成
this.el = document.createElement('li'); //プロパティをthis.el
this.el.classList.add('pressed') //pressedクラスを付与
this.el.addEventListener('click',() => {
this.check();
})
}
getEl() {
return this.el
}
//パネルクラスを外してパネルにランダムで数字を入れる
activate(num) {
this.el.classList.remove('pressed');
this.el.textContent = num
}
//panelボタンを押す際に0から押すようにif分で条件分岐する
check() {
if(currentNum === parseInt(this.el.textContent, 10)) {
this.el.classList.add('pressed')
currentNum++
}
if(currentNum === 4) { //currentNumが総パネル数と同じになったらタイマーを止める
clearTimeout(timeoutId)
}
}
}
class Board {
//インスタンスの初期化設定
constructor(game) {
this.game = game
//各パネルを配列に格納するための空の配列を作成
this.panels = [];
//空の配列にパネルを格納するためにfor分でループを回す
for(let i = 0; i< 4; i++) {
this.panels.push(new Panel(this.game)) //Panelクラスでパネルを用意する
}
this.setup()
}
setup() {
const board = document.getElementById('board');
this.panels.forEach(panel => {
board.appendChild(panel.getEl())
})
}
//btnをクリックした際にboardの中のパネルのメソッドを呼び出す
activate() {
const nums = [0,1,2,3]; //パネルにつける番号を配列で保持
this.panels.forEach(panel => {
const num = nums.splice(Math.floor(Math.random() * nums.length),1)[0];
panel.activate(num);
})
}
}
// const panel = new Panel();
class Game {
constructor() {
this.board = new Board(this);
//ボタンのクリック時に今、どのボタンが押されているかを管理するための変数
this.currentNum = undefined
//タイマー処理を実装
this.startTime = undefined
//タイマーを止める変数
this.timeoutId = undefined
//ボタンクリック操作でパネルを押す処理
//ボタン要素を取得
const btn = document.getElementById('btn');
btn.addEventListener('click', () => {
this.startClick()
})
}
startClick() {
this.board.activate();
this.currentNum = 0;
if(typeof this.timeoutId !== 'undefined') {
clearTimeout(this.timeoutId)
}
this.startTime = Date.now()
this.runTimer()
}
runTimer() {
const timer = document.getElementById('timer')
this.elapsedTime = ((Date.now() - this.startTime) / 1000).toFixed(2);
timer.textContent =this.elapsedTime;
this.timeoutId = setTimeout(() => {
this.runTimer()
},10)
}
}
new Game()