Recently, I embarked on a journey to learn the art of JavaScript
, and my current project involves creating a Tic Tac Toe game. However, I've hit a roadblock with the IN
statement, as it consistently returns True
under the specified condition.
function getMove(index){
key=parseInt(index);
var temp;
temp=moves;
elem=document.getElementById(index);
var valid_move=(key in temp);
document.getElementById('warning').innerText=valid_move;`
The crux of the issue lies within the 5th statement of the function above: var valid_move=(key in temp);
No matter how I manipulate the value of index
once it's occupied, the outcome invariably remains True
:
var key;
var elem;
var moves=[1,2,3,4,5,6,7,8,9,10];
var score_x=0;
var score_o=0;
var X=true;
function getMove(index){
key=parseInt(index);
var temp;
temp=moves;
elem=document.getElementById(index);
var valid_move=(key in temp);
document.getElementById('warning').innerText=valid_move;
if (X && valid_move){
elem.innerText='X';
elem.style.color='Crimson';
moves[key-1]='occ';
X=false;
document.getElementById('head').innerText=temp;
}else if(!X && valid_move){
elem.innerText='O';
elem.style.color='blue';
moves[key-1]='occ';
document.getElementById('head').innerText=temp;
X=true;
}
else {
document.getElementById('warning').innerText='Already Occupied !'
}
var len;
len=temp.length;
if (len==1){
document.write('GAME OVER');
}
}
This is the whole code.
If you observe carefully, every time an index gets occupied, its value switches to occ
to prevent players from placing moves at the same position twice (as expected in TIC TAC TOE
). Nonetheless, I'm still able to place moves at the same spot more than once.
Your assistance would be greatly appreciated.