Решил втянуться в ООП, написал простейшие крестики-нолики, но с отсутствием опыта в этой области не знаю, что сделал не так, и как это улучшить. Надеюсь на вашу инспекцию ! ;)
class Game {
constructor() {
this.game = document.getElementById("game")
this.gameBlock = document.getElementsByClassName("game_block")
this.winnerDOM = document.getElementById("win")
this.btnReset = document.getElementById("btn-reset")
this.cloneGameBlock = new Array(this.gameBlock.length)
this.current = 0
}
calculateWinner(squares) {
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
]
for (let i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i]
if (
squares[a] &&
squares[a] === squares[b] &&
squares[a] === squares[c]
) {
return squares[a]
}
}
return null
}
cloneAnArray() {
for (let i = 0; i < this.cloneGameBlock.length; i++) {
this.cloneGameBlock[i] = this.gameBlock[i].innerHTML
}
}
winnerDom() {
if (this.calculateWinner(this.cloneGameBlock)) {
this.winnerDOM.style.display = "block"
this.winnerDOM.innerHTML = `Победитель: ${this.calculateWinner(this.cloneGameBlock)}`
}
}
resetGame() {
for (let i = 0; i < this.gameBlock.length; i++) {
this.gameBlock[i].innerHTML = ""
this.cloneGameBlock[i] = ""
}
this.winnerDOM.innerHTML = ""
this.current = 0
}
addCymeriad(index) {
if (!this.calculateWinner(this.cloneGameBlock)) {
if (!this.gameBlock[index].innerHTML) {
this.current++
this.current % 2 ?
(this.gameBlock[index].innerHTML = "X") :
(this.gameBlock[index].innerHTML = "0")
}
this.cloneAnArray()
}
this.winnerDom()
}
}
const game = new Game()
const {
gameBlock,
btnReset
} = game
for (let i = 0; i < gameBlock.length; i++) {
gameBlock[i].addEventListener("click", () => game.addCymeriad(i))
}
btnReset.addEventListener("click", () => game.resetGame())
#game {
width: 120px;
height: 120px;
margin: 30px auto;
outline: 1px solid black;
display: flex;
flex-wrap: wrap;
}
.game_block {
width: 40px;
height: 40px;
outline: 1px solid black;
transition: .4s;
text-align: center;
line-height: 40px;
font-size: 44px;
}
.game_block:hover {
background: rgb(241, 238, 238);
cursor: pointer;
}
#win {
display: none;
text-align: center;
}
.flex {
display: flex;
}
.flex-center {
justify-content: center;
}
<div id="game">
<div class="game_block"></div>
<div class="game_block"></div>
<div class="game_block"></div>
<div class="game_block"></div>
<div class="game_block"></div>
<div class="game_block"></div>
<div class="game_block"></div>
<div class="game_block"></div>
<div class="game_block"></div>
</div>
<h2 id='win'></h2>
<div class="flex flex-center">
<button id='btn-reset'>Начать заново</button>
</div>
Апостиль в Лос-Анджелесе без лишних нервов и бумажной волокиты
Основные этапы разработки сайта для стоматологической клиники
Продвижение своими сайтами как стратегия роста и независимости