104 lines
2.6 KiB
JavaScript
104 lines
2.6 KiB
JavaScript
import { Controller } from "https://unpkg.com/@hotwired/stimulus/dist/stimulus.js";
|
|
|
|
export class GameController extends Controller {
|
|
static targets = [
|
|
"clock",
|
|
"score",
|
|
"problem",
|
|
"indicators",
|
|
"answer",
|
|
];
|
|
|
|
start() {
|
|
this.startGame();
|
|
this.element.classList.remove('hidden');
|
|
}
|
|
|
|
submitAnswer(ev) {
|
|
ev.preventDefault();
|
|
|
|
this._checkAnswer();
|
|
}
|
|
|
|
startGame() {
|
|
this._clock = 120;
|
|
this._score = 0;
|
|
|
|
this._generateProblem();
|
|
this._startClock();
|
|
|
|
this._updateClock();
|
|
}
|
|
|
|
_startClock() {
|
|
this._clockInterval = window.setInterval(() => {
|
|
if (this._clock <= 0) {
|
|
this._gameOver();
|
|
return;
|
|
}
|
|
|
|
this._clock -= 1;
|
|
this._updateClock();
|
|
}, 1000);
|
|
}
|
|
|
|
_gameOver() {
|
|
window.clearInterval(this._clockInterval);
|
|
|
|
this.element.classList.add('hidden');
|
|
window.dispatchEvent(new CustomEvent("endGame"));
|
|
}
|
|
|
|
_generateProblem() {
|
|
const num1 = Math.floor(Math.random() * 99) + 1;
|
|
const num2 = Math.floor(Math.random() * 99) + 1;
|
|
|
|
this._problem = [num1, num2];
|
|
this._answer = num1 + num2;
|
|
|
|
this.indicatorsTarget.classList.remove('right', 'wrong');
|
|
this.problemTarget.innerHTML = '';
|
|
|
|
for (let i = 0; i < this._problem.length; i++) {
|
|
const div = document.createElement('div');
|
|
|
|
if (i === this._problem.length - 1) {
|
|
div.textContent = '+ ' + this._problem[i];
|
|
} else {
|
|
div.textContent = this._problem[i];
|
|
}
|
|
this.problemTarget.appendChild(div);
|
|
}
|
|
|
|
this.answerTarget.disabled = false;
|
|
this.answerTarget.value = "";
|
|
this.answerTarget.focus();
|
|
}
|
|
|
|
_checkAnswer() {
|
|
let isRight = parseInt(this.answerTarget.value) === this._answer;
|
|
|
|
this.answerTarget.disabled = true;
|
|
|
|
let delay = 500;
|
|
|
|
if (isRight) {
|
|
this._score += 1;
|
|
this.indicatorsTarget.classList.add('right');
|
|
} else {
|
|
this.indicatorsTarget.classList.add('wrong');
|
|
this.answerTarget.value = this._answer;
|
|
delay = 800;
|
|
}
|
|
|
|
this.scoreTarget.textContent = this._score;
|
|
|
|
window.setTimeout(() => { this._generateProblem(); }, delay);
|
|
}
|
|
|
|
_updateClock() {
|
|
let m = Math.floor(this._clock / 60);
|
|
let s = this._clock % 60;
|
|
this.clockTarget.textContent = `${m}:${s < 10 ? '0' : ''}${s}`;
|
|
}
|
|
} |