From 257db0c23a03feede0ecbf88fbaf04ed5268d8f9 Mon Sep 17 00:00:00 2001 From: gucio321 <73652197+gucio321@users.noreply.github.com> Date: Mon, 28 Mar 2022 17:09:24 +0200 Subject: [PATCH] pcplayer engine: refactor canWinTwoMoves method --- pkg/core/pcplayer/pc_player_engine.go | 43 ++++++++++----------------- 1 file changed, 15 insertions(+), 28 deletions(-) diff --git a/pkg/core/pcplayer/pc_player_engine.go b/pkg/core/pcplayer/pc_player_engine.go index 119123c..d2da666 100644 --- a/pkg/core/pcplayer/pc_player_engine.go +++ b/pkg/core/pcplayer/pc_player_engine.go @@ -4,7 +4,6 @@ package pcplayer import ( "math/rand" - "reflect" "time" "github.com/gucio321/tic-tac-go/pkg/core/board" @@ -74,39 +73,27 @@ func canWinTwoMoves(gameBoard *board.Board, player letter.Letter) (result []int) return } - winningChains := gameBoard.GetWinBoard(minimalChainLen) - - availableWinningChains := make([][]int, 0) + potentiallyAvailableChains := gameBoard.GetWinBoard(gameBoard.ChainLength() + 1) - // check for available chains -validatingChains: - for _, chain := range winningChains { - for _, idx := range chain { - if gameBoard.GetIndexState(idx) != player { - continue validatingChains - } +searching: + for _, potentialPlace := range potentiallyAvailableChains { + if !gameBoard.IsIndexFree(potentialPlace[0]) || !gameBoard.IsIndexFree(potentialPlace[len(potentialPlace)-1]) { + continue } - availableWinningChains = append(availableWinningChains, chain) - } + var gaps []int - // now we have lost of potentially available places - potentiallyAvailableChains := gameBoard.GetWinBoard(gameBoard.ChainLength() + 1) - for _, potentialPlace := range potentiallyAvailableChains { - for _, chain := range availableWinningChains { - if !gameBoard.IsIndexFree(potentialPlace[0]) || !gameBoard.IsIndexFree(potentialPlace[len(potentialPlace)-1]) { - continue + for i := 1; i < len(potentialPlace)-1; i++ { + switch gameBoard.GetIndexState(potentialPlace[i]) { + case letter.LetterNone: + gaps = append(gaps, potentialPlace[i]) + case player.Opposite(): // operation already blocked + continue searching } + } - if reflect.DeepEqual(potentialPlace[1:len(chain)+1], chain) { - result = append(result, potentialPlace[len(potentialPlace)-2]) - - break - } else if reflect.DeepEqual(potentialPlace[2:len(chain)+2], chain) { - result = append(result, potentialPlace[1]) - - break - } + if len(gaps) == 1 { + result = append(result, gaps...) } }