The first function makes 2 players
const Player = (name,mark) => {
return {name, mark}
}
let player1 = Player('Player 1', '<div>X</div>');
let player2 = Player('Player 2', '<div>O</div>');
The rest of the code which runs the game
const gameBoard = (() => {
board = [["","",""],["","",""],["","",""]];
let whichPlayer = getCurrentPlayer();
const AddEventListeners = (() => {
$('.square').click(function(event) {
if(win == false && this.innerHTML == ''){
console.log(this)
let a = addToBoard(whichPlayer()).bind(this);
a(this.id)}
})
$('.restart').click(function(e) {
board = [["","",""],["","",""],["","",""]];
$('.square').empty()
btnDiv.style.display = "none";
$('.winnermsg').hide();
win = false;
})
})();
function getCurrentPlayer(){
let currentPlayer = player1
function getPlayer() {
if(currentPlayer === player1){
currentPlayer = player2
crntPlayer = player1
return player1
}else{
currentPlayer = player1
crntPlayer = player2
return player2
}
}
return getPlayer;
}
function addToBoard(currentPlayer) {
return function(square){
this.innerHTML = currentPlayer.mark
let coords = square.split('')
board[coords[0]][coords[1]] = currentPlayer.mark
checkWin()
}
}
function declareWinner(tie = false){
win = true;
$('.winnermsg').show();
if(tie){
$('.winnermsg').html(`<p>Tie game, try again</p>`);
}else{
$('.winnermsg').html(`<p>Congratulations, ${crntPlayer.name} you have won</p>`);
}
if (crntPlayer == player1){whichPlayer();}
btnDiv.style.display = "grid"
}
function checkWin(){
//check horizontal
for(let i=0;i<board.length;i++){
array=[]
if(board[i].every(x => x == crntPlayer.mark )){
declareWinner()
}
//check vertical
for(let j=0;j<board[i].length;j++){
array.push(board[j][i])
if(array.every(x=>x == crntPlayer.mark && array.length == 3)){
declareWinner()
}
}
}
//check diags
newArray=[]
newArray.push(board[0][0],board[1][1],board[2][2])
if(newArray.every(x => x == crntPlayer.mark)){
declareWinner()
}
newArray=[]
newArray.push(board[0][2],board[1][1],board[2][0])
if(newArray.every(x => x == crntPlayer.mark)){
declareWinner()
}
//check tie
newArray=board.reduce((a,b) => a.concat(b))
if(!newArray.includes('')){declareWinner('tie')}
}
})();
So I just add event listeners to each div and if it's empty it changes the innerHTML to the player's mark and adds that mark to the board array and then checks if there's a winner.
I feel like it's not very well organized but i'm not sure how it would best be improved.