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"]