JSFiddle - React, Tailwind, and code Playground
by ifonecoder
HTML
<table>
<h3> Tic Tac Toe</h3>
<tr>
<td id="11"></td>
<td id="12"></td>
<td id="13"></td>
</tr>
<tr>
<td id="21"></td>
<td id="22"></td>
<td id="23"></td>
</tr>
<tr>
<td id="31"></td>
<td id="32"></td>
<td id="33"></td>
</tr>
</table>
<div id="winner"></div>
CSS
table {
border: 2px solid;
height: 100px;
width: 100px
}
td {
border: 1px solid;
height: 20px;
width: 20px;
}
JavaScript
var player = 0;
var isDone = function (one, two, three) {
var $one = $('#' + one).text().trim().trim();
var $two = $('#' + two).text().trim().trim();
var $three = $('#' + three).text().trim().trim();
if (($one === "") || ($two === "") || ($three === "")) { return false;}
if (($one === $two) && ($one === $three)) {
return true;
} else {
return false;
}
};
var possibles = [[11,12,13],[21,22,23],[31,32,33],[11,21,31],[12,22,32],[13,23,33],[11,22,33],[13,22,31]];
var stopGame=false;
$('td').click(function () {
if(stopGame) return;
var textAt = $(this).text();
if (textAt === "") {
if (player === 0) {
player = 1;
$(this).append('X');
} else {
player = 0;
$(this).append('O');
}
}
var thisid = $(this).attr('id');
// alert(isDone(11,12,13));
for (var i = 0; i < possibles.length; i++) {
if (isDone(possibles[i][0], possibles[i][1], possibles[i][2])) {
$('#' + possibles[i][0]).css('background-color','green');
$('#' + possibles[i][1]).css('background-color','green');
$('#' + possibles[i][2]).css('background-color','green');
alert('game over ');
stopGame=true;
if(player===1){
$('#winner').append('<p>Winner: X</p>');
}else{
$('#winner').append('<p>Winner: O</p>');
}
}
}
});