-
Notifications
You must be signed in to change notification settings - Fork 1
/
rot.js
5405 lines (4699 loc) · 138 KB
/
rot.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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
This is rot.js, the ROguelike Toolkit in JavaScript.
Version 0.7~dev, generated on Tue Dec 12 13:31:09 CET 2017.
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([], factory);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
} else {
// Browser globals (root is window)
root.ROT = factory();
}
}(this, function() {
/**
* @namespace Top-level ROT namespace
*/
var ROT = {
/**
* @returns {bool} Is rot.js supported by this browser?
*/
isSupported: function() {
return !!(document.createElement("canvas").getContext && Function.prototype.bind);
},
/** Default with for display and map generators */
DEFAULT_WIDTH: 80,
/** Default height for display and map generators */
DEFAULT_HEIGHT: 25,
/** Directional constants. Ordering is important! */
DIRS: {
"4": [
[ 0, -1],
[ 1, 0],
[ 0, 1],
[-1, 0]
],
"8": [
[ 0, -1],
[ 1, -1],
[ 1, 0],
[ 1, 1],
[ 0, 1],
[-1, 1],
[-1, 0],
[-1, -1]
],
"6": [
[-1, -1],
[ 1, -1],
[ 2, 0],
[ 1, 1],
[-1, 1],
[-2, 0]
]
},
/** Cancel key. */
VK_CANCEL: 3,
/** Help key. */
VK_HELP: 6,
/** Backspace key. */
VK_BACK_SPACE: 8,
/** Tab key. */
VK_TAB: 9,
/** 5 key on Numpad when NumLock is unlocked. Or on Mac, clear key which is positioned at NumLock key. */
VK_CLEAR: 12,
/** Return/enter key on the main keyboard. */
VK_RETURN: 13,
/** Reserved, but not used. */
VK_ENTER: 14,
/** Shift key. */
VK_SHIFT: 16,
/** Control key. */
VK_CONTROL: 17,
/** Alt (Option on Mac) key. */
VK_ALT: 18,
/** Pause key. */
VK_PAUSE: 19,
/** Caps lock. */
VK_CAPS_LOCK: 20,
/** Escape key. */
VK_ESCAPE: 27,
/** Space bar. */
VK_SPACE: 32,
/** Page Up key. */
VK_PAGE_UP: 33,
/** Page Down key. */
VK_PAGE_DOWN: 34,
/** End key. */
VK_END: 35,
/** Home key. */
VK_HOME: 36,
/** Left arrow. */
VK_LEFT: 37,
/** Up arrow. */
VK_UP: 38,
/** Right arrow. */
VK_RIGHT: 39,
/** Down arrow. */
VK_DOWN: 40,
/** Print Screen key. */
VK_PRINTSCREEN: 44,
/** Ins(ert) key. */
VK_INSERT: 45,
/** Del(ete) key. */
VK_DELETE: 46,
/***/
VK_0: 48,
/***/
VK_1: 49,
/***/
VK_2: 50,
/***/
VK_3: 51,
/***/
VK_4: 52,
/***/
VK_5: 53,
/***/
VK_6: 54,
/***/
VK_7: 55,
/***/
VK_8: 56,
/***/
VK_9: 57,
/** Colon (:) key. Requires Gecko 15.0 */
VK_COLON: 58,
/** Semicolon (;) key. */
VK_SEMICOLON: 59,
/** Less-than (<) key. Requires Gecko 15.0 */
VK_LESS_THAN: 60,
/** Equals (=) key. */
VK_EQUALS: 61,
/** Greater-than (>) key. Requires Gecko 15.0 */
VK_GREATER_THAN: 62,
/** Question mark (?) key. Requires Gecko 15.0 */
VK_QUESTION_MARK: 63,
/** Atmark (@) key. Requires Gecko 15.0 */
VK_AT: 64,
/***/
VK_A: 65,
/***/
VK_B: 66,
/***/
VK_C: 67,
/***/
VK_D: 68,
/***/
VK_E: 69,
/***/
VK_F: 70,
/***/
VK_G: 71,
/***/
VK_H: 72,
/***/
VK_I: 73,
/***/
VK_J: 74,
/***/
VK_K: 75,
/***/
VK_L: 76,
/***/
VK_M: 77,
/***/
VK_N: 78,
/***/
VK_O: 79,
/***/
VK_P: 80,
/***/
VK_Q: 81,
/***/
VK_R: 82,
/***/
VK_S: 83,
/***/
VK_T: 84,
/***/
VK_U: 85,
/***/
VK_V: 86,
/***/
VK_W: 87,
/***/
VK_X: 88,
/***/
VK_Y: 89,
/***/
VK_Z: 90,
/***/
VK_CONTEXT_MENU: 93,
/** 0 on the numeric keypad. */
VK_NUMPAD0: 96,
/** 1 on the numeric keypad. */
VK_NUMPAD1: 97,
/** 2 on the numeric keypad. */
VK_NUMPAD2: 98,
/** 3 on the numeric keypad. */
VK_NUMPAD3: 99,
/** 4 on the numeric keypad. */
VK_NUMPAD4: 100,
/** 5 on the numeric keypad. */
VK_NUMPAD5: 101,
/** 6 on the numeric keypad. */
VK_NUMPAD6: 102,
/** 7 on the numeric keypad. */
VK_NUMPAD7: 103,
/** 8 on the numeric keypad. */
VK_NUMPAD8: 104,
/** 9 on the numeric keypad. */
VK_NUMPAD9: 105,
/** * on the numeric keypad. */
VK_MULTIPLY: 106,
/** + on the numeric keypad. */
VK_ADD: 107,
/***/
VK_SEPARATOR: 108,
/** - on the numeric keypad. */
VK_SUBTRACT: 109,
/** Decimal point on the numeric keypad. */
VK_DECIMAL: 110,
/** / on the numeric keypad. */
VK_DIVIDE: 111,
/** F1 key. */
VK_F1: 112,
/** F2 key. */
VK_F2: 113,
/** F3 key. */
VK_F3: 114,
/** F4 key. */
VK_F4: 115,
/** F5 key. */
VK_F5: 116,
/** F6 key. */
VK_F6: 117,
/** F7 key. */
VK_F7: 118,
/** F8 key. */
VK_F8: 119,
/** F9 key. */
VK_F9: 120,
/** F10 key. */
VK_F10: 121,
/** F11 key. */
VK_F11: 122,
/** F12 key. */
VK_F12: 123,
/** F13 key. */
VK_F13: 124,
/** F14 key. */
VK_F14: 125,
/** F15 key. */
VK_F15: 126,
/** F16 key. */
VK_F16: 127,
/** F17 key. */
VK_F17: 128,
/** F18 key. */
VK_F18: 129,
/** F19 key. */
VK_F19: 130,
/** F20 key. */
VK_F20: 131,
/** F21 key. */
VK_F21: 132,
/** F22 key. */
VK_F22: 133,
/** F23 key. */
VK_F23: 134,
/** F24 key. */
VK_F24: 135,
/** Num Lock key. */
VK_NUM_LOCK: 144,
/** Scroll Lock key. */
VK_SCROLL_LOCK: 145,
/** Circumflex (^) key. Requires Gecko 15.0 */
VK_CIRCUMFLEX: 160,
/** Exclamation (!) key. Requires Gecko 15.0 */
VK_EXCLAMATION: 161,
/** Double quote () key. Requires Gecko 15.0 */
VK_DOUBLE_QUOTE: 162,
/** Hash (#) key. Requires Gecko 15.0 */
VK_HASH: 163,
/** Dollar sign ($) key. Requires Gecko 15.0 */
VK_DOLLAR: 164,
/** Percent (%) key. Requires Gecko 15.0 */
VK_PERCENT: 165,
/** Ampersand (&) key. Requires Gecko 15.0 */
VK_AMPERSAND: 166,
/** Underscore (_) key. Requires Gecko 15.0 */
VK_UNDERSCORE: 167,
/** Open parenthesis (() key. Requires Gecko 15.0 */
VK_OPEN_PAREN: 168,
/** Close parenthesis ()) key. Requires Gecko 15.0 */
VK_CLOSE_PAREN: 169,
/* Asterisk (*) key. Requires Gecko 15.0 */
VK_ASTERISK: 170,
/** Plus (+) key. Requires Gecko 15.0 */
VK_PLUS: 171,
/** Pipe (|) key. Requires Gecko 15.0 */
VK_PIPE: 172,
/** Hyphen-US/docs/Minus (-) key. Requires Gecko 15.0 */
VK_HYPHEN_MINUS: 173,
/** Open curly bracket ({) key. Requires Gecko 15.0 */
VK_OPEN_CURLY_BRACKET: 174,
/** Close curly bracket (}) key. Requires Gecko 15.0 */
VK_CLOSE_CURLY_BRACKET: 175,
/** Tilde (~) key. Requires Gecko 15.0 */
VK_TILDE: 176,
/** Comma (,) key. */
VK_COMMA: 188,
/** Period (.) key. */
VK_PERIOD: 190,
/** Slash (/) key. */
VK_SLASH: 191,
/** Back tick (`) key. */
VK_BACK_QUOTE: 192,
/** Open square bracket ([) key. */
VK_OPEN_BRACKET: 219,
/** Back slash (\) key. */
VK_BACK_SLASH: 220,
/** Close square bracket (]) key. */
VK_CLOSE_BRACKET: 221,
/** Quote (''') key. */
VK_QUOTE: 222,
/** Meta key on Linux, Command key on Mac. */
VK_META: 224,
/** AltGr key on Linux. Requires Gecko 15.0 */
VK_ALTGR: 225,
/** Windows logo key on Windows. Or Super or Hyper key on Linux. Requires Gecko 15.0 */
VK_WIN: 91,
/** Linux support for this keycode was added in Gecko 4.0. */
VK_KANA: 21,
/** Linux support for this keycode was added in Gecko 4.0. */
VK_HANGUL: 21,
/** 英数 key on Japanese Mac keyboard. Requires Gecko 15.0 */
VK_EISU: 22,
/** Linux support for this keycode was added in Gecko 4.0. */
VK_JUNJA: 23,
/** Linux support for this keycode was added in Gecko 4.0. */
VK_FINAL: 24,
/** Linux support for this keycode was added in Gecko 4.0. */
VK_HANJA: 25,
/** Linux support for this keycode was added in Gecko 4.0. */
VK_KANJI: 25,
/** Linux support for this keycode was added in Gecko 4.0. */
VK_CONVERT: 28,
/** Linux support for this keycode was added in Gecko 4.0. */
VK_NONCONVERT: 29,
/** Linux support for this keycode was added in Gecko 4.0. */
VK_ACCEPT: 30,
/** Linux support for this keycode was added in Gecko 4.0. */
VK_MODECHANGE: 31,
/** Linux support for this keycode was added in Gecko 4.0. */
VK_SELECT: 41,
/** Linux support for this keycode was added in Gecko 4.0. */
VK_PRINT: 42,
/** Linux support for this keycode was added in Gecko 4.0. */
VK_EXECUTE: 43,
/** Linux support for this keycode was added in Gecko 4.0. */
VK_SLEEP: 95
};
/**
* @namespace
* Contains text tokenization and breaking routines
*/
ROT.Text = {
RE_COLORS: /%([bc]){([^}]*)}/g,
/* token types */
TYPE_TEXT: 0,
TYPE_NEWLINE: 1,
TYPE_FG: 2,
TYPE_BG: 3,
/**
* Measure size of a resulting text block
*/
measure: function(str, maxWidth) {
var result = {width:0, height:1};
var tokens = this.tokenize(str, maxWidth);
var lineWidth = 0;
for (var i=0;i<tokens.length;i++) {
var token = tokens[i];
switch (token.type) {
case this.TYPE_TEXT:
lineWidth += token.value.length;
break;
case this.TYPE_NEWLINE:
result.height++;
result.width = Math.max(result.width, lineWidth);
lineWidth = 0;
break;
}
}
result.width = Math.max(result.width, lineWidth);
return result;
},
/**
* Convert string to a series of a formatting commands
*/
tokenize: function(str, maxWidth) {
var result = [];
/* first tokenization pass - split texts and color formatting commands */
var offset = 0;
str.replace(this.RE_COLORS, function(match, type, name, index) {
/* string before */
var part = str.substring(offset, index);
if (part.length) {
result.push({
type: ROT.Text.TYPE_TEXT,
value: part
});
}
/* color command */
result.push({
type: (type == "c" ? ROT.Text.TYPE_FG : ROT.Text.TYPE_BG),
value: name.trim()
});
offset = index + match.length;
return "";
});
/* last remaining part */
var part = str.substring(offset);
if (part.length) {
result.push({
type: ROT.Text.TYPE_TEXT,
value: part
});
}
return this._breakLines(result, maxWidth);
},
/* insert line breaks into first-pass tokenized data */
_breakLines: function(tokens, maxWidth) {
if (!maxWidth) { maxWidth = Infinity; }
var i = 0;
var lineLength = 0;
var lastTokenWithSpace = -1;
while (i < tokens.length) { /* take all text tokens, remove space, apply linebreaks */
var token = tokens[i];
if (token.type == ROT.Text.TYPE_NEWLINE) { /* reset */
lineLength = 0;
lastTokenWithSpace = -1;
}
if (token.type != ROT.Text.TYPE_TEXT) { /* skip non-text tokens */
i++;
continue;
}
/* remove spaces at the beginning of line */
while (lineLength == 0 && token.value.charAt(0) == " ") { token.value = token.value.substring(1); }
/* forced newline? insert two new tokens after this one */
var index = token.value.indexOf("\n");
if (index != -1) {
token.value = this._breakInsideToken(tokens, i, index, true);
/* if there are spaces at the end, we must remove them (we do not want the line too long) */
var arr = token.value.split("");
while (arr.length && arr[arr.length-1] == " ") { arr.pop(); }
token.value = arr.join("");
}
/* token degenerated? */
if (!token.value.length) {
tokens.splice(i, 1);
continue;
}
if (lineLength + token.value.length > maxWidth) { /* line too long, find a suitable breaking spot */
/* is it possible to break within this token? */
var index = -1;
while (1) {
var nextIndex = token.value.indexOf(" ", index+1);
if (nextIndex == -1) { break; }
if (lineLength + nextIndex > maxWidth) { break; }
index = nextIndex;
}
if (index != -1) { /* break at space within this one */
token.value = this._breakInsideToken(tokens, i, index, true);
} else if (lastTokenWithSpace != -1) { /* is there a previous token where a break can occur? */
var token = tokens[lastTokenWithSpace];
var breakIndex = token.value.lastIndexOf(" ");
token.value = this._breakInsideToken(tokens, lastTokenWithSpace, breakIndex, true);
i = lastTokenWithSpace;
} else { /* force break in this token */
token.value = this._breakInsideToken(tokens, i, maxWidth-lineLength, false);
}
} else { /* line not long, continue */
lineLength += token.value.length;
if (token.value.indexOf(" ") != -1) { lastTokenWithSpace = i; }
}
i++; /* advance to next token */
}
tokens.push({type: ROT.Text.TYPE_NEWLINE}); /* insert fake newline to fix the last text line */
/* remove trailing space from text tokens before newlines */
var lastTextToken = null;
for (var i=0;i<tokens.length;i++) {
var token = tokens[i];
switch (token.type) {
case ROT.Text.TYPE_TEXT: lastTextToken = token; break;
case ROT.Text.TYPE_NEWLINE:
if (lastTextToken) { /* remove trailing space */
var arr = lastTextToken.value.split("");
while (arr.length && arr[arr.length-1] == " ") { arr.pop(); }
lastTextToken.value = arr.join("");
}
lastTextToken = null;
break;
}
}
tokens.pop(); /* remove fake token */
return tokens;
},
/**
* Create new tokens and insert them into the stream
* @param {object[]} tokens
* @param {int} tokenIndex Token being processed
* @param {int} breakIndex Index within current token's value
* @param {bool} removeBreakChar Do we want to remove the breaking character?
* @returns {string} remaining unbroken token value
*/
_breakInsideToken: function(tokens, tokenIndex, breakIndex, removeBreakChar) {
var newBreakToken = {
type: ROT.Text.TYPE_NEWLINE
};
var newTextToken = {
type: ROT.Text.TYPE_TEXT,
value: tokens[tokenIndex].value.substring(breakIndex + (removeBreakChar ? 1 : 0))
};
tokens.splice(tokenIndex+1, 0, newBreakToken, newTextToken);
return tokens[tokenIndex].value.substring(0, breakIndex);
}
};
/**
* @returns {any} Randomly picked item, null when length=0
*/
Array.prototype.random = Array.prototype.random || function() {
if (!this.length) { return null; }
return this[Math.floor(ROT.RNG.getUniform() * this.length)];
};
/**
* @returns {array} New array with randomized items
*/
Array.prototype.randomize = Array.prototype.randomize || function() {
var result = [];
var clone = this.slice();
while (clone.length) {
var index = clone.indexOf(clone.random());
result.push(clone.splice(index, 1)[0]);
}
return result;
};
/**
* Always positive modulus
* @param {int} n Modulus
* @returns {int} this modulo n
*/
Number.prototype.mod = Number.prototype.mod || function(n) {
return ((this%n)+n)%n;
};
/**
* @returns {string} First letter capitalized
*/
String.prototype.capitalize = String.prototype.capitalize || function() {
return this.charAt(0).toUpperCase() + this.substring(1);
};
/**
* Left pad
* @param {string} [character="0"]
* @param {int} [count=2]
*/
String.prototype.lpad = String.prototype.lpad || function(character, count) {
var ch = character || "0";
var cnt = count || 2;
var s = "";
while (s.length < (cnt - this.length)) { s += ch; }
s = s.substring(0, cnt-this.length);
return s+this;
};
/**
* Right pad
* @param {string} [character="0"]
* @param {int} [count=2]
*/
String.prototype.rpad = String.prototype.rpad || function(character, count) {
var ch = character || "0";
var cnt = count || 2;
var s = "";
while (s.length < (cnt - this.length)) { s += ch; }
s = s.substring(0, cnt-this.length);
return this+s;
};
/**
* Format a string in a flexible way. Scans for %s strings and replaces them with arguments. List of patterns is modifiable via String.format.map.
* @param {string} template
* @param {any} [argv]
*/
String.format = String.format || function(template) {
var map = String.format.map;
var args = Array.prototype.slice.call(arguments, 1);
var replacer = function(match, group1, group2, index) {
if (template.charAt(index-1) == "%") { return match.substring(1); }
if (!args.length) { return match; }
var obj = args[0];
var group = group1 || group2;
var parts = group.split(",");
var name = parts.shift();
var method = map[name.toLowerCase()];
if (!method) { return match; }
var obj = args.shift();
var replaced = obj[method].apply(obj, parts);
var first = name.charAt(0);
if (first != first.toLowerCase()) { replaced = replaced.capitalize(); }
return replaced;
};
return template.replace(/%(?:([a-z]+)|(?:{([^}]+)}))/gi, replacer);
};
String.format.map = String.format.map || {
"s": "toString"
};
/**
* Convenience shortcut to String.format(this)
*/
String.prototype.format = String.prototype.format || function() {
var args = Array.prototype.slice.call(arguments);
args.unshift(this);
return String.format.apply(String, args);
};
if (!Object.create) {
/**
* ES5 Object.create
*/
Object.create = function(o) {
var tmp = function() {};
tmp.prototype = o;
return new tmp();
};
}
/**
* Sets prototype of this function to an instance of parent function
* @param {function} parent
*/
Function.prototype.extend = Function.prototype.extend || function(parent) {
this.prototype = Object.create(parent.prototype);
this.prototype.constructor = this;
return this;
};
if (typeof window != "undefined") {
window.requestAnimationFrame =
window.requestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.oRequestAnimationFrame
|| window.msRequestAnimationFrame
|| function(cb) { return setTimeout(function() { cb(Date.now()); }, 1000/60); };
window.cancelAnimationFrame =
window.cancelAnimationFrame
|| window.mozCancelAnimationFrame
|| window.webkitCancelAnimationFrame
|| window.oCancelAnimationFrame
|| window.msCancelAnimationFrame
|| function(id) { return clearTimeout(id); };
}
/**
* @class Visual map display
* @param {object} [options]
* @param {int} [options.width=ROT.DEFAULT_WIDTH]
* @param {int} [options.height=ROT.DEFAULT_HEIGHT]
* @param {int} [options.fontSize=15]
* @param {string} [options.fontFamily="monospace"]
* @param {string} [options.fontStyle=""] bold/italic/none/both
* @param {string} [options.fg="#ccc"]
* @param {string} [options.bg="#000"]
* @param {float} [options.spacing=1]
* @param {float} [options.border=0]
* @param {string} [options.layout="rect"]
* @param {bool} [options.forceSquareRatio=false]
* @param {int} [options.tileWidth=32]
* @param {int} [options.tileHeight=32]
* @param {object} [options.tileMap={}]
* @param {image} [options.tileSet=null]
* @param {image} [options.tileColorize=false]
*/
ROT.Display = function(options) {
var canvas = document.createElement("canvas");
this._context = canvas.getContext("2d");
this._data = {};
this._dirty = false; /* false = nothing, true = all, object = dirty cells */
this._options = {};
this._backend = null;
var defaultOptions = {
width: ROT.DEFAULT_WIDTH,
height: ROT.DEFAULT_HEIGHT,
transpose: false,
layout: "rect",
fontSize: 15,
spacing: 1,
border: 0,
forceSquareRatio: false,
fontFamily: "monospace",
fontStyle: "",
fg: "#ccc",
bg: "#000",
tileWidth: 32,
tileHeight: 32,
tileMap: {},
tileSet: null,
tileColorize: false,
termColor: "xterm"
};
for (var p in options) { defaultOptions[p] = options[p]; }
this.setOptions(defaultOptions);
this.DEBUG = this.DEBUG.bind(this);
this._tick = this._tick.bind(this);
requestAnimationFrame(this._tick);
};
/**
* Debug helper, ideal as a map generator callback. Always bound to this.
* @param {int} x
* @param {int} y
* @param {int} what
*/
ROT.Display.prototype.DEBUG = function(x, y, what) {
var colors = [this._options.bg, this._options.fg];
this.draw(x, y, null, null, colors[what % colors.length]);
};
/**
* Clear the whole display (cover it with background color)
*/
ROT.Display.prototype.clear = function() {
this._data = {};
this._dirty = true;
};
/**
* @see ROT.Display
*/
ROT.Display.prototype.setOptions = function(options) {
for (var p in options) { this._options[p] = options[p]; }
if (options.width || options.height || options.fontSize || options.fontFamily || options.spacing || options.layout) {
if (options.layout) {
this._backend = new ROT.Display[options.layout.capitalize()](this._context);
}
var font = (this._options.fontStyle ? this._options.fontStyle + " " : "") + this._options.fontSize + "px " + this._options.fontFamily;
this._context.font = font;
this._backend.compute(this._options);
this._context.font = font;
this._context.textAlign = "center";
this._context.textBaseline = "middle";
this._dirty = true;
}
return this;
};
/**
* Returns currently set options
* @returns {object} Current options object
*/
ROT.Display.prototype.getOptions = function() {
return this._options;
};
/**
* Returns the DOM node of this display
* @returns {node} DOM node
*/
ROT.Display.prototype.getContainer = function() {
return this._context.canvas;
};
/**
* Compute the maximum width/height to fit into a set of given constraints
* @param {int} availWidth Maximum allowed pixel width
* @param {int} availHeight Maximum allowed pixel height
* @returns {int[2]} cellWidth,cellHeight
*/
ROT.Display.prototype.computeSize = function(availWidth, availHeight) {
return this._backend.computeSize(availWidth, availHeight, this._options);
};
/**
* Compute the maximum font size to fit into a set of given constraints
* @param {int} availWidth Maximum allowed pixel width
* @param {int} availHeight Maximum allowed pixel height
* @returns {int} fontSize
*/
ROT.Display.prototype.computeFontSize = function(availWidth, availHeight) {
return this._backend.computeFontSize(availWidth, availHeight, this._options);
};
/**
* Convert a DOM event (mouse or touch) to map coordinates. Uses first touch for multi-touch.
* @param {Event} e event
* @returns {int[2]} -1 for values outside of the canvas
*/
ROT.Display.prototype.eventToPosition = function(e) {
if (e.touches) {
var x = e.touches[0].clientX;
var y = e.touches[0].clientY;
} else {
var x = e.clientX;
var y = e.clientY;
}
var rect = this._context.canvas.getBoundingClientRect();
x -= rect.left;
y -= rect.top;
x *= this._context.canvas.width / this._context.canvas.clientWidth;
y *= this._context.canvas.height / this._context.canvas.clientHeight;
if (x < 0 || y < 0 || x >= this._context.canvas.width || y >= this._context.canvas.height) { return [-1, -1]; }
return this._backend.eventToPosition(x, y);
};
/**
* @param {int} x
* @param {int} y
* @param {string || string[]} ch One or more chars (will be overlapping themselves)
* @param {string} [fg] foreground color
* @param {string} [bg] background color
*/
ROT.Display.prototype.draw = function(x, y, ch, fg, bg) {
if (!fg) { fg = this._options.fg; }
if (!bg) { bg = this._options.bg; }
this._data[x+","+y] = [x, y, ch, fg, bg];
if (this._dirty === true) { return; } /* will already redraw everything */
if (!this._dirty) { this._dirty = {}; } /* first! */
this._dirty[x+","+y] = true;
};
/**
* Draws a text at given position. Optionally wraps at a maximum length. Currently does not work with hex layout.
* @param {int} x
* @param {int} y
* @param {string} text May contain color/background format specifiers, %c{name}/%b{name}, both optional. %c{}/%b{} resets to default.
* @param {int} [maxWidth] wrap at what width?
* @returns {int} lines drawn
*/
ROT.Display.prototype.drawText = function(x, y, text, maxWidth) {
var fg = null;
var bg = null;
var cx = x;
var cy = y;
var lines = 1;
if (!maxWidth) { maxWidth = this._options.width-x; }
var tokens = ROT.Text.tokenize(text, maxWidth);
while (tokens.length) { /* interpret tokenized opcode stream */
var token = tokens.shift();
switch (token.type) {
case ROT.Text.TYPE_TEXT:
var isSpace = false, isPrevSpace = false, isFullWidth = false, isPrevFullWidth = false;
for (var i=0;i<token.value.length;i++) {
var cc = token.value.charCodeAt(i);
var c = token.value.charAt(i);
// Assign to `true` when the current char is full-width.
isFullWidth = (cc > 0xff00 && cc < 0xff61) || (cc > 0xffdc && cc < 0xffe8) || cc > 0xffee;
// Current char is space, whatever full-width or half-width both are OK.
isSpace = (c.charCodeAt(0) == 0x20 || c.charCodeAt(0) == 0x3000);
// The previous char is full-width and
// current char is nether half-width nor a space.
if (isPrevFullWidth && !isFullWidth && !isSpace) { cx++; } // add an extra position
// The current char is full-width and
// the previous char is not a space.
if(isFullWidth && !isPrevSpace) { cx++; } // add an extra position
this.draw(cx++, cy, c, fg, bg);
isPrevSpace = isSpace;
isPrevFullWidth = isFullWidth;
}
break;
case ROT.Text.TYPE_FG:
fg = token.value || null;
break;
case ROT.Text.TYPE_BG:
bg = token.value || null;
break;
case ROT.Text.TYPE_NEWLINE:
cx = x;
cy++;
lines++;
break;
}
}
return lines;
};
/**
* Timer tick: update dirty parts
*/
ROT.Display.prototype._tick = function() {
requestAnimationFrame(this._tick);
if (!this._dirty) { return; }
if (this._dirty === true) { /* draw all */
this._context.fillStyle = this._options.bg;
this._context.fillRect(0, 0, this._context.canvas.width, this._context.canvas.height);
for (var id in this._data) { /* redraw cached data */
this._draw(id, false);
}
} else { /* draw only dirty */
for (var key in this._dirty) {
this._draw(key, true);
}
}
this._dirty = false;
};
/**
* @param {string} key What to draw
* @param {bool} clearBefore Is it necessary to clean before?
*/
ROT.Display.prototype._draw = function(key, clearBefore) {
var data = this._data[key];
if (data[4] != this._options.bg) { clearBefore = true; }
this._backend.draw(data, clearBefore);
};
/**
* @class Abstract display backend module
* @private
*/
ROT.Display.Backend = function(context) {
this._context = context;
};
ROT.Display.Backend.prototype.compute = function(options) {
};
ROT.Display.Backend.prototype.draw = function(data, clearBefore) {
};
ROT.Display.Backend.prototype.computeSize = function(availWidth, availHeight) {
};
ROT.Display.Backend.prototype.computeFontSize = function(availWidth, availHeight) {
};