-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathai.js
52 lines (39 loc) · 1.25 KB
/
ai.js
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
function findBestDirection(game, nSimulations) {
const directions = [
Direction.UP,
Direction.DOWN,
Direction.LEFT,
Direction.RIGHT
]
function evaluateDirection(game, direction) {
let simulationScore = 0
for (let i = 0; i < nSimulations; i += 1) {
const simulationGame = new Game(game.board)
if (!simulationGame.play(direction)) {
return 0
}
let depth = 1
while (!simulationGame.isOver) {
simulationGame.play(Helper.randomFrom(directions))
depth += 1
}
simulationScore += simulationGame.score * depth
}
return simulationScore
}
if (game.isOver) {
throw new Error('game is already over')
}
const randomDirections = directions.slice(0)
Helper.shuffle(randomDirections)
let bestSimulationScore = 0
let bestDirection = null
for (const direction of randomDirections) {
const simulationScore = evaluateDirection(game, direction)
if (simulationScore > bestSimulationScore) {
bestSimulationScore = simulationScore
bestDirection = direction
}
}
return bestDirection
}