Skip to content

Instantly share code, notes, and snippets.

@geotrev
Last active March 3, 2020 01:26
Show Gist options
  • Save geotrev/d7f7e65ec09b5771a8930b44fef80dd6 to your computer and use it in GitHub Desktop.
Save geotrev/d7f7e65ec09b5771a8930b44fef80dd6 to your computer and use it in GitHub Desktop.
Tic Tac Toe
class TicTacToe {
constructor() {
this.handleMouseEnter = this.handleMouseEnter.bind(this)
this.handleMouseLeave = this.handleMouseLeave.bind(this)
this.handleClick = this.handleClick.bind(this)
this.handleResetClick = this.handleResetClick.bind(this)
this.tiles = []
this.start()
}
start() {
this.loadBoard()
this.player = "X"
this.tiles = Array.apply(null, document.querySelectorAll(".board-tile"))
this.tiles.forEach(button => {
button.addEventListener("click", this.handleClick)
button.addEventListener("mouseenter", this.handleMouseEnter)
button.addEventListener("mouseleave", this.handleMouseLeave)
})
const replayButton = document.getElementById("reset")
replayButton.addEventListener("click", this.handleResetClick)
}
loadboard() {
// add styles
const styleTag = document.createElement("style")
styleTag.textContent = `
.board {
display: flex;
flex-wrap: wrap;
width: 12rem;
height: 12rem;
}
.board-tile {
width: 4rem;
height: 4rem;
font-size: 2rem;
font-family: Comic Sans MS;
background: #efefef;
}
.board-tile:not(:disabled):hover {
color: gray;
}
.board-tile:disabled {
color: black;
}
.board-reset {}
`
document.head.appendChild(styleTag)
// add html
document.body.innerHTML = `
<h3 id="turn">
<span data-player="X"></span>'s turn
</h3>
<div id="container" class="board">
<button class="board-tile"></button>
<button class="board-tile"></button>
<button class="board-tile"></button>
<button class="board-tile"></button>
<button class="board-tile"></button>
<button class="board-tile"></button>
<button class="board-tile"></button>
<button class="board-tile"></button>
<button class="board-tile"></button>
</div>
<button id="reset" class="board-reset">Replay</button>
`
}
// handlers
handleResetClick() {
this.tiles.forEach(button => {
button.textContent = ''
button.disabled = false
})
}
handleClick(event) {
event.target.textContent = this.player
event.target.disabled = true
this.player = this.player === "X" ? "O" : "X"
}
handleMouseEnter(event) {
event.target.textContent = this.player
}
handleMouseLeave(event) {
event.target.textContent = ''
}
// getters and setters
get player() {
const playerEl = document.querySelector("[data-player]")
const player = playerEl.getAttribute("data-player")
return player
}
set player(value) {
document.querySelector("[data-player]").textContent = value
document.querySelector("[data-player]").setAttribute("data-player", value)
}
}
const Game = new TicTacToe()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment