-1

I am trying to build an AI for tic tac toe, this is the first time I'm doing any kind of AI, and I am having trouble figuring out how to get the AI to try every different move possible for a given situation (board). "E" are empty cells, and I am storing their indexes in an array called available. The AI move would be inserting "O" in the nextBoard variable with the indexes provided by the available array once at each time. This function is modifying both the nextBoard variable, which I want to use to evaluate the next AI move by giving it a score, but also the real board variable, that I am using to evaluate the state of the game.

function AiPossibleActions () {
  available=[0,1,2,3,5,6,7,8];
  board=["E","E","E","E","X","E","E","E","E"];
  var nextBoard=board
  for (var i=0; i<available.length; i++) {
    nextBoard = board;
    nextBoard[available[i]]="O";
  }
  oMovesCount++
}

When I run the function both variables(nextBoard and board) are being modifying and none of them with expected output.

//wrong output
 ["O", "O", "O", "O", "X", "O", "O", "O", "O"]

The ideal output would be that for each iteration the variable nextBoard is equal to:

//1st iteration
["O", "E", "E", "E", "X", "E", "E", "E", "E"]
//2nd iteration
["E", "O", "E", "E", "X", "E", "E", "E", "E"]
//3rd iteration
["E", "E", "O", "E", "X", "E", "E", "E", "E"]
//4th iteration
["E", "E", "E", "O", "X", "E", "E", "E", "E"]
//5th iteration
["E", "E", "E", "E", "X", "O", "E", "E", "E"]
//6th iteration
["E", "E", "E", "E", "X", "E", "O", "E", "E"]
//7th iteration
["E", "E", "E", "E", "X", "E", "E", "O", "E"]
//8th iteration
["E", "E", "E", "E", "X", "E", "E", "E", "O"]
vanpeta
  • 13
  • 4
  • 2
    Well that should tell you that you're actually modifying the same array, and that you need to find a different way to make a copy, since clearly a mere assignment doesn't do it. –  Jun 17 '16 at 02:27
  • JavaScript stores object by reference, not value, when you do `nextBoard = board` then nextBard isn't a copy of board, it **is** board. – Bálint Jun 17 '16 at 02:30

1 Answers1

1

You may have the problem of that object are shallow copies in javascript, so

var nextBoard=board

does not make a copy of the board, but only makes a copy of the refernce to the array.

In your case, if you need a copy, then you may be able to use slice, like;

var nextBoard=board.slice()

(and then the same inside the loop), but it would have to be more elaborate if your array element are themselves objects.

Soren
  • 14,402
  • 4
  • 41
  • 67