-
Notifications
You must be signed in to change notification settings - Fork 0
/
minimax.go
66 lines (61 loc) · 1.39 KB
/
minimax.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package main
import (
"math"
)
// fmt.Printf("------------------------------------\n")
// copy.Print()
// fmt.Printf("max: x:%09b o:%09b score:%f depth: %d\n", copy.xBits, copy.oBits, bestMove, depth)
// fmt.Printf("------------------------------------\n")
// copy.Print()
// fmt.Printf("min: x:%09b o:%09b score:%f depth: %d\n", copy.xBits, copy.oBits, bestMove, depth)
func minimax(board Board, depth int, isMaximizing bool) float64 {
copy := board.Copy()
gameOver, msg := copy.CheckGameOver()
if gameOver {
if msg == "O" {
return 1
} else if msg == "X" {
return -1
} else {
return 0
}
}
if isMaximizing {
bestMove := math.Inf(-1)
for i := range copy.cells {
if copy.isOpen(i) {
copy.PlaceO(i)
bestMove = math.Max(bestMove, float64(minimax(copy, depth+1, false)))
copy.ResetCell(i)
}
}
return bestMove
} else {
bestMove := math.Inf(1)
for i := range copy.cells {
if copy.isOpen(i) {
copy.PlaceX(i)
bestMove = math.Min(bestMove, float64(minimax(copy, depth+1, true)))
copy.ResetCell(i)
}
}
return bestMove
}
}
func generateMaximizerMove(board Board) int {
bestScore := math.Inf(-1)
bestMove := 0
copy := board.Copy()
for i := range copy.cells {
if copy.isOpen(i) {
copy.PlaceO(i)
score := minimax(copy, 1, false)
copy.ResetCell(i)
if score > bestScore {
bestScore = score
bestMove = i
}
}
}
return bestMove
}