I am having a hard time figuring out why this code is working the way it is. Below, I have all of the code that produces my tic tac toe game. The game works as intended until we come to a full board that SHOULD result in a win for either 'O' or 'X'. My current logic sometimes will work as intended and pick the correct winner but a majority of the time, it will produce a 'DRAW', even if the last move on the last square should result in a win. Given the if/else if chain, I don't see how that would work? The applicable if/else if statement is the second set.
Here is my code:
$(document).ready(function() {
let addX = "<h1>X</h1>"
let addO = "<h1>O</h1>"
let turn = []
let board = [$("#one"), $("#two"), $("#three"), $("#four"), $("#five"),$("#six"), $("#seven"), $("#eight"), $("#nine")]
let combos = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [6,4,2]]
for (let i = 0; i < board.length; i++){
board[i].click(function(){
if (turn.length === 0){
turn.push(board.indexOf(board[i].html(addX)) + "X")
} else if (turn.length % 2 !== 0 && board[i].html() === ''){
turn.push(board.indexOf(board[i].html(addO)) + "O")
} else if (turn.length % 2 === 0 && board[i].html() === ''){
turn.push(board.indexOf(board[i].html(addX)) + "X")
}
for(let i = 0; i < combos.length; i++){
if (turn.includes(combos[i][0] + 'O') && turn.includes(combos[i][1] + 'O') && turn.includes(combos[i][2] + 'O') ){
alert('O IS WINNER!')
setTimeout(function() {$("#ttt_table tbody tr td").html(""); }, 1500);
turn.length = 0
} else if(turn.join("").includes(combos[i][0] + 'X') && turn.join("").includes(combos[i][1] + 'X') && turn.join("").includes(combos[i][2] + 'X') ){
alert('X IS WINNER!')
setTimeout(function() {$("#ttt_table tbody tr td").html(""); }, 1500);
turn.length = 0
break
} else if (turn.length === 9){
alert('DRAW!')
setTimeout(function() {$("#ttt_table tbody tr td").html(""); }, 1500);
turn.length = 0
}
}
})
}
});
Here is a codepen to test out the game itself:
https://codepen.io/tylerp33/pen/NeOxyY
Basically, shouldn't the game see there's a winning combo in:
else if(turn.join("").includes(combos[i][0] + 'X') && turn.join("").includes(combos[i][1] + 'X') && turn.join("").includes(combos[i][2] + 'X')
before the last
else if (turn.length === 9) produces a 'DRAW'?
Thanks for your help!
Aucun commentaire:
Enregistrer un commentaire