Skip to content

Instantly share code, notes, and snippets.

@ken-master
Last active February 15, 2016 14:51
Show Gist options
  • Save ken-master/fa3803644da27340422d to your computer and use it in GitHub Desktop.
Save ken-master/fa3803644da27340422d to your computer and use it in GitHub Desktop.
Tic Tac Toe using javascript (jquery)
<!DOCTYPE html>
<html>
<head>
<style>
tr > td {
height: 30px;
width:30px;
align: center;
}
</style>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script>
$( document ).ready(function(){
/**
* ASsign X's and O's
*/
var val = "O";
$("table td").on("click",function(){
if(val === "O"){
val = "X";
$(this).html(val);
}else{
val = "O";
$(this).html(val);
}
});
$('.check_winner').on('click',function(){
//diagonal
var diag1 = new Array();
var diag2 = new Array();
var collum1 = new Array();
var collum2 = new Array();
var collum3 = new Array();
$("tr").each(function(i,v){
diag1[i] = $(v).find('td').eq(0+i, -3).html();
diag2[i] = $(v).find('td').eq(2-i, 3).html();
collum1[i] = $(v).find('td').eq(0).html();
collum2[i] = $(v).find('td').eq(1).html();
collum3[i] = $(v).find('td').eq(2).html();
//console.log( $(v).find('td').eq(0+i, -3) );
//console.log( $(v).find('td').eq(2-i, 3).html() );
});
//console.log(collum1);
checkArray(diag1);
checkArray(diag2);
checkArray(collum1);
checkArray(collum2);
checkArray(collum3);
//add ROW to checking
});
function checkArray(array){
o = 0;
x = 0;
for( i = 0;i <= array.length; i++ ){
if(array[i] == "X"){
x += 1;
}
if(array[i] == "O"){
o += 1;
}
}
if(x == 3){
alert("X is winner") ;
}else if(o == 3){
alert("O is winner") ;
}else{
return false;
}
delete o;
delete x;
// console.log(x);
// console.log(o)
}
});
</script>
</head>
<body>
<h1>TicTacToe</h1>
<table border="1" >
<tr class="row">
<td id="matrx1"></td>
<td id="matrx2"></td>
<td id="matrx3"></td>
</tr>
<tr class="row">
<td id="matrx4"></td>
<td id="matrx5"></td>
<td id="matrx6"></td>
</tr>
<tr class="row">
<td id="matrx7"></td>
<td id="matrx8"></td>
<td id="matrx9"></td>
</tr>
</table>
<button class="check_winner">CHECK WINNER</button>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment