为什么同一类的不同实例会相互覆盖?

时间:2017-09-25 11:01:37

标签: javascript class

所以我的问题在于playAI和miniMaxAlgorithm。

首先,我制作了一个myTicTacToe实例的副本,之后我称之为tempgame,我在该副本上调用了miniMaxAlgorithm。这一切都是为了确保myTicTacToe保持不变。

问题是myTicTacToe后来跟tempgame的值相同。 我不明白为什么。

/ ************************** TicTacToe班****************** **** /

class TicTacToe {




constructor(playField = [

    ['E', 'E', 'E'],
    ['E', 'E', 'E'],
    ['E', 'E', 'E']


], human = 'X', computer = 'O', gameStatus = "playing", currentPlayer = 'X') {

    this.playField = playField;


    this.human = human;
    this.computer = computer;
    this.gameStatus = gameStatus;
    this.bestMove;
    this.startingPlayer = human;


    this.currentPlayer = currentPlayer;

}



reset() {
    this.playField = [

        ['E', 'E', 'E'],
        ['E', 'E', 'E'],
        ['E', 'E', 'E']


    ];

    this.gameStatus = 'playing';
    this.currentPlayer = this.startingPlayer;
    $('#gamestate').text('');

}


checkGameState() {

    /******************** Win conditions******************************/
    if (this.currentPlayer === 'X' || this.currentPlayer === 'O') {

        if (this.winOrNot()) {


            $('#gamestate').text('Player ' + this.currentPlayer + ' won.');
            this.gameStatus = 'over';

        }



        //********************** Check if it is a draw***************/
        else {
            /*which results in a draw*/
            let arrayOfFreePlaces = this.freePositions();
            if (!(arrayOfFreePlaces.length > 0)) {

                $('#gamestate').text('It is a draw');
                this.gameStatus = 'over';
            }

        }

    }
}
/***********************/

winOrNot() {

    if ((this.playField[0][0] === this.currentPlayer && this.playField[0][1] === this.currentPlayer && this.playField[0][2] === this.currentPlayer) ||
        (this.playField[1][0] === this.currentPlayer && this.playField[1][1] === this.currentPlayer && this.playField[1][2] === this.currentPlayer) ||
        (this.playField[2][0] === this.currentPlayer && this.playField[2][1] === this.currentPlayer && this.playField[2][2] === this.currentPlayer) ||
        (this.playField[0][0] === this.currentPlayer && this.playField[1][0] === this.currentPlayer && this.playField[2][0] === this.currentPlayer) ||
        (this.playField[0][1] === this.currentPlayer && this.playField[1][1] === this.currentPlayer && this.playField[2][1] === this.currentPlayer) ||
        (this.playField[0][2] === this.currentPlayer && this.playField[1][2] === this.currentPlayer && this.playField[2][2] === this.currentPlayer) ||
        (this.playField[0][0] === this.currentPlayer && this.playField[1][1] === this.currentPlayer && this.playField[2][2] === this.currentPlayer) ||
        (this.playField[0][2] === this.currentPlayer && this.playField[1][1] === this.currentPlayer && this.playField[2][0] === this.currentPlayer)

    ) {

        return true;

    } else {
        return false;
    }

}


freePositions() {

    let emptyPositions = [];

    for (let i = 0; i < this.playField.length; i++) {




        for (let j = 0; j < this.playField[i].length; j++) {

            if (this.playField[i][j] === 'E') {


                emptyPositions.push([i, j]);


            }



        }



    }



    return emptyPositions;



}
// rate gamestate

rateField() {
    // if computer wins +10
    if (this.winOrNot(this.computer)) {

        return 10;
    }
    // if human wins -10
    else if (this.winOrNot(this.human)) {

        return -10;
    }
    // if no one wins +0, aka drawm or not finished yet
    else {

        return 0;

    }


}




}

  //Prototypes of TicTacToe


   TicTacToe.prototype.placeSign = function(row, column) {
   // check if field is empty

if (this.playField[row][column] === 'E') {

    if (this.currentPlayer === "X") {


        this.playField[row][column] = 'X';

    } else if (this.currentPlayer === "O") {

        this.playField[row][column] = 'O';

    }
    this.checkGameState();
    this.currentPlayer === this.computer ? this.currentPlayer = this.human : this.currentPlayer = this.computer;


} else {


    console.log("Select an empty field!!");
}

};

/ *******************声明************************** ***** /

    let myTicTacToe = new TicTacToe();
     let tempgame = new TicTacToe();
       let bestMove;

/ ******** ********功能/

// miniMaxAlgorithm

  function miniMaxAlgorithm(TicTacToe1) {








/****************base case********************************/

// if the game is over , return rating
if (TicTacToe1.gameStatus === 'over') {
    return TicTacToe1.rateField();
}
/******************************************/
//contains the rating of each move
let scores = [];

// containing the equivalent moves
let moves = [];

//fill the scores array
/**************************recursive case*******************************/
// create on array with containing all possible moves of the current tictactoe instance
let freeFields = TicTacToe1.freePositions();
for (let i = 0; i < freeFields.length; i++) {
    //make a copy of the current tictactoe instance
    let possibleTicTacToe = new TicTacToe(TicTacToe1.playField, TicTacToe1.human, TicTacToe1.computer, TicTacToe1.gameStatus, TicTacToe1.currentPlayer);
    //play one of the possible moves
    possibleTicTacToe.placeSign(freeFields[i][0], freeFields[i][1]);
    // calling the function recursively until game is over 
    scores.push(miniMaxAlgorithm(possibleTicTacToe));
    // adding place sign parameters ass an array inside moves
    moves.push([freeFields[i][0], freeFields[i][1]]);
}


//  Min Max Calculation
if (TicTacToe1.currentPlayer === TicTacToe1.computer) {
    //      search for the largest score and save its index in maxScoreIndex
    let maxScoreIndex = 0;
    for (let j = 1; j < scores.length; j++) {
        if (scores[j] > scores[maxScoreIndex]) {
            maxScoreIndex = j;

        }

    }

    bestMove = moves[maxScoreIndex];
    return scores[maxScoreIndex];
}

// tests best possible opponent moves (human)
else {
    //        
    let minScoreIndex = 0;
    for (let j = 1; j < scores.length; j++) {
        if (scores[j] < scores[minScoreIndex]) {
            minScoreIndex = j;

        }



    }




    bestMove = moves[minScoreIndex];
    return scores[minScoreIndex];
}



/**********************************************************************/

}

function updateFields(){

document.getElementById('field1').innerHTML = myTicTacToe.playField[0][0];
document.getElementById('field2').innerHTML = myTicTacToe.playField[0][1];
document.getElementById('field3').innerHTML = myTicTacToe.playField[0][2];
document.getElementById('field4').innerHTML = myTicTacToe.playField[1][0];
document.getElementById('field5').innerHTML = myTicTacToe.playField[1][1];
document.getElementById('field6').innerHTML = myTicTacToe.playField[1][2];
document.getElementById('field7').innerHTML = myTicTacToe.playField[2][0];
document.getElementById('field8').innerHTML = myTicTacToe.playField[2][1];
document.getElementById('field9').innerHTML = myTicTacToe.playField[2][2];
           }
          /**********************************************************/

// playAI

 function playAI() {

//AI miniMaxEnd

    tempgame = new TicTacToe (myTicTacToe.playField,myTicTacToe.human,myTicTacToe.computer,myTicTacToe.gameStatus,myTicTacToe.currentPlayer)

         console.dir(myTicTacToe);
        console.dir(tempgame);
         miniMaxAlgorithm(tempgame);
         console.dir(myTicTacToe);
         console.dir(tempgame);

    myTicTacToe.placeSign(bestMove[0],bestMove[1]);
  //AI miniMaxEnd




updateFields();

}

1 个答案:

答案 0 :(得分:0)

我知道可能导致此问题的原因。

在javascript数组(或列表)中由引用而不是 value 传递。

这意味着如果您将一个数组作为参数传递给一个函数,它会将一个指针传递给该列表,而不是该列表的副本。

TicTacToe 类中,您有一个名为 playField 的变量,它是一个列表。

您可以像这样创建TicTacToe对象的克隆:

tempgame = new TicTacToe (myTicTacToe.playField, ... )

在这里,你将引用传递给现有的 playField 列表而不是克隆列表。即传递列表的地址而不是其内容。

myTicTacToe tempgame 都将使用 playField 数据的相同副本。一个变化将导致另一个变化。

为了创建数组的新副本,使用javascript 切片操作是标准的:

tempgame = new TicTacToe (myTicTacToe.playField.slice(0), ... )

此操作将从第一个元素(0)开始创建数组的新副本。

有关使用切片操作克隆数组的更多信息,请访问:

https://davidwalsh.name/javascript-clone-array