我正在尝试为 Android 应用程序制作井字游戏。我打算制作的井字游戏模式是人机对抗。但问题是程序没有更新我的 switchPlayer 函数中的切换过程(setState),因为在执行 setState 后,Previous player 和 Current player 是相同的。switchPlayer 函数的预期输出:上一个玩家:1,当前玩家:-1,但实际输出:上一个玩家:1,当前玩家:1。
我也尝试使用其他 Stackoverflow 问题中建议/推荐的回调方法,但仍然无法正常工作。我做对了吗?任何建议将不胜感激。先感谢您。
代码如下:
switchPlayer = (newPlayer) => {
console.log("Previous player: "+this.state.currentPlayer);
this.setState(
{currentPlayer: newPlayer},
function () {console.log("Current player: "+this.state.currentPlayer); }
);
};
onTilePress = (row, col, ValidMove) => {
if (ValidMove == 1) { //If move is valid
//Dont allow tiles to change
var value = this.state.gameState[row][col];
if (value !== 0) { return;}
//Identify and grab current player
var PlayerNow = this.state.currentPlayer;
console.log(row, col, PlayerNow);
//Set the correct tile...
var arr = this.state.gameState.slice();
arr[row][col] = PlayerNow;
this.setState({gameState: arr});
//Switch to other player
if (PlayerNow == 1) { //if player 1, then change to bot
this.switchPlayer(-1);
}
else if (PlayerNow == -1) {
this.switchPlayer(1);
}
console.log("New current player " + this.state.currentPlayer);
//check winner
var winner = this.getWinner(); //get the winner update
if (winner == 1) {
Alert.alert("Player 1 has won!");
this.initializeGame();
}
else if (winner == -1){
Alert.alert("Bot has won!");
this.initializeGame();
}
else if (this.checkTie() == 9){ //check if the match is a draw
Alert.alert("It's a draw!");
this.initializeGame();
}
//Alert.alert("It's Player "+takePlayer+"'s turn!");
this.BotMove();
}
else {
Alert.alert("Player 1, please make a move!");
}
}