Skip to content

Commit

Permalink
pcplayer engine: refactoring: add getAvailableOptions method and chan…
Browse files Browse the repository at this point in the history
…ge nil strategy to empty slice
  • Loading branch information
gucio321 committed Mar 28, 2022
1 parent 257db0c commit 38cfea7
Showing 1 changed file with 22 additions and 29 deletions.
51 changes: 22 additions & 29 deletions pkg/core/pcplayer/pc_player_engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,51 +115,33 @@ searching:
func GetPCMove(gameBoard *board.Board, pcLetter letter.Letter) (i int) {
playerLetter := pcLetter.Opposite()

var options []int
var options []int = make([]int, 0)

// attack: try to win now
if ok, indexes := canWin(gameBoard, pcLetter); ok {
for _, i := range indexes {
if gameBoard.IsIndexFree(i) {
options = append(options, i)
}
}
options = getAvailableOptions(gameBoard, indexes)

if options != nil {
if len(options) > 0 {
return getRandomNumber(options)
}
}

// defense: check, if user can win
if ok, indexes := canWin(gameBoard, playerLetter); ok {
for _, i := range indexes {
if gameBoard.IsIndexFree(i) {
options = append(options, i)
}
}
options = getAvailableOptions(gameBoard, indexes)

if options != nil {
if len(options) > 0 {
return getRandomNumber(options)
}
}

for _, i := range canWinTwoMoves(gameBoard, pcLetter) {
if gameBoard.IsIndexFree(i) {
options = append(options, i)
}
}

if options != nil {
options = getAvailableOptions(gameBoard, canWinTwoMoves(gameBoard, pcLetter))
if len(options) > 0 {
return getRandomNumber(options)
}

for _, i := range canWinTwoMoves(gameBoard, playerLetter) {
if gameBoard.IsIndexFree(i) {
options = append(options, i)
}
}

if options != nil {
options = getAvailableOptions(gameBoard, canWinTwoMoves(gameBoard, playerLetter))
if len(options) > 0 {
return getRandomNumber(options)
}

Expand Down Expand Up @@ -196,7 +178,7 @@ func GetPCMove(gameBoard *board.Board, pcLetter letter.Letter) (i int) {
return getRandomNumber(playerOppositeCorners)
}

if options != nil {
if len(options) > 0 {
return getRandomNumber(options)
}

Expand All @@ -207,7 +189,7 @@ func GetPCMove(gameBoard *board.Board, pcLetter letter.Letter) (i int) {
}
}

if options != nil {
if len(options) > 0 {
return getRandomNumber(options)
}

Expand Down Expand Up @@ -235,3 +217,14 @@ func getRandomNumber(numbers []int) int {

return result
}

func getAvailableOptions(gameBoard *board.Board, candidates []int) (available []int) {
available = make([]int, 0)
for _, i := range candidates {
if gameBoard.IsIndexFree(i) {
available = append(available, i)
}
}

return available
}

0 comments on commit 38cfea7

Please sign in to comment.