MCPcopy Create free account
hub / github.com/candybox2/candybox2.github.io / playTicTacToe_minimax

Method playTicTacToe_minimax

code/main/ATree.ts:186–236  ·  view source on GitHub ↗
(board: ATreeTicTacToeSign[][], playerSign: ATreeTicTacToeSign, depth: number = 2)

Source from the content-addressed store, hash-verified

184 }
185
186 private playTicTacToe_minimax(board: ATreeTicTacToeSign[][], playerSign: ATreeTicTacToeSign, depth: number = 2): ATreeTicTacToeMinimaxReturnValue{
187 // Variables
188 var tempBoard: ATreeTicTacToeSign[][]; // The temp board, used to simulate moves
189 var currentScore: number; // Current score, used for calculations
190 var returnValue: ATreeTicTacToeMinimaxReturnValue = new ATreeTicTacToeMinimaxReturnValue; // The return value, which contains the best position and the best score
191 var gameFull: boolean = true; // Used later to find out if the game is full or not
192
193 // Set the initial best score, depending on the playerSign parameter
194 if(playerSign == ATreeTicTacToeSign.O) // If the player sign is the squirrel
195 returnValue.bestScore = -99999999;
196 else // Else
197 returnValue.bestScore = 99999999;
198
199 // If the depth is > to 0 (this condition is needed to stop the iterating loop at some point)
200 if(depth > 0){
201 // Iterate over all the board
202 for(var i = 1; i <= 3; i++){
203 for(var j = 1; j <= 3; j++){
204 // If this cell is empty
205 if(board[i][j] == ATreeTicTacToeSign.NO_SIGN){
206 // We found at least one non-empty cell : the game isn't full
207 gameFull = false;
208 // Set the temp board from the real board
209 tempBoard = this.playTicTacToe_copyBoard(board);
210 // Try to play on this cell using the temp board
211 tempBoard[i][j] = playerSign;
212 if(playerSign == ATreeTicTacToeSign.O){ // If we're testing the squirrel
213 currentScore = this.playTicTacToe_minimax(tempBoard, ATreeTicTacToeSign.X, depth - 1).bestScore;
214 if(returnValue.bestScore <= currentScore){
215 returnValue.bestScore = currentScore;
216 returnValue.bestPosition = new Pos(i, j);
217 }
218 }
219 else{ // Else, we're testing the player
220 currentScore = this.playTicTacToe_minimax(tempBoard, ATreeTicTacToeSign.O, depth - 1).bestScore;
221 if(returnValue.bestScore >= currentScore){
222 returnValue.bestScore = currentScore;
223 returnValue.bestPosition = new Pos(i, j);
224 }
225 }
226 }
227 }
228 }
229 // If the game seems full, we calculate the best score too
230 if(gameFull) returnValue.bestScore = this.playTicTacToe_evaluateBoard(board);
231 }
232 else returnValue.bestScore = this.playTicTacToe_evaluateBoard(board);
233
234 // Return the return value (best position found + the score)
235 return returnValue;
236 }
237
238 private playTicTacToe_testEndGameConditions(): boolean{
239 // Variables

Callers 1

playTicTacToeSignMethod · 0.95

Calls 2

Tested by

no test coverage detected