I have 9 different divs in an array each attached to a forEach and event listener. I'm wondering how I would console.log a string only after three of the buttons are clicked. If this helps you understand my question better, I'm making tic tac toe, and need an alert when someone wins from clicking in the intended areas. Thanks!
HTML
<div class="game-container">
<div class="cell" id="0"></div>
<div class="cell" id="1"></div>
<div class="cell" id="2"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
</div>
const cell = document.querySelectorAll('.cell');
player1 = 'X'
player2 = 'O'
let currentPlayer = player1
cell.forEach(element => {
element.addEventListener('click', function (e) {
if (currentPlayer === player1) {
element.style.backgroundColor='red'
currentPlayer = player2;
} else {
currentPlayer = player1;
element.style.backgroundColor='Blue'
}
})
})
Create on object that will store game state in a 3*3 array and will be notified on each click. After that he change his state (add one clicked cell) and will check if somebody win. If yes - log
You should create a state for winning cases in the game and check if user-selected cells are matching anything in a winning case.. maybe this repo is useful for you. https://github.com/AhmedMalekX/tic-tac-toe-game