Open lanbau opened 8 years ago
// fix click outside grid bug if (tile.className !== 'tile') return // fix stealing grids if (tile.textContent) return
return
statement. Refactor to avoid duplicated statements.function isValidClickTarget (tile) { return isTile(tile) && isEmpty(tile) }
function isTile (tile) { return tile.className !== 'tile' }
function isEmpty(tile) { return !!tile.textContent }
// ...
if (!isValidClickTarget(tile)) return
if (currentPlayer === 'one') { tile.textContent = 'x' currentPlayer = 'two' } else { tile.textContent = 'o' currentPlayer = 'one' }
var currentPlayerSymbol = currentPlayer === 'one' ? 'x' : 'o'
var nextPlayerName = currentPlayer === 'one' ? 'two' : 'one'
tile.textContent = currentPlayerSymbol
currentPlayer = nextPlayerName
var tile11 = document.querySelector('.row:nth-of-type(1) .tile:nth-of-type(1)').textContent // ...
function getTile (x, y) {
var rowSelector = '.row:nth-of-type(' + x + ')'
var columnSelector = '.tile:nth-of-type(' + y + ')'
var tileSelector = rowSelector + ' ' + columnSelector
return document.querySelector(tileSelector).textContent
}
var tile11 = getTile(1, 1)
// ... repeat
Then continue to refactor any repeated similar code.
var rowx1 = (tile11 === 'x' && tile12 === 'x' && tile13 === 'x') var rowx2 = (tile21 === 'x' && tile22 === 'x' && tile23 === 'x') var rowx3 = (tile31 === 'x' && tile32 === 'x' && tile33 === 'x') if (rowx1 || rowx2 || rowx3) { console.log('Player X Wins!') document.getElementById('score').innerHTML = 'Player X Wins!' var ans = prompt('Type yes To Play Again') if (ans === 'yes') { window.location.reload() } }
@cbas