-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
57 lines (48 loc) · 1.24 KB
/
game.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
let fs = require('fs')
function load (fileName) {
let level = fs.readFileSync(fileName).toString('utf8')
let rows = level.split('\n').map(x => x.split(''))
let bunny
let carrots = {}
let walls = {}
rows.forEach((row, y) => {
row.forEach((c, x) => {
if (c === 'B') bunny = { x, y }
if (c === 'C') carrots[`${x}:${y}`] = true
if (c === '|') walls[`${x}:${y}`] = true
})
})
if (!bunny) throw new TypeError('Bad bunny')
function isCarrot (x, y) { return carrots[`${x}:${y}`] }
function isBunny (x, y) { return bunny.x === x && bunny.y === y }
function isWall (x, y) { return walls[`${x}:${y}`] }
// TODO: no wall jumping
function move (x, y) {
if (isWall(bunny.x + x, bunny.y + y)) return
bunny.x += x
bunny.y += y
if (isCarrot(bunny.x, bunny.y)) {
delete carrots[`${bunny.x}:${bunny.y}`]
}
}
function print () {
rows.forEach((row, y) => {
let s = ''
row.forEach((_, x) => {
if (isBunny(x, y)) s += 'B'
else if (isCarrot(x, y)) s += ''
else if (isWall(x, y)) s += '|'
else s += ' '
})
console.log(s)
})
}
bunny.move = move
return {
isCarrot,
isWall,
bunny,
print
}
}
module.exports = load