首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在dart中访问循环外的变量?

如何在dart中访问循环外的变量?
EN

Stack Overflow用户
提问于 2020-05-27 22:26:59
回答 1查看 311关注 0票数 0

我编写了一个小的TicTacToe AI,在其中我在循环内声明了'bestMove‘,但不能在它之外访问它。

代码语言:javascript
复制
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';
      }
    }
  }

我已经尝试过为变量使用getter和setter方法。

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):空

EN

回答 1

Stack Overflow用户

发布于 2020-05-27 23:26:17

bestMove变量在逻辑中以某种方式被覆盖。

如果你的板包含8个值,你的循环索引将是从0到7,因为列表索引是从零开始的。

computerMove()中,您可以随时使用作用域bestMove变量。

请删除下划线前缀_,因为局部变量没有私有作用域。它只适用于库/类级别。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62045552

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档