Как мне получить доступ к переменной вне l oop в dart? - PullRequest
0 голосов
/ 27 мая 2020

Я запрограммировал небольшой ИИ TicTacToe, в котором я объявляю 'bestMove' внутри l oop, но не могу получить к нему доступ за его пределами.

void computerMove() {
    int _currentMove;
    int _currentScore = 0;
    int _bestMove; // here i initialize it
    int _bestScore = 0;
    List<String> boardWithMove = List.from(_board);
    if (!isWin() && !isDraw()) {
      for (int i = 0; i <= 8; i++) {
        // checks all first move possibilities
        if (_board[i] == null) {
          if (_computerIsX) {
            boardWithMove[i] = 'X';
            _currentMove = i;
            print(_currentMove);
            print('computer thinking');
          }
          // Try's all possibilities for the initial move
          for (int i = 0; i <= 8; i++) {
            if (boardWithMove[i] == null) {
              if (_computerTurn && _computerIsX) {
                boardWithMove[i] = 'X';
                _computerTurn = false;
                if (isWin()) {
                  _currentScore++;
                }
              } else if (!_computerTurn && _computerIsX) {
                boardWithMove[i] = 'O';
                _computerTurn = true;
                if (isWin()) {
                  _currentScore--;
                }
              }
            }
          }
          // safes the best move with best results
          if (_currentScore > _bestScore) {
            _bestScore = _currentScore;
            _bestMove = _currentMove; // here i change it
            print(_bestMove);
          }
        }
      }
      // sets the best output
      if (_computerIsX) {
        print(_bestMove); // returns null
        _board[_bestMove] = 'X'; // here I want to use it
      } else if (!_computerIsX) {
        _board[_bestMove] = 'O';
      }
    }
  }

Я пробовал иметь геттер и метод установки для переменной.

Consol выводит это:

I / flutter (6179): 1 I / flutter (6179): компьютерное мышление I / flutter (6179): 2 ...

I / flutter (6179): компьютерное мышление I / flutter (6179): 7 I / flutter (6179): компьютерное мышление I / flutter (6179): 8 I / flutter (6179): компьютерное мышление I / flutter (6179): ноль

1 Ответ

0 голосов
/ 27 мая 2020

Переменная bestMove каким-то образом перезаписывается в logi c.

Если ваша доска содержит 8 значений, ваши l oop индексы будут от 0 до 7, так как индексирование списка начинается с нуля.

В зависимости от области действия bestMove Переменная доступна вам в каждой точке computerMove().

Удалите префиксы подчеркивания _, поскольку локальные переменные не имеют частной области видимости. Это относится только к уровню библиотеки / класса.

...