-
Notifications
You must be signed in to change notification settings - Fork 0
/
page.js
89 lines (83 loc) · 2.54 KB
/
page.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
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
78
79
80
81
82
83
84
85
86
87
88
89
const worker = new Worker('worker.js')
let game = new Game()
const app = new Vue({
el: '#app',
data() {
return {
direction: Direction,
board: Helper.copyBoard(game.board),
isAiPlaying: false,
lastAiTimings: [],
aiAggressiveness: 'medium'
}
},
computed: {
averageAitimings() {
if (this.lastAiTimings.length === 0) {
return 0
}
const startIndex = Math.max(0, this.lastAiTimings.length - 3)
const timings = this.lastAiTimings.slice(startIndex)
const average = timings.reduce((acc, x) => acc + x, 0) / timings.length
return Math.floor(average)
}
},
methods: {
startNewGame() {
game = new Game()
this.board = Helper.copyBoard(game.board)
this.lastAiTimings = []
},
toggleAi() {
if (game.isOver) {
alert('Game is over! Start a new game')
} else if (this.isAiPlaying) {
this.isAiPlaying = false
} else {
this.isAiPlaying = true
this.postAiWork()
}
},
makeMove(direction) {
if (game.isOver) {
alert('Game is over! Start a new game')
} else {
game.play(direction)
this.board = Helper.copyBoard(game.board)
}
},
postAiWork() {
const nSimulations = ({
'high': 3000,
'medium': 1000,
'low': 200
})[this.aiAggressiveness]
worker.postMessage({
type: 'find-best-direction',
board: game.board,
nSimulations,
})
}
},
mounted() {
setTimeout(() => {
document.getElementById('loading').classList.add('invisible')
}, 1000)
worker.addEventListener('message', ({ data }) => {
switch (data.type) {
case 'find-best-direction': {
const { direction, duration } = data
this.makeMove(direction)
this.lastAiTimings.push(duration)
if (this.isAiPlaying) {
if (game.isOver) {
this.isAiPlaying = false
} else {
this.postAiWork()
}
}
}
}
})
}
})