-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathlevels.js
More file actions
476 lines (390 loc) · 13.3 KB
/
levels.js
File metadata and controls
476 lines (390 loc) · 13.3 KB
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
//
// Copyright (c) 2017 Cisco Systems
// Licensed under the MIT License
//
function debug(entry) {
console.log(entry)
}
function fine(entry) {
console.debug(entry)
}
function Maze(structure, walls, phrases, scores, treasure) {
this.structure = structure
this.walls = walls
this.phrases = phrases
this.scores = scores
this.treasure = treasure
this.score = 0
this.position = [1, 1]
}
Maze.prototype.updateScore = function (points) {
this.score += points
}
Maze.prototype.isOver = function () {
return (this.score < 0)
}
Maze.prototype.isWon = function () {
return (this.score >= this.scores[this.treasure])
}
Maze.prototype.tryMove = function (direction) {
debug(`trying ${direction}`)
var result
switch (direction) {
case 'up':
result = this._move(this.position, -1, 0);
break
case 'down':
result = this._move(this.position, 1, 0)
break
case 'left':
result = this._move(this.position, 0, -1)
break
case 'right':
result = this._move(this.position, 0, 1)
break
default:
throw new Error("unknown direction");
}
// update position
this.position = result.pos
// update score
this.updateScore(result.points)
fine(`score updated to ${this.score}`)
// return move outcome
result.direction = direction
result.score = this.score
return result
}
Maze.prototype.up = function () {
return this.tryMove('up');
}
Maze.prototype.down = function () {
return this.tryMove('down');
}
Maze.prototype.left = function () {
return this.tryMove('left');
}
Maze.prototype.right = function () {
return this.tryMove('right');
}
Maze.prototype._getPointsFor = function (character) {
if (!this.scores) {
fine('no scoring for this game')
return 0
}
let points = this.scores[character]
if (!points) {
return 0
}
return points
}
// Returns the outcome of the specified move, but does not actually perform it
Maze.prototype._move = function (pos, x, y) {
let newX = pos[0] + x
let newY = pos[1] + y
// Check what's laying at new positiob
let thingCharacter = this.structure[newX][newY]
// What did we meed
var story = this.phrases[thingCharacter]
debug('> ' + story)
// If this is a wall, stay at current position
if (this.walls.includes(thingCharacter)) {
fine(`staying at: ${pos}`)
return {
'success': false,
'outcome': story,
'thing': this.look(pos),
'pos': pos,
'points': this._getPointsFor(thingCharacter)
}
}
// Move to new position
var newPos = [newX, newY]
fine(`now at: ${newPos}`)
return {
'success': true,
'outcome': 'move successful',
'thing': this.look(newPos),
'pos': newPos,
'points': this._getPointsFor(thingCharacter)
}
}
// Returns what is laying at specified location
Maze.prototype.look = function (pos) {
var x = pos[0]
var y = pos[1]
var thing = this.structure[x][y]
return this.phrases[thing];
}
// Use this function if the output supports Newlines
Maze.prototype.buildMap = function () {
var pos = this.position
var poster = ""
for (var y = 0; y < this.structure.length; y++) {
var line = ""
for (var x = 0; x < this.structure[0].length; x++) {
var char = this.structure[y][x]
if ((y == pos[0]) && x == pos[1]) {
char = 'o'
}
line += char
}
poster += line + "\n"
}
debug("poster:\n" + poster)
return poster
}
// Use this function if the output does NOT supports newlines
Maze.prototype.buildMapAsWrapped = function (linewidth, skipBorders) {
var map = ""
var pos = this.position
for (var y = 0; y < this.structure.length; y++) {
if (!(skipBorders && ((y == 0) || (y == this.structure.length - 1)))) {
var line = ""
for (var x = 0; x < this.structure[0].length; x++) {
var char = this.structure[y][x]
if ((y == pos[0]) && x == pos[1]) {
char = 'o'
}
line += char
}
var left = Math.round((linewidth - line.length) / 2)
var mazeline = line.padStart(left + line.length, "-")
map += mazeline.padEnd(linewidth, "-")
map += " "
}
}
debug("maze map:" + map)
return map
}
// Used to initialize the maze
Maze.prototype.pickInitialPosition = function (emptyChar) {
if (!emptyChar) emptyChar = ' '
// Ping a random number, on an empty spot
while (true) {
var y = Math.round(Math.random() * (this.structure.length - 2) + 1)
var x = Math.round(Math.random() * (this.structure[0].length - 2) + 1)
fine(`picked x: ${x}, y: ${y}`)
if (this.structure[y][x] == emptyChar) {
fine(`position is clear, storing...`)
return this._setPosition(x, y)
}
}
}
Maze.prototype._setPosition = function (x, y) {
this.position = [y, x]
return this.position
}
//
// Utilities
//
function showProgress(count, delay, cb, final, initial) {
return new Promise(function (resolve, reject) {
var counter = 0
if (!initial) initial = ""
var progress = ".....".padEnd(count, '.')
var timer = setInterval(function (event) {
cb(initial + progress.substring(0, counter + 1))
counter++;
if (counter >= count) {
clearInterval(timer)
resolve(cb(final))
}
}, delay)
})
}
//
// Room Controls
//
const xapi = require('xapi');
function showScore(message) {
console.debug('refresh score')
// Display current score unless a message is specifid
if (!message) {
message = game.score
}
xapi.command('UserInterface Extensions Widget SetValue', {
WidgetId: 'score',
Value: message
})
}
function showInstructions(message) {
//console.debug('updating instructions')
xapi.command('UserInterface Extensions Widget SetValue', {
WidgetId: 'instructions',
Value: message
})
}
function showDifficulty(level) {
xapi.command('UserInterface Extensions Widget SetValue', {
WidgetId: 'difficulty',
Value: level
})
}
// Displays the outcome of the latest move
function showOutcome(res, initial) {
console.log('computing instructions from latest move')
// Tell the reason if the move was not successful
let message = res.outcome
if (res.success) {
// Tell the thing met at the new location
message = res.thing
}
// update instructions
showProgress(5, 500, showInstructions, message, initial).then(() => {
// Check score, if <0 game over
if (game.isOver()) {
showScore("Game Over")
}
else {
// refresh score
showScore()
}
})
}
// Displays the Maze's map on an Alert Panel
function showHelp() {
console.debug("showing map in Alert Panel")
// Does the user has enough points ?
if (game.score < 500) {
console.debug("not enough points to show the map")
showInstructions("sorry you don't have enough points")
return
}
// Remove 500 points
game.updateScore(-500)
// The maze needs to be wrapped as In-Room Controls do not support multi-lines
// Each line's width depends on the device: 51 for Touch10 dispay, 31 for Screen display
xapi.status.get("SystemUnit ProductPlatform").then((product) => {
console.debug(`running on a ${product}`)
let width = 45 // when the Alert is shown on a Touch 10
if (product == "DX80") {
console.debug('has no Touch10 attached')
width = 30 // when the Alert is shown on a screen
}
// Show Alert panel
// Increase the duration with the difficulty to leave time for the user to memorize the map
// Note that the panel will stay on if duration is >= 10.
xapi.command('UserInterface Message Alert Display', {
Title: 'With a little help from ... the bot',
Text: game.buildMapAsWrapped(width, true),
Duration: 5 * (difficulty + 1)
}).then(() => {
showScore()
})
})
}
function onGui(event) {
if (event.Type == 'clicked') {
// Restart button
if (event.WidgetId == 'restart') {
restart()
return
}
// Check game is still running
if (game.isOver()) {
showInstructions("Sorry you did not make it! Hit restart to play again.")
return
}
// Check treasure has not been found
if (game.isWon()) {
showInstructions("Looks like you already found the treasure! Hit restart to play again.")
return
}
if (event.WidgetId == 'directions') {
var direction = event.Value
// If center was hitted, display help
if (direction == 'center') {
showHelp()
return
}
showInstructions(`moving ${direction}`)
var res = game.tryMove(direction)
showOutcome(res, `moving ${direction}`)
return
}
}
if (event.Type == 'pressed') {
if (event.WidgetId == 'difficulty') {
difficulty = event.Value
debug(`set difficulty level to: ${difficulty}`)
}
}
}
xapi.event.on('UserInterface Extensions Widget Action', onGui);
function restart() {
console.log('resetting the maze')
// Show current level while game initializes
showScore(levels[difficulty])
// Create the maze
game = new Maze(structures[difficulty], walls, phrases, scores, '?')
game.pickInitialPosition('_')
game.updateScore(1000)
// Update UI
showProgress(10, 200, showInstructions, 'Then here you are: lost in an hostile maze, looking for a treasure. Pick a direction...', 'loading')
.then(() => {
showScore()
showDifficulty(difficulty)
})
}
//
// Maze artefacts
//
// Build structures
var structures = []
var structure = []
structure[0] = ['|', '-', '-', '-', '-', '-', '|']
structure[1] = ['|', 'M', 'C', '_', '_', '_', '|']
structure[2] = ['|', '_', '_', 'X', 'D', '_', '|']
structure[3] = ['|', '_', 'X', '?', 'X', '_', '|']
structure[4] = ['|', '_', '_', '_', '_', 'X', '|']
structure[5] = ['|', '-', '-', '-', '-', '-', '|']
structures[0] = structure
structure = []
structure[0] = ['|', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '|']
structure[1] = ['|', '_', '_', '_', 'D', 'X', '_', '_', '_', 'M', '_', 'X', '_', '_', 'X', '_', '|']
structure[2] = ['|', 'C', 'X', '_', '_', 'X', '_', 'X', '_', '_', '_', '_', '_', 'X', 'X', 'C', '|']
structure[3] = ['|', '_', '_', 'X', '_', '_', '_', 'D', 'X', 'C', '_', 'X', '_', '_', '_', '_', '|']
structure[4] = ['|', 'D', '_', '?', 'X', '_', '_', '_', '_', 'X', '_', 'X', '_', '_', 'X', '_', '|']
structure[5] = ['|', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '|']
structures[1] = structure
structure = []
structure[0] = ['|', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '|']
structure[1] = ['|', 'C', '_', '_', 'D', '_', 'M', '_', 'X', '_', '_', '_', 'C', 'D', '_', 'C', '_', '_', '_', 'X', '_', '_', '_', '_', '_', '_', 'X', 'C', '_', 'D', '_', '_', 'X', '|']
structure[2] = ['|', '_', '_', 'X', 'X', '_', '_', '_', 'X', 'C', 'M', '_', 'X', '_', '_', '_', 'M', 'D', '_', '_', 'X', '_', '_', 'X', 'D', '_', '_', 'X', '_', '_', '_', 'X', 'C', '|']
structure[3] = ['|', '_', 'X', 'C', '_', 'X', 'X', '_', '_', '_', 'X', 'X', '_', '_', 'D', 'X', 'X', '_', '_', 'X', '_', 'M', 'X', 'C', '_', '_', 'M', '_', '_', 'X', '_', '_', '_', '|']
structure[4] = ['|', '_', '_', 'D', '_', '_', '?', 'X', '_', 'X', 'C', '_', '_', 'X', 'X', 'X', 'D', '_', '_', '_', 'C', '_', '_', '_', 'X', '_', '_', '_', 'C', 'X', '_', 'D', 'M', '|']
structure[5] = ['|', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '|']
structures[2] = structure
var walls = ['|', '-', 'X']
var phrases = {}
phrases['|'] = "cannot get there, this a maze border you just hitted"
phrases['-'] = "cannot get there, this a maze border you just hitted"
phrases['|'] = "cannot get there, this a maze border you just hitted"
phrases['X'] = "ouch, you bumped a wall"
phrases['_'] = "nothing here, let's continue exploring."
phrases['C'] = "hello kitty, you look hungry. Are you lost too? Jump in."
phrases['D'] = "WOW, an agressive dog is lying here. You've been bitten!"
phrases['M'] = "Too late, the ugly monster saw you. RUN!!!"
phrases['?'] = "CONGRATS, you found the treasure!!!"
var scores = {}
scores['|'] = -200
scores['-'] = -200
scores['|'] = -200
scores['X'] = -100
scores['_'] = 50
scores['C'] = 200
scores['D'] = -200
scores['M'] = -500
scores['?'] = 5000
var levels = []
levels[0] = 'Rookie'
levels[1] = 'Seasoned'
levels[2] = 'Expert'
var difficulty = 0
//
// Start game
//
console.info("Starting Maze game, v1.0.0")
var game
restart()