forked from AlexNisnevich/untrusted
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmap.js
710 lines (581 loc) · 23.1 KB
/
map.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
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
function Map(display, __game) {
/* private variables */
var __player;
var __grid;
var __dynamicObjects = [];
var __objectDefinitions;
var __lines;
var __dom;
var __domCSS = '';
var __allowOverwrite;
var __keyDelay;
var __refreshRate;
var __intervals = [];
var __chapterHideTimeout;
/* unexposed variables */
this._properties = {};
this._display = display;
this._dummy = false; // overridden by dummyMap in validate.js
this._status = '';
/* wrapper */
function wrapExposedMethod(f, map) {
return function () {
var args = arguments;
return __game._callUnexposedMethod(function () {
return f.apply(map, args);
});
};
};
/* unexposed getters */
this._getObjectDefinition = function(objName) {
if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._getObjectDefinition()';}
return __objectDefinitions[objName];
};
this._getObjectDefinitions = function() {
if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._getObjectDefinitions()';}
return __objectDefinitions;
};
this._getGrid = function () {
if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._getGrid()';}
return __grid;
};
this._getLines = function() {
if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._getLines()';}
return __lines;
};
/* exposed getters */
this.getDynamicObjects = function () {
// copy dynamic object list to fix issue#166
var copy = [];
for (var i = 0; i < __dynamicObjects.length; i++) {
copy[i] = __dynamicObjects[i];
}
return copy;
};
this.getPlayer = function () { return __player; };
this.getWidth = function () { return __game._dimensions.width; };
this.getHeight = function () { return __game._dimensions.height; };
/* unexposed methods */
this._reset = function () {
if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._reset()';}
__objectDefinitions = __game.getListOfObjects();
this._display.clear();
__grid = new Array(__game._dimensions.width);
for (var x = 0; x < __game._dimensions.width; x++) {
__grid[x] = new Array(__game._dimensions.height);
for (var y = 0; y < __game._dimensions.height; y++) {
__grid[x][y] = {type: 'empty'};
}
}
this.getDynamicObjects().forEach(function (obj) {
obj._destroy(true);
});
__dynamicObjects = [];
__player = null;
this._clearIntervals();
__lines = [];
__dom = '';
this._overrideKeys = {};
// preload stylesheet for DOM level
$.get('styles/dom.css', function (css) {
__domCSS = css;
});
this.finalLevel = false;
this._callbackValidationFailed = false;
};
this._clearIntervals = function() {
if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._clearIntervals()';}
for (var i = 0; i < __intervals.length; i++) {
clearInterval(__intervals[i]);
}
__intervals = [];
};
this._ready = function () {
if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._ready()';}
var map = this;
// set refresh rate if one is specified
if (__refreshRate) {
// wrapExposedMethod is necessary here to prevent the game from thinking
// `map._status` is an unauthorized attempt to access a private attribute.
map.startTimer(wrapExposedMethod(function () {
// refresh the map
map.refresh();
// rewrite status
if (map._status) {
map.writeStatus(map._status);
}
// check for nonstandard victory condition
if (typeof(__game.objective) === 'function' && __game.objective(map)) {
__game._moveToNextLevel();
}
}), __refreshRate);
}
};
this._setProperties = function (mapProperties) {
if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._setProperties()';}
// set defaults
this._properties = {};
__allowOverwrite = false;
__keyDelay = 0;
__refreshRate = null;
// now set any properties that were passed in
if (mapProperties) {
this._properties = mapProperties;
if (mapProperties.allowOverwrite === true) {
__allowOverwrite = true;
}
if (mapProperties.keyDelay) {
__keyDelay = mapProperties.keyDelay;
}
if (mapProperties.refreshRate) {
__refreshRate = mapProperties.refreshRate;
}
}
};
this._canMoveTo = function (x, y, myType) {
if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._canMoveTo()';}
var x = Math.floor(x); var y = Math.floor(y);
if (x < 0 || x >= __game._dimensions.width || y < 0 || y >= __game._dimensions.height) {
return false;
}
// look for static objects that can serve as obstacles
var objType = __grid[x][y].type;
var object = __objectDefinitions[objType];
if (object.impassable) {
if (myType && object.passableFor && object.passableFor.indexOf(myType) > -1) {
// this object is of a type that can pass the obstacle
return true;
} else if (typeof object.impassable === 'function') {
// the obstacle is impassable only in certain circumstances
try {
return this._validateCallback(function () {
return !object.impassable(__player, object);
});
} catch (e) {
display.writeStatus(e.toString());
}
} else {
// the obstacle is always impassable
return false;
}
} else if (myType && object.impassableFor && object.impassableFor.indexOf(myType) > -1) {
// this object is of a type that cannot pass the obstacle
return false;
} else {
// no obstacle
return true;
}
};
// Returns the object of the given type closest to target coordinates
this._findNearestToPoint = function (type, targetX, targetY) {
if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._findNearestToPoint()';}
var foundObjects = [];
// look for static objects
for (var x = 0; x < this.getWidth(); x++) {
for (var y = 0; y < this.getHeight(); y++) {
if (__grid[x][y].type === type) {
foundObjects.push({x: x, y: y});
}
}
}
// look for dynamic objects
for (var i = 0; i < __dynamicObjects.length; i++) {
var object = __dynamicObjects[i];
if (object.getType() === type) {
foundObjects.push({x: object.getX(), y: object.getY()});
}
}
// look for player
if (type === 'player') {
foundObjects.push({x: __player.getX(), y: __player.getY()});
}
var dists = [];
for (var i = 0; i < foundObjects.length; i++) {
var obj = foundObjects[i];
dists[i] = Math.sqrt(Math.pow(targetX - obj.x, 2) + Math.pow(targetY - obj.y, 2));
// We want to find objects distinct from ourselves
if (dists[i] === 0) {
dists[i] = 999;
}
}
var minDist = Math.min.apply(Math, dists);
var closestTarget = foundObjects[dists.indexOf(minDist)];
return closestTarget;
};
this._isPointOccupiedByDynamicObject = function (x, y) {
if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._isPointOccupiedByDynamicObject()';}
var x = Math.floor(x); var y = Math.floor(y);
for (var i = 0; i < __dynamicObjects.length; i++) {
var object = __dynamicObjects[i];
if (object.getX() === x && object.getY() === y) {
return true;
}
}
return false;
};
this._findDynamicObjectAtPoint = function (x, y) {
if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._findDynamicObjectAtPoint()';}
var x = Math.floor(x); var y = Math.floor(y);
for (var i = 0; i < __dynamicObjects.length; i++) {
var object = __dynamicObjects[i];
if (object.getX() === x && object.getY() === y) {
return object;
}
}
return false;
};
this._moveAllDynamicObjects = function () {
if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._moveAllDynamicObjects()';}
// the way things work right now, teleporters must take precedence
// over all other objects -- otherwise, pointers.jsx will not work
// correctly.
// TODO: make this not be the case
// "move" teleporters
__dynamicObjects.filter(function (object) {
return (object.getType() === 'teleporter');
}).forEach(function(object) {
object._onTurn();
});
// move everything else
__dynamicObjects.filter(function (object) {
return (object.getType() !== 'teleporter');
}).forEach(function(object) {
object._onTurn();
});
// refresh only at the end
this.refresh();
};
this._removeItemFromMap = function (x, y, klass) {
if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._removeItemFromMap()';}
var x = Math.floor(x); var y = Math.floor(y);
if (__grid[x][y].type === klass) {
__grid[x][y].type = 'empty';
}
};
this._reenableMovementForPlayer = function (player) {
if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._reenableMovementForPlayer()';}
if (!this._callbackValidationFailed) {
setTimeout(function () {
player._canMove = true;
}, __keyDelay);
}
};
this._hideChapter = function() {
if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._hideChapter()';}
// start fading out chapter immediately
// unless it's a death message, in which case wait 2.5 sec
clearInterval(__chapterHideTimeout);
__chapterHideTimeout = setTimeout(function () {
$('#chapter').fadeOut(1000);
}, $('#chapter').hasClass('death') ? 2500 : 0);
// also, clear any status text if map is refreshing automatically (e.g. boss level)
this._status = '';
};
this._refreshDynamicObjects = function() {
if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._refreshDynamicObjects()';}
__dynamicObjects = __dynamicObjects.filter(function (obj) { return !obj.isDestroyed(); });
};
this._countTimers = function() {
if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._countTimers()';}
return __intervals.length;
}
/* (unexposed) wrappers for game methods */
this._startOfStartLevelReached = function() {
__game._startOfStartLevelReached = true;
};
this._endOfStartLevelReached = function() {
__game._endOfStartLevelReached = true;
};
this._playSound = function (sound) {
if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._playSound()';}
__game.sound.playSound(sound);
};
this._validateCallback = function (callback) {
if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._validateCallback()';}
return __game.validateCallback(callback);
};
/* exposed methods */
this.refresh = wrapExposedMethod(function () {
if (__dom) {
this._display.clear();
var domHTML = __dom[0].outerHTML
.replace(/"/g, "'")
.replace(/<hr([^>]*)>/g, '<hr $1 />')
.replace(/<img([^>]*)>/g, '<img $1 />');
this._display.renderDom(domHTML, __domCSS);
} else {
this._display.drawAll(this);
}
__game.drawInventory();
}, this);
this.countObjects = wrapExposedMethod(function (type) {
var count = 0;
// count static objects
for (var x = 0; x < this.getWidth(); x++) {
for (var y = 0; y < this.getHeight(); y++) {
if (__grid[x][y].type === type) {
count++;
}
}
}
// count dynamic objects
__dynamicObjects.forEach(function (obj) {
if (obj.getType() === type) {
count++;
}
})
return count;
}, this);
this.placeObject = wrapExposedMethod(function (x, y, type) {
var x = Math.floor(x); var y = Math.floor(y);
if (!__objectDefinitions[type]) {
throw "There is no type of object named " + type + "!";
}
if (__player && x == __player.getX() && y == __player.getY()) {
throw "Can't place object on top of player!";
}
if (typeof(__grid[x]) === 'undefined' || typeof(__grid[x][y]) === 'undefined') {
return;
// throw "Not a valid location to place an object!";
}
if (__objectDefinitions[type].type === 'dynamic') {
// dynamic object
__dynamicObjects.push(new DynamicObject(this, type, x, y, __game));
} else {
// static object
if (__grid[x][y].type === 'empty' || __grid[x][y].type === type || __allowOverwrite) {
__grid[x][y].type = type;
} else {
throw "There is already an object at (" + x + ", " + y + ")!";
}
}
}, this);
this.placePlayer = wrapExposedMethod(function (x, y) {
var x = Math.floor(x); var y = Math.floor(y);
if (__player) {
throw "Can't place player twice!";
}
__player = new __game._playerPrototype(x, y, this, __game);
__game.saveReferenceImplementations(null, __player);
this._display.drawAll(this);
}, this);
this.createFromGrid = wrapExposedMethod(function (grid, tiles, xOffset, yOffset) {
for (var y = 0; y < grid.length; y++) {
var line = grid[y];
for (var x = 0; x < line.length; x++) {
var tile = line[x];
var type = tiles[tile];
if (type === 'player') {
this.placePlayer(x + xOffset, y + yOffset);
} else if (type) {
this.placeObject(x + xOffset, y + yOffset, type);
}
}
}
}, this);
this.setSquareColor = wrapExposedMethod(function (x, y, bgColor) {
var x = Math.floor(x); var y = Math.floor(y);
__grid[x][y].bgColor = bgColor;
}, this);
this.defineObject = wrapExposedMethod(function (name, properties) {
if (__objectDefinitions[name]) {
throw "There is already a type of object named " + name + "!";
}
if (properties.interval && properties.interval < 100) {
throw "defineObject(): minimum interval is 100 milliseconds";
}
__objectDefinitions[name] = properties;
}, this);
this.getObjectTypeAt = wrapExposedMethod(function (x, y) {
var x = Math.floor(x); var y = Math.floor(y);
// Bazek: We should always check, if the coordinates are inside of map!
if (x >= 0 && x < this.getWidth() && y >= 0 && y < this.getHeight())
return __grid[x][y].type;
else
return '';
}, this);
this.getAdjacentEmptyCells = wrapExposedMethod(function (x, y) {
var x = Math.floor(x); var y = Math.floor(y);
var map = this;
var actions = ['right', 'down', 'left', 'up'];
var adjacentEmptyCells = [];
$.each(actions, function (i, action) {
switch (actions[i]) {
case 'right':
var child = [x+1, y];
break;
case 'left':
var child = [x-1, y];
break;
case 'down':
var child = [x, y+1];
break;
case 'up':
var child = [x, y-1];
break;
}
// Bazek: We need to check, if child is inside of map!
var childInsideMap = child[0] >= 0 && child[0] < map.getWidth() && child[1] >= 0 && child[1] < map.getHeight();
if (childInsideMap && map.getObjectTypeAt(child[0], child[1]) === 'empty') {
adjacentEmptyCells.push([child, action]);
}
});
return adjacentEmptyCells;
}, this);
this.startTimer = wrapExposedMethod(function(timer, delay) {
if (!delay) {
throw "startTimer(): delay not specified"
} else if (delay < 25) {
throw "startTimer(): minimum delay is 25 milliseconds";
}
var validate = this._validateCallback;
__intervals.push(setInterval(function(){validate(timer)}, delay));
}, this);
this.timeout = wrapExposedMethod(function(timer, delay) {
if (!delay) {
throw "timeout(): delay not specified"
} else if (delay < 25) {
throw "timeout(): minimum delay is 25 milliseconds";
}
var validate = this._validateCallback;
__intervals.push(setTimeout(function(){validate(timer)}, delay));
}, this);
this.displayChapter = wrapExposedMethod(function(chapterName, cssClass) {
if (__game._displayedChapters.indexOf(chapterName) === -1) {
$('#chapter').html(chapterName.replace("\n","<br>"));
$('#chapter').removeClass().show();
if (cssClass) {
$('#chapter').addClass(cssClass);
} else {
__game._displayedChapters.push(chapterName);
}
setTimeout(function () {
$('#chapter').fadeOut();
}, 5 * 1000);
}
}, this);
this.writeStatus = wrapExposedMethod(function(status) {
this._status = status;
if (__refreshRate) {
// write the status immediately
display.writeStatus(status);
} else {
// wait 100 ms for redraw reasons
setTimeout(function () {
display.writeStatus(status);
}, 100);
}
}, this);
// used by validators
// returns true iff called at the start of the level (that is, on DummyMap)
// returns false iff called by validateCallback (that is, on the actual map)
this.isStartOfLevel = wrapExposedMethod(function () {
return this._dummy;
}, this);
/* canvas-related stuff */
this.getCanvasContext = wrapExposedMethod(function() {
var ctx = $('#drawingCanvas')[0].getContext('2d');
if(!this._dummy) {
var opts = this._display.getOptions();
ctx.font = opts.fontSize+"px " +opts.fontFamily;
}
return ctx;
}, this);
this.getCanvasCoords = wrapExposedMethod(function() {
var x, y;
if(arguments.length == 1) {
var obj = arguments[0];
x = obj.getX();
y = obj.getY();
} else {
x = arguments[0];
y = arguments[1];
}
var canvas = $('#drawingCanvas')[0];
return {
x: (x + 0.5) * canvas.width / __game._dimensions.width,
y: (y + 0.5) * canvas.height / __game._dimensions.height
};
}, this);
this.getRandomColor = wrapExposedMethod(function(start, end) {
var mean = [
Math.floor((start[0] + end[0]) / 2),
Math.floor((start[1] + end[1]) / 2),
Math.floor((start[2] + end[2]) / 2)
];
var std = [
Math.floor((end[0] - start[0]) / 2),
Math.floor((end[1] - start[1]) / 2),
Math.floor((end[2] - start[2]) / 2)
];
return ROT.Color.toHex(ROT.Color.randomize(mean, std));
}, this);
this.createLine = wrapExposedMethod(function(start, end, callback) {
__lines.push({'start': start, 'end': end, 'callback': callback});
}, this);
this.testLineCollisions = wrapExposedMethod(function(player) {
var threshold = 7;
var playerCoords = this.getCanvasCoords(player);
__lines.forEach(function (line) {
if (pDistance(playerCoords.x, playerCoords.y,
line.start[0], line.start[1],
line.end[0], line.end[1]) < threshold) {
line.callback(__player);
}
})
}, this);
/* for DOM manipulation level */
this.getDOM = wrapExposedMethod(function () {
return __dom;
})
this.createFromDOM = wrapExposedMethod(function(dom) {
__dom = dom;
}, this);
this.updateDOM = wrapExposedMethod(function(dom) {
__dom = dom;
}, this);
this.overrideKey = wrapExposedMethod(function(keyName, callback) {
this._overrideKeys[keyName] = callback;
}, this);
/* validators */
this.validateAtLeastXObjects = wrapExposedMethod(function(num, type) {
var count = this.countObjects(type);
if (count < num) {
throw 'Not enough ' + type + 's on the map! Expected: ' + num + ', found: ' + count;
}
}, this);
this.validateAtMostXObjects = wrapExposedMethod(function(num, type) {
var count = this.countObjects(type);
if (count > num) {
throw 'Too many ' + type + 's on the map! Expected: ' + num + ', found: ' + count;
}
}, this);
this.validateExactlyXManyObjects = wrapExposedMethod(function(num, type) {
var count = this.countObjects(type);
if (count != num) {
throw 'Wrong number of ' + type + 's on the map! Expected: ' + num + ', found: ' + count;
}
}, this);
this.validateAtMostXDynamicObjects = wrapExposedMethod(function(num) {
var count = this.getDynamicObjects().length;
if (count > num) {
throw 'Too many dynamic objects on the map! Expected: ' + num + ', found: ' + count;
}
}, this);
this.validateNoTimers = wrapExposedMethod(function() {
var count = this._countTimers();
if (count > 0) {
throw 'Too many timers set on the map! Expected: 0, found: ' + count;
}
}, this);
this.validateAtLeastXLines = wrapExposedMethod(function(num) {
var count = this._getLines().length;
if (count < num) {
throw 'Not enough lines on the map! Expected: ' + num + ', found: ' + count;
}
}, this);
/* initialization */
this._reset();
// call secureObject to prevent user code from tampering with private attributes
__game.secureObject(this, "map.");
}