我编写了一个小的TicTacToe AI,在其中我在循环内声明了'bestMove‘,但不能在它之外访问它。
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):空
发布于 2020-05-27 23:26:17
bestMove变量在逻辑中以某种方式被覆盖。
如果你的板包含8个值,你的循环索引将是从0到7,因为列表索引是从零开始的。
在computerMove()中,您可以随时使用作用域bestMove变量。
请删除下划线前缀_,因为局部变量没有私有作用域。它只适用于库/类级别。
https://stackoverflow.com/questions/62045552
复制相似问题