diff --git a/TicTacToe/Model/GameLogicModel.swift b/TicTacToe/Model/GameLogicModel.swift index 74c9f68..12ec1ab 100644 --- a/TicTacToe/Model/GameLogicModel.swift +++ b/TicTacToe/Model/GameLogicModel.swift @@ -44,6 +44,17 @@ struct GameLogicModel { return -1 } + func pickSecondSquare() -> Int { + let secondSquare = 1 // 1 is the second square in array [0, 1, 2...] + if !aiVM.isSquareOccupied(in: moves, forIndex: secondSquare) { + if moves.contains(where: { $0?.boardIndex == 4 && $0?.player == .computer }) { + return secondSquare + } + } + + return -1 + } + func pickCornerSquare() -> Int { let corners: [Int] = [0, 2, 6, 8] for corner in corners { diff --git a/TicTacToe/ViewModel/VersusAIViewModel.swift b/TicTacToe/ViewModel/VersusAIViewModel.swift index 21ebbdc..33cd1d8 100644 --- a/TicTacToe/ViewModel/VersusAIViewModel.swift +++ b/TicTacToe/ViewModel/VersusAIViewModel.swift @@ -102,8 +102,8 @@ final class VersusAIViewModel: ObservableObject { if (middleSquare != -1) { return middleSquare } // If AI can't pick middle square because is yours, then pick a square above the middle - let secondSquare = 1 // 1 is the second square in array [0, 1, 2...] - if moves.contains(where: { $0?.boardIndex == 4 && $0?.player == .computer }) { return secondSquare } + let secondSquare = logicModel.pickMiddleSquare() + if (secondSquare != -1) { return secondSquare } // If AI can't pick middle square because is not yours, then pick a corner square let cornerSquare = logicModel.pickCornerSquare()