Skip to content

Instantly share code, notes, and snippets.

@leaysgur
Created June 29, 2021 08:33
Show Gist options
  • Save leaysgur/249f7faeff917ed63f0744c3be9defd2 to your computer and use it in GitHub Desktop.
Save leaysgur/249f7faeff917ed63f0744c3be9defd2 to your computer and use it in GitHub Desktop.
High Low Game
class Game {
constructor({ $buttons, $result, $reset }) {
this.answer = null;
this.$buttons = $buttons;
this.$result = $result;
this.$reset = $reset;
}
start() {
this.answer = Math.floor((Math.random() * 5) + 1);
for (const $button of this.$buttons) {
$button.addEventListener("click", this._handleChoice.bind(this));
}
this.$result.textContent = "数字を選んでね";
this.$reset.addEventListener("click", this._handleReset.bind(this));
this.$reset.style.display = "none";
}
_handleChoice(ev) {
const value = Number(ev.currentTarget.textContent);
if (value < this.answer)
return this.$result.textContent = "Low";
if (value > this.answer)
return this.$result.textContent = "High";
this.$result.textContent = "正解!";
this.$reset.style.display = "block";
}
_handleReset() {
this.answer = Math.floor((Math.random() * 5) + 1);
this.$result.textContent = "数字を選んでね";
this.$reset.style.display = "none";
}
}
new Game({
$buttons: document.querySelectorAll("[data-js-button]"),
$result: document.querySelector("[data-js-result]"),
$reset: document.querySelector("[data-js-reset]"),
}).start()
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<button data-js-button>1</button>
<button data-js-button>2</button>
<button data-js-button>3</button>
<button data-js-button>4</button>
<button data-js-button>5</button>
<div data-js-result></div>
<button data-js-reset>リセット</button>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment