$(document).ready(function() {
let gameArray = [];
let turn = 1;
let gameOver = false;
$("#turn").text(turn === 1 ? 'X' : 'O');
$(".smallbox").click(function() {
let squereIndex = $(this).attr('id').replace('square', '') - 1;
if (turn == 1 && !gameOver && gameArray[squereIndex] === undefined) {
$(this).text("X");
$(this).addClass("X");
turn = 2;
gameArray[squereIndex] = 1;
} else if (!gameOver && gameArray[squereIndex] === undefined) {
$(this).text("O");
$(this).addClass("O");
turn = 1;
gameArray[squereIndex] = -1;
}
checkWinner();
$("#turn").text(turn === 1 ? 'X' : 'O')
});
function checkWinner() {
let result;
//check Rows
for (let i = 0; i <= 6; i += 3) {
result = gameArray[i] + (gameArray[i + 1]) + (gameArray[i + 2]);
if (result === 3) {
$("#winner").text('X win');
gameOver = true;
}
if (result === -3) {
$("#winner").text('O win');
gameOver = true;
}
}
//check Columns
for (let i = 0; i <= 3; i++) {
result = gameArray[i] + (gameArray[i + 3]) + (gameArray[i + 6]);
if (result === 3) {
$("#winner").text('X win');
gameOver = true;
}
if (result === -3) {
$("#winner").text('O win');
gameOver = true;
}
}
//check Diagonal
result = gameArray[0] + (gameArray[4]) + (gameArray[8]);
if (result === 3) {
$("#winner").text('X win');
gameOver = true;
}
if (result === -3) {
$("#winner").text('O win');
gameOver = true;
}
result = gameArray[2] + (gameArray[4]) + (gameArray[6]);
if (result === 3) {
$("#winner").text('X win');
gameOver = true;
}
if (result === -3) {
$("#winner").text('O win');
gameOver = true;
}
}
});
.smallbox {
width: 50px;
border: 1px solid black;
height: 35px;
margin: 2px;
text-align: center;
padding-top: 15px;
}
.row-container {
display: flex;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="box" id="mainbox">
Turn: <span id='turn'></span>
<!-- creat 9 small box -->
<div class="row-container">
<div class="smallbox" id="square1"></div>
<div class="smallbox" id="square2"></div>
<div class="smallbox" id="square3"></div>
</div>
<div class="row-container">
<div class="smallbox" id="square4"></div>
<div class="smallbox" id="square5"></div>
<div class="smallbox" id="square6"></div>
</div>
<div class="row-container">
<div class="smallbox" id="square7"></div>
<div class="smallbox" id="square8"></div>
<div class="smallbox" id="square9"></div>
</div>
<span id='winner'></span>
</div>
solved how can i check winners by using jquery [duplicate]