Tic-Tac-Toe Key

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 == “e”) {
key = “X”;
console.log(key);
//Object.values(key)=“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);
if (y == “e”) {
key=“O”;
Object.values(key) = “O”;
document.getElementById(Object.keys(key)).innerHTML = “O”;
loop1=false;
}
}
}

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.

1 Like

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”;