how do i reset the state of the board after a tictactoe game?
i want to fire the startGame() function where it will clear out all the x’s and O’s of the board whenever i hit the restart button.
or do you have any other cleaner approach to do so? thank you so much
const squares = document.querySelectorAll('.grid') const XCLASS = "x" const OCLASS = "o" const textElementWin = document.getElementById('xowinMessage') const screenElementWin = document.querySelector('.winningScreen') const textElementDraw = document.getElementById('drawMessage') const screenElementDraw = document.querySelector('.drawScreen') const restartButtons = document.querySelectorAll('.button') const winCombinations=[ [0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6] ] let circleturn squares.forEach(square => { square.addEventListener('click', handleEvent, {once:true}) }) function handleEvent(event){ const cell = event.target const currentPlayer = circleturn ? OCLASS : XCLASS placeItem(cell,currentPlayer) if (checkWin(currentPlayer)){ screenElementWin.classList.add('show') textElementWin.innerText = `${currentPlayer} wins!` }else if(checkDraw()){ screenElementDraw.classList.add('show') textElementDraw.innerText = "It's a tie!" } else{ swapTurn() } } restartButtons.forEach(eachbutton => { eachbutton.addEventListener('click', ()=>{ screenElementWin.classList.remove('show') startGame() }) })
Advertisement
Answer
Bear in mind that element.className
is a space separated list of class names.
Assumption: at the beginning of a game, all cells in the grid have the same class name string. This may be the empty string, a single class name, or a space separated list of class names that do not include the values of
OCLASS
orXCLASS
.const squares = document.querySelectorAll('.grid'); const EMPTY_CLASS = squares[0].className; // empty cell class ...
Suggestion: don’t process clicks on cells that have already been clicked.
const cell = event.target; if( cell.className != EMPTY_CLASS) { return; } placeItem(cell,currentPlayer) ...
Reset the
className
property of all cells toEMPTY_CLASS
in thestartGame
function. This function can also be responsible for ensuring winning notifications are removed and notifying players of who goes first (‘x’ or ‘o’).While you could inline the
startGame
code, it may be clearer to separate it from the event handler in the same manner as functionsplaceItem
andswapTurn
have been separated.