用jQuery寫一個井字遊戲
1.jQuery原始檔
(
function(){
var flag = 0;
var n=[0,0,0,0,0,0,0,0,0];
var result=[0,0,0,0,0,0,0,0];
var
invalidate =
function(item){ //時間到一定會執行
$( '.
cell' ).each(
function(idx) {
if(idx !== item)
return;
var me = $(this);
me.find('
i').removeClass('fa-circle-o');
me.find('
i').removeClass('fa-times');
n[idx] = 0;
});
};
setInterval(
function(){
var item = Math.floor(Math.random()*9);
invalidate(item);
},1000);
$( '.
cell' ).each(function(idx) {
var me = $(this); //一開始會直9次註冊每個 cell 物件的click event call back function
me.on('click',function(){ //只有在click evevt 發生時才會執行
if(me.find('
i').hasClass('fa-circle-o') || me.find('
i').hasClass('fa-times'))
return;
//if (flag == 9)
//
return;
if(flag % 2)
me.find('
i').addClass('fa-circle-o');
else
me.find('
i').addClass('fa-times');
flag++;
n[idx] = (flag % 2) ? 1:-1;
result[0]=n[0]+n[1]+n[2];
result[1]=n[3]+n[4]+n[5];
result[2]=n[6]+n[7]+n[8];
result[3]=n[0]+n[3]+n[6];
result[4]=n[1]+n[4]+n[7];
result[5]=n[2]+n[5]+n[8];
result[6]=n[0]+n[4]+n[8];
result[7]=n[2]+n[4]+n[6];
if(result.indexOf(3) !== -1)
alert('You win');
if(result.indexOf(-3) !== -1)
alert('I win');
})
});
})();
2.html檔
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Bootstrap test</title>
<!-- Bootstrap -->
<link href="/vendor/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="/vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet">
<link href="/game.js/game.css" rel="stylesheet">
</head>
<body>
<div class="container" id="game">
<div class="row">
<div class="cell col-md-4 col-sm-4 col-xs-4"><i data-num='0' class="fa"> </i></div>
<div class="cell col-md-4 col-sm-4 col-xs-4"><i data-num='1' class="fa"> </i> </div>
<div class="cell col-md-4 col-sm-4 col-xs-4"><i data-num='2' class="fa"> </i> </div>
</div>
<div class="row">
<div class="cell col-md-4 col-sm-4 col-xs-4"><i data-num='3' class="fa"> </i></div>
<div class="cell col-md-4 col-sm-4 col-xs-4"><i data-num='3' class="fa"> </i> </div>
<div class="cell col-md-4 col-sm-4 col-xs-4"><i data-num='5' class="fa"> </i> </div>
</div>
<div class="row">
<div class="cell col-md-4 col-sm-4 col-xs-4"><i data-num='6' class="fa"> </i></div>
<div class="cell col-md-4 col-sm-4 col-xs-4"><i data-num='7' class="fa"> </i> </div>
<div class="cell col-md-4 col-sm-4 col-xs-4"><i data-num='8' class="fa"> </i> </div>
</div>
</div>
<script src="/vendor/jquery/dist/jquery.min.js"></script>
<script src="/vendor/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="/game.js/game.js"></script>
</body>
</html>