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
67
68
69
70
71
72
73
74
75
76
77
|
func blackjackSolverMinimax(cards []int) int {
cache := make(map[string]int)
encodeState := func(pSum, dSum, pos int, playerTurn bool) string {
turn := 0
if playerTurn {
turn = 1
}
return fmt.Sprintf("%d_%d_%d_%d", pSum, dSum, pos, turn)
}
var minimax func(pSum, dSum, pos int, playerTurn bool, alpha, beta int) int
minimax = func(pSum, dSum, pos int, playerTurn bool, alpha, beta int) int {
// Terminal conditions
if pSum > 21 {
return -1 // Player bust
}
if dSum > 21 {
return 1 // Dealer bust
}
if pos >= len(cards) {
if pSum > dSum {
return 1
}
if pSum < dSum {
return -1
}
return 0
}
state := encodeState(pSum, dSum, pos, playerTurn)
if val, exists := cache[state]; exists {
return val
}
var result int
if playerTurn {
result = math.MinInt32
// Option 1: Hit
hitVal := minimax(pSum+cards[pos], dSum, pos+1, true, alpha, beta)
result = max(result, hitVal)
alpha = max(alpha, result)
if beta <= alpha {
cache[state] = result
return result
}
// Option 2: Stand (switch to dealer)
standVal := minimax(pSum, dSum, pos, false, alpha, beta)
result = max(result, standVal)
} else {
// Dealer's turn - deterministic
if dSum <= 16 {
result = minimax(pSum, dSum+cards[pos], pos+1, false, alpha, beta)
} else {
// Dealer stands
if pSum > dSum {
result = 1
} else if pSum < dSum {
result = -1
} else {
result = 0
}
}
}
cache[state] = result
return result
}
pStart := cards[0] + cards[2]
dStart := cards[1] + cards[3]
return minimax(pStart, dStart, 4, true, math.MinInt32, math.MaxInt32)
}
|