Skip to content

Commit

Permalink
search: keep track of killer moves
Browse files Browse the repository at this point in the history
  • Loading branch information
e0ff committed Nov 25, 2023
1 parent 032e52c commit 2e01009
Showing 1 changed file with 44 additions and 2 deletions.
46 changes: 44 additions & 2 deletions internal/search/negamax.go
Original file line number Diff line number Diff line change
@@ -1,25 +1,34 @@
package search

import (
"cmp"
"math"
"rosaline/internal/chess"
"rosaline/internal/evaluation"
"slices"
)

const (
initialAlpha = math.MinInt + 1
initialBeta = math.MaxInt - 1

maxNumberKillerMoves = 1024
)

type NegamaxSearcher struct {
evaluator evaluation.Evaluator
drawTable drawTable

killerMoves map[chess.Color][]chess.Move
killerMoveIndex int
}

func NewNegamaxSearcher(evaluator evaluation.Evaluator) NegamaxSearcher {
return NegamaxSearcher{
evaluator: evaluator,
drawTable: newDrawTable(),
evaluator: evaluator,
drawTable: newDrawTable(),
killerMoves: make(map[chess.Color][]chess.Move),
killerMoveIndex: 0,
}
}

Expand All @@ -45,6 +54,15 @@ func (s NegamaxSearcher) Search(position chess.Position, depth int) ScoredMove {
return bestMove
}

func (s NegamaxSearcher) scoreMove(position chess.Position, move chess.Move) int {
turn := position.Turn()
if slices.Contains(s.killerMoves[turn], move) {
return 1000
}

return 0
}

func (s *NegamaxSearcher) doSearch(position chess.Position, alpha int, beta int, depth int, ply int, extensions int) int {
if s.drawTable.IsRepeat(position.Hash()) {
return evaluation.DrawScore
Expand Down Expand Up @@ -73,6 +91,10 @@ func (s *NegamaxSearcher) doSearch(position chess.Position, alpha int, beta int,
return s.evaluator.AbsoluteEvaluation(position)
}

slices.SortFunc(moves, func(m1, m2 chess.Move) int {
return cmp.Compare(s.scoreMove(position, m1), s.scoreMove(position, m2))
})

for _, move := range moves {
s.drawTable.Push(position.Hash())

Expand All @@ -83,6 +105,25 @@ func (s *NegamaxSearcher) doSearch(position chess.Position, alpha int, beta int,
s.drawTable.Pop()

if score >= beta {
if !move.HasFlag(chess.CaputureMoveFlag) {
turn := position.Turn()
length := len(s.killerMoves[turn])
if length >= maxNumberKillerMoves {
if s.killerMoveIndex >= (maxNumberKillerMoves - 1) {
s.killerMoveIndex = 0
}

if !slices.Contains(s.killerMoves[turn], move) {
s.killerMoves[turn][s.killerMoveIndex] = move
s.killerMoveIndex++
}
} else {
if !slices.Contains(s.killerMoves[turn], move) {
s.killerMoves[turn] = append(s.killerMoves[turn], move)
}
}
}

return beta
}

Expand All @@ -97,4 +138,5 @@ func (s *NegamaxSearcher) doSearch(position chess.Position, alpha int, beta int,
// Reset clears any information about searched positions.
func (s *NegamaxSearcher) Reset() {
s.drawTable.Clear()
clear(s.killerMoves)
}

0 comments on commit 2e01009

Please sign in to comment.