How to pass values up in a tree in javascript

Asked

Viewed 94 times

-1

Hello, I’m doing an exercise that consists in making an algorithm that plays the game of old, so far I managed to generate all the game paths and detect which lead to victory or defeat and organizes the dice in a tree-like structure object, the code follows:

loadPossibilities(squares, xIsNext) {
    var livres = this.getFree(squares);
    var possibilities = [];
    var Xwin = 0;
    var Owin = 0;
    var fake = squares.slice();
    var tmp = [];
    for (let i = 0; i < livres.length; i++) {
      fake = squares.slice();
      fake[livres[i]] = xIsNext ? "O" : "X";
      possibilities.push({
        squares: fake,
        possibilities: [],
        Xwin: 0,
        Owin: 0,
        ganhador: calculateWinner(fake).winner
      });
      if (possibilities[i].ganhador === "X") {
        Xwin++;
      } else if (possibilities[i].ganhador === "O") {
        Owin++;
      }
    }
    if (possibilities.length > 1) {
      for (let i = 0; i < possibilities.length; i++) {
        if (possibilities[i].ganhador == null) {
          tmp = this.loadPossibilities(possibilities[i].squares, !xIsNext);
          possibilities[i].possibilities = tmp;
        }
      }
    }
    Xwin = Xwin = tmp.Xwin;

    Owin = Owin = tmp.Owin;
    // console.log(possibilities);
    return { possibilities: possibilities, Xwin: Xwin, Owin: Owin };
  }

The values Xwin and Owin are calculated correctly but when they are passed up the tree they end up becoming Undefined, the variable Squares is a nine-position vector representing the board. the complete code can be found here https://github.com/Mathe13/tic-tac-toe-ia-2019 I used an example of React as an interface. someone knows how to solve?

1 answer

0

I believe that at the last execution of its recursion the code will not execute the logic within the if(possibilities.length > 1), therefore, the variable tmp will be nothing more than a Array (how she was raised on top like this).

Therefore, you will not be able to access the Xwin property, let alone Owin it, by returning Undefined to the tree above.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.