Tic-Tac-Toe Key

Tic-Tac-Toe Key
0

#1

When I hit a square, the computer picks another square. However, sometimes the computer picks square that is already picked. I think it is because the square is not set.

function fillBox(x) {
if (key[x] == “e”) {
key[x] = “X”;
console.log(key[x]);
//Object.values(key)[x]=“X”;
document.getElementById(x).innerHTML = “X”;
compMove();
} else {
alert(“Spot is taken. Try Again”);
}
}

function compMove() {
var loop1 = true;
while (loop1) {
var x = Math.floor(Math.random() * 9);
var y = Object.values(key)[x];
if (y == “e”) {
key[x]=“O”;
Object.values(key)[x] = “O”;
document.getElementById(Object.keys(key)[x]).innerHTML = “O”;
loop1=false;
}
}
}


#2

You have one major inconsistency in your code:

your object keys and the one you are trying to access in the loop does not match.

you object:

var key = {
  ul: "e",
  uc: "e",
  [...]
}

while in the loop:

var x = Math.floor(Math.random() * 9); // x is a number 

if (y == “e”) {
key[x]=“O”; // here key[x] is undefined 

That’s because you are trying to access a value in the object with key 0-8 while your keys have the shape of “ul - uc - cc …”

Therefore your object never gets updated properly.


#3

Thank you. I solved this problem.
I added the function

function getPostion(postion) {
switch (postion) {
case 0:
return “ul”;
case 1:
return “uc”;

}
}

Then changed
var y = Object.values(key)[x];
if (y == “e”) {
key[x]=“O”;

to:
var y = getPostion(x);
if (key[y] == “e”) {
key[y] = “O”;