/
index.js
100 lines (88 loc) · 2.52 KB
/
index.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
90
91
92
93
94
95
96
97
98
99
100
import { Game } from './game.js'
// Get the canvas graphics context, and start a new game
const game = new Game(
(() => {
const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')
canvas.width = 600
canvas.height = 600
return ctx
})()
)
const togglePathfindingButton = document.getElementById('toggle-pathfinding')
const togglePlayPauseButton = document.getElementById('toggle-play-pause')
const toggleAIButton = document.getElementById('toggle-ai')
const nextFrameButton = document.getElementById('next-frame')
function setPathfinding(showPathfinding) {
game.showPathfinding = showPathfinding
const showOrHide = showPathfinding ? 'Hide' : 'Show'
togglePathfindingButton.textContent = showOrHide + ' pathfinding'
}
function setPaused(paused) {
game.paused = paused
if (paused) {
togglePlayPauseButton.textContent = 'Play'
nextFrameButton.disabled = false
} else {
togglePlayPauseButton.textContent = 'Pause'
nextFrameButton.disabled = true
}
}
let updateTimer
function setAI(ai) {
game.ai = ai
window.clearInterval(updateTimer)
// Get rid of any queued turns
game.snake.queuedTurns = []
if (ai) {
updateTimer = window.setInterval(() => game.update(), 25)
toggleAIButton.textContent = 'Human'
} else {
updateTimer = window.setInterval(() => game.update(), 100)
toggleAIButton.textContent = 'AI'
}
}
setPathfinding(game.showPathfinding)
setPaused(game.paused)
setAI(game.ai)
togglePathfindingButton.addEventListener('click', () => {
togglePathfindingButton.blur()
setPathfinding(!game.showPathfinding)
})
togglePlayPauseButton.addEventListener('click', () => {
togglePlayPauseButton.blur()
setPaused(!game.paused)
})
toggleAIButton.addEventListener('click', () => {
toggleAIButton.blur()
setAI(!game.ai)
})
nextFrameButton.addEventListener('click', () => {
nextFrameButton.blur()
game.update(true)
})
document.addEventListener('keydown', event => {
if (event.key === ' ') {
setPaused(!game.paused)
}
if (event.key === 'h') {
setAI(!game.ai)
}
if (event.key === 'f' && game.paused) {
game.update(true)
}
if (!game.ai) {
if (event.key === 'ArrowUp' || event.key === 'w') {
game.snake.queueTurn('north')
}
if (event.key === 'ArrowDown' || event.key === 's') {
game.snake.queueTurn('south')
}
if (event.key == 'ArrowRight' || event.key === 'd') {
game.snake.queueTurn('east')
}
if (event.key === 'ArrowLeft' || event.key === 'a') {
game.snake.queueTurn('west')
}
}
})