|
var winArr=[['1','2','3'], ['4','5','6'], ['7','8','9'], ['1','4','7'], ['2','5','8'], ['3','6','9'], ['1','5','9'], ['3','5','7']], |
|
boardArr=['1','2','3','4','5','6','7','8','9'], |
|
boardObj={ |
|
'1':'one','2':'two','3':'three','4':'four','5':'five','6':'six','7':'seven','8':'eight','9':'nine' |
|
}, |
|
userArr=[], |
|
aiArr=[], |
|
xFlag=false, |
|
oFlag=false, |
|
userFlag=false, |
|
aiFlag=false, |
|
aiMoveIndex='', |
|
val=''; |
|
|
|
function refresh(){ |
|
boardArr=['1','2','3','4','5','6','7','8','9'], |
|
userArr=[], |
|
aiArr=[], |
|
xFlag=false, |
|
oFlag=false, |
|
userFlag=false, |
|
aiFlag=false, |
|
aiMoveIndex='', |
|
val=''; |
|
$('.box').text(''); |
|
$('.box').removeAttr('status'); |
|
$('.xo').show(); |
|
$('.first').show(); |
|
|
|
} |
|
|
|
function checkWin(){// check if user wins; |
|
for(var i=0; i<winArr.length; i++){ |
|
if(userArr.includes(winArr[i][0])&&userArr.includes(winArr[i][1])&&userArr.includes(winArr[i][2])){ |
|
|
|
alert('you won'); |
|
return refresh(); |
|
} |
|
if(aiArr.includes(winArr[i][0])&&aiArr.includes(winArr[i][1])&&aiArr.includes(winArr[i][2])){ |
|
alert('computer won') |
|
return refresh(); |
|
} |
|
if(boardArr.length===0){ |
|
|
|
alert('tie') |
|
return refresh(); |
|
} |
|
} |
|
} |
|
|
|
function userMove(){ |
|
userArr.push(val);//create user position array; |
|
changeBoardArr(); |
|
checkWin(); |
|
} |
|
|
|
function aiMove (){//ai move automatically according to Math.random(); |
|
if(xFlag||oFlag){ |
|
$(this).attr('status', 'true');//prevent user double click clicked box; |
|
aiMoveIndex = Math.floor(Math.random()*boardArr.length); |
|
var aiPosClass=boardObj[boardArr[aiMoveIndex]]; |
|
console.log(aiPosClass) |
|
$('.'+aiPosClass).text(oFlag ? 'X' : 'O'); |
|
$('.'+aiPosClass).attr('status', 'true'); |
|
aiArr.push(boardArr[aiMoveIndex])//===val e.g. 1,2,3...; |
|
boardArr.splice(aiMoveIndex,1);//create aiArr; |
|
checkWin(); |
|
console.log(aiArr); |
|
console.log(boardArr); |
|
} |
|
|
|
} |
|
|
|
function changeBoardArr (){//splice boardArr after each click; |
|
var index=boardArr.indexOf(val); |
|
return boardArr.splice(index, 1); |
|
} |
|
|
|
function checkXO(){// check user's x or o choice; |
|
$('.x').click(function(){ |
|
xFlag=true; |
|
$('.xo').hide(); |
|
}); |
|
|
|
$('.o').click(function(){ |
|
oFlag=true; |
|
$('.xo').hide(); |
|
}); |
|
} |
|
|
|
function tic(){ |
|
|
|
checkXO();// check user's x or o choice; |
|
|
|
//checkUser();// check user or computer first; |
|
|
|
$('.box').click(function(){//user click board; |
|
|
|
if(!$(this).attr('status')){//prevent double click same box; |
|
if(oFlag||xFlag){ |
|
$(this).attr('status', 'true');//after clicking status changed to true; prevent user double click clicked box; |
|
|
|
val=$(this).attr('value');//get 1,2,3... number value; |
|
|
|
if(xFlag){$(this).text('X');} |
|
if(oFlag){$(this).text('O');} |
|
|
|
userMove(); |
|
aiMove(); |
|
} |
|
|
|
} |
|
}) |
|
|
|
} |
|
tic(); |