-
Notifications
You must be signed in to change notification settings - Fork 0
/
kotlin.kt
73 lines (66 loc) · 2.25 KB
/
kotlin.kt
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
class Node(val state: Any, val parent: Node?, val children: MutableList<Node> = mutableListOf()) {
var wins = 0
var visits = 0
var untriedMoves: List<Any> = listOf()
}
fun mcts(initialState: Any, timeLimit: Long, iterations: Int, evaluate: (Any) -> Double) {
val root = Node(initialState, null)
root.untriedMoves = getUntriedMoves(root.state)
val start = System.currentTimeMillis()
var i = 0
while (i < iterations && System.currentTimeMillis() - start < timeLimit) {
val node = select(root)
val winner = playout(node)
backpropagate(node, winner)
i++
}
println("Selected move: " + bestChild(root, 0.0).state)
}
fun select(node: Node): Node {
var current = node
while (!current.untriedMoves.isEmpty() && current.children.isNotEmpty()) {
current = bestChild(current, 1.4)
}
if (current.untriedMoves.isNotEmpty()) {
val move = randomMove(current.untriedMoves)
val newState = doMove(current.state, move)
current = Node(newState, current)
current.untriedMoves = getUntriedMoves(current.state)
}
return current
}
fun randomMove(moves: List<Any>): Any {
val index = (Math.random() * moves.size).toInt()
return moves[index]
}
fun playout(node: Node): Double {
var current = node
while (current.untriedMoves.isNotEmpty()) {
val move = randomMove(current.untriedMoves)
val newState = doMove(current.state, move)
current = Node(newState, current)
current.untriedMoves = getUntriedMoves(current.state)
}
return evaluate(current.state)
}
fun backpropagate(node: Node, winner: Double) {
var current = node
while (current != null) {
current.visits++
current.wins += winner
current = current.parent
}
}
fun bestChild(node: Node, c: Double): Node {
var best = node.children[0]
for (child in node.children) {
val score = (child.wins / child.visits) + c * Math.sqrt(2 * Math.log(node.visits) / child.visits)
if (score > (best.wins / best.visits) + c * Math.sqrt(2 * Math.log(node.visits) / best.visits)) {
best = child
}
}
return best
}
fun getUntriedMoves(state: Any): List<Any> {
// implementation left to user
return listOf()