JSFiddle - React, Tailwind, and code Playground
by gisheri
HTML
<body>
<center>
<h1>Tic Tac Toe</h1>
<table>
<tr id="row1">
<td id="square00"> </td>
<td id="square10"> </td>
<td id="square20"> </td>
</tr>
<tr id="row2">
<td id="square01"> </td>
<td id="square11"> </td>
<td id="square21"> </td>
</tr>
<tr id="row3">
<td id="square02"> </td>
<td id="square12"> </td>
<td id="square22"> </td>
</tr>
</table>
</center>
</body>
CSS
td {
border-width: 2px;
border-style: solid;
border-color: black;
border-collapse: collapse;
padding: 5px;
width: 2em;
text-align: center;
cursor: pointer;
}
td.winner {
background: red;
}
JavaScript
var waysToWin = [
['00','10','20'],
['01','11','21'],
['02','12','22'],
['00','01','02'],
['10','11','12'],
['20','21','22'],
['00','11','22'],
['02','11','20']
];
var my_x = [];
var my_o = [];
var checkWin = function(mylist){
var i = 0;
var j = 0;
var h = 0;
var k=0;
var score = 0;
var winners = [];
var winner;
for(i=0; i<waysToWin.length; i++){
score = 0;
winners = [];
for(j=0; j<waysToWin[i].length;j++)
{
for(h=0; h<mylist.length; h++)
{
if (mylist[h] == waysToWin[i][j])
{
score += 1;
winners.push(waysToWin[i][j]);
}
}
}
if(score >=3)
{
console.log("winners"+winners);
for(k=0; k<winners.length;k++)
{
winner = "square"+winners[k];
console.log(winner);
}
}
return true;
}
}
return false;
}
var handler = function(){
var coord;
if (this.innerHTML == 'x' || this.innerHTML == 'o'){
return false;
}
if (turn%2==0){
this.innerHTML = 'x';
coord = this.id;
coord = coord.substr(6,2);
console.log(coord)
my_x.push(coord);
console.log(my_x);
checkWin(my_x);
}
else {
this.innerHTML = 'o';
coord = this.id;
coord = coord.substr(6,2);
console.log(coord)
my_o.push(coord);
console.log(my_o);
checkWin(my_o);
}
turn ++;
};
console.log(waysToWin);
var turn = 0;
var myArray =new Array(00,01,02,10,11,12,20,21,22);
console.log(myArray);
all = document.getElementsByTagName('td');
console.log(all);
for (i=0; i<all.length;i++){
console.log(all.item(i));
all.item(i).onclick= handler;
all.item(i).onmouseover =...