I'm trying to make a TicTacToe game for an android app. The TicTacToe's game mode that I'm intended to make is Human-vs-Computer. But the problem is the program did not update the switching-procedure (setState) in my switchPlayer function as the Previous player and Current player is the same after doing the setState. The expected output from switchPlayer function: Previous player: 1, Current player: -1 but the actual output: Previous player: 1, Current player: 1.
I've also tried to use the callback method as suggested/recommended from other Stackoverflow question, but still not working. Am I doing it right? Any suggestion will be much appreciated. Thank you in advance.
Codes are as below:
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!");
}
}