<!DOCTYPE HTML>
<head><title> Tic Tac Toe Game </title>
<script type="Text/Javascript" src="jquery-3.1.1.min.js"></script>
<style>
.box {
width : 100px;
height: 100px;
background-color: red;
position: relative;
border : 5px solid black;
cursor : pointer;
margin: 5px;
float: left;
text-align: center;
color: white;
}
div.container {
width: 360px;
height: 360px;
border : 10px solid green;
}
.message {
width: 360px;
font-size: 20px;
font-family: verdana;
font-weight: bold;
text-align: center;
color: red;
margin : 10px;
}
.clear {
clear: left;
}
.highlight {
border : 5px solid orange;
}
</style>
<script>
var $board_size = 3;
var $player = 1;
$(document).ready(function() {
$create_board();
$("div.box").css("font-size", parseInt($("div.box:first").css("width")) * .75 + "px");
$("div.box").hover(function() {
$(this).toggleClass("highlight");
});
$("div.box").click(function() {
$(this).off();
$(this).text($player == 1 ? "X" : "O");
if ($isWinner($player, parseInt($(this).attr("id")))) {
$("div.container").after("<div class='message'> Player " + $player + " Wins.");
$("div").off();
}
else if (isDraw()) {
$("div.container").after("<div class='message'>Draw</div>");
}
$player = ($player == 1 ? 2 : 1);
});
});
function $create_board() {
for (var $i = 1; $i <= $board_size * $board_size; $i++) {
$("div.container").append("<div id='" + $i + "'" + ($i % 3 == 1 ? "class='clear box'" : "class='box'") + "></div>");
}
}
function $isWinner($player, $id) {
var $counter;
// checking for horizontal
for (var $i = 1; $i <= $board_size; $i++) {
$counter = 0;
for (var $j = ($i * 3) - 2; $j <= ($i * 3); $j++) {
if ($("#" + $j).text() == ($player == 1 ? "X" : "O")) {
$counter++;
}
else {
break;
}
}
if ($counter == 3) return true;
}
// checking for vertical
$counter = 0;
$startindex = $id;
while (Math.floor((($startindex - 1) / 3)) != 0) {
$startindex-=3;
}
for (var $i = 1; $i <= $board_size; $i++) {
if ($("#" + $startindex).text() == ($player == 1 ? "X" : "O"))
$counter++;
$startindex += 3;
}
if ($counter == 3) return true;
// checking for diagonal
$counter = 0;
for (var $i = 1; $i <= $board_size * $board_size; $i += 4) {
if ($("#" + $i).text() == ($player == 1 ? "X" : "O")) {
$counter++;
}
}
if ($counter == 3) return true;
$counter = 0;
for (var $i = 3; $i <= $board_size * $board_size - 2; $i += 2) {
if ($("#" + $i).text() == ($player == 1 ? "X" : "O")) {
$counter++;
}
}
if ($counter == 3) return true;
return false;
}
function isDraw() {
var $counter = 0;
for (var $i = 1; $i <= $board_size * $board_size; $i++) {
if ($("#" + $i).text() != "") {
$counter++;
}
}
return ($counter == 9);
}
</script>
</head>
<html>
<body>
<div class="message">Tic-Tac-Toe Game 1.0</div>
<div class="container">
</div>
</body>
</html>
thanks sir. :D
ReplyDelete