forked from doublespeakgames/adarkroom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
engine.js
794 lines (693 loc) · 19.6 KB
/
engine.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
(function() {
var Engine = window.Engine = {
SITE_URL: encodeURIComponent("http://adarkroom.doublespeakgames.com"),
VERSION: 1.3,
MAX_STORE: 99999999999999,
SAVE_DISPLAY: 30 * 1000,
GAME_OVER: false,
//object event types
topics: {},
Perks: {
'boxer': {
name: _('boxer'),
desc: _('punches do more damage'),
/// TRANSLATORS : means with more force.
notify: _('learned to throw punches with purpose')
},
'martial artist': {
name: _('martial artist'),
desc: _('punches do even more damage.'),
notify: _('learned to fight quite effectively without weapons')
},
'unarmed master': {
/// TRANSLATORS : master of unarmed combat
name: _('unarmed master'),
desc: _('punch twice as fast, and with even more force'),
notify: _('learned to strike faster without weapons')
},
'barbarian': {
name: _('barbarian'),
desc: _('melee weapons deal more damage'),
notify: _('learned to swing weapons with force')
},
'slow metabolism': {
name: _('slow metabolism'),
desc: _('go twice as far without eating'),
notify: _('learned how to ignore the hunger')
},
'desert rat': {
name: _('desert rat'),
desc: _('go twice as far without drinking'),
notify: _('learned to love the dry air')
},
'evasive': {
name: _('evasive'),
desc: _('dodge attacks more effectively'),
notify: _("learned to be where they're not")
},
'precise': {
name: _('precise'),
desc: _('land blows more often'),
notify: _('learned to predict their movement')
},
'scout': {
name: _('scout'),
desc: _('see farther'),
notify: _('learned to look ahead')
},
'stealthy': {
name: _('stealthy'),
desc: _('better avoid conflict in the wild'),
notify: _('learned how not to be seen')
},
'gastronome': {
name: _('gastronome'),
desc: _('restore more health when eating'),
notify: _('learned to make the most of food')
}
},
options: {
state: null,
debug: false,
log: false,
dropbox: false,
doubleTime: false
},
init: function(options) {
this.options = $.extend(
this.options,
options
);
this._debug = this.options.debug;
this._log = this.options.log;
// Check for HTML5 support
if(!Engine.browserValid()) {
window.location = 'browserWarning.html';
}
// Check for mobile
if(Engine.isMobile()) {
window.location = 'mobileWarning.html';
}
Engine.disableSelection();
if(this.options.state != null) {
window.State = this.options.state;
} else {
Engine.loadGame();
}
$('<div>').attr('id', 'locationSlider').appendTo('#main');
var menu = $('<div>')
.addClass('menu')
.appendTo('body');
if(typeof langs != 'undefined'){
var customSelect = $('<span>')
.addClass('customSelect')
.addClass('menuBtn')
.appendTo(menu);
var selectOptions = $('<span>')
.addClass('customSelectOptions')
.appendTo(customSelect);
var optionsList = $('<ul>')
.appendTo(selectOptions);
$('<li>')
.text("language.")
.appendTo(optionsList);
$.each(langs, function(name,display){
$('<li>')
.text(display)
.attr('data-language', name)
.on("click", function() { Engine.switchLanguage(this); })
.appendTo(optionsList);
});
}
$('<span>')
.addClass('lightsOff menuBtn')
.text(_('lights off.'))
.click(Engine.turnLightsOff)
.appendTo(menu);
$('<span>')
.addClass('hyper menuBtn')
.text(_('hyper.'))
.click(Engine.triggerHyperMode)
.appendTo(menu);
$('<span>')
.addClass('menuBtn')
.text(_('restart.'))
.click(Engine.confirmDelete)
.appendTo(menu);
$('<span>')
.addClass('menuBtn')
.text(_('share.'))
.click(Engine.share)
.appendTo(menu);
$('<span>')
.addClass('menuBtn')
.text(_('save.'))
.click(Engine.exportImport)
.appendTo(menu);
if(this.options.dropbox && Engine.Dropbox) {
this.dropbox = Engine.Dropbox.init();
$('<span>')
.addClass('menuBtn')
.text(_('dropbox.'))
.click(Engine.Dropbox.startDropbox)
.appendTo(menu);
}
$('<span>')
.addClass('menuBtn')
.text(_('app store.'))
.click(function() { window.open('https://itunes.apple.com/us/app/a-dark-room/id736683061'); })
.appendTo(menu);
$('<span>')
.addClass('menuBtn')
.text(_('github.'))
.click(function() { window.open('https://github.com/doublespeakgames/adarkroom'); })
.appendTo(menu);
// Register keypress handlers
$('body').off('keydown').keydown(Engine.keyDown);
$('body').off('keyup').keyup(Engine.keyUp);
// Register swipe handlers
swipeElement = $('#outerSlider');
swipeElement.on('swipeleft', Engine.swipeLeft);
swipeElement.on('swiperight', Engine.swipeRight);
swipeElement.on('swipeup', Engine.swipeUp);
swipeElement.on('swipedown', Engine.swipeDown);
// subscribe to stateUpdates
$.Dispatch('stateUpdate').subscribe(Engine.handleStateUpdates);
$SM.init();
Notifications.init();
Events.init();
Room.init();
if(typeof $SM.get('stores.wood') != 'undefined') {
Outside.init();
}
if($SM.get('stores.compass', true) > 0) {
Path.init();
}
if($SM.get('features.location.spaceShip')) {
Ship.init();
}
if($SM.get('config.lightsOff', true)){
Engine.turnLightsOff();
}
if($SM.get('config.hyperMode', true)){
Engine.triggerHyperMode();
}
Engine.saveLanguage();
Engine.travelTo(Room);
},
browserValid: function() {
return ( location.search.indexOf( 'ignorebrowser=true' ) >= 0 || ( typeof Storage != 'undefined' && !oldIE ) );
},
isMobile: function() {
return ( location.search.indexOf( 'ignorebrowser=true' ) < 0 && /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test( navigator.userAgent ) );
},
saveGame: function() {
if(typeof Storage != 'undefined' && localStorage) {
if(Engine._saveTimer != null) {
clearTimeout(Engine._saveTimer);
}
if(typeof Engine._lastNotify == 'undefined' || Date.now() - Engine._lastNotify > Engine.SAVE_DISPLAY){
$('#saveNotify').css('opacity', 1).animate({opacity: 0}, 1000, 'linear');
Engine._lastNotify = Date.now();
}
localStorage.gameState = JSON.stringify(State);
}
},
loadGame: function() {
try {
var savedState = JSON.parse(localStorage.gameState);
if(savedState) {
State = savedState;
$SM.updateOldState();
Engine.log("loaded save!");
}
} catch(e) {
State = {};
$SM.set('version', Engine.VERSION);
Engine.event('progress', 'new game');
}
},
exportImport: function() {
Events.startEvent({
title: _('Export / Import'),
scenes: {
start: {
text: [
_('export or import save data, for backing up'),
_('or migrating computers')
],
buttons: {
'export': {
text: _('export'),
onChoose: Engine.export64
},
'import': {
text: _('import'),
nextScene: {1: 'confirm'}
},
'cancel': {
text: _('cancel'),
nextScene: 'end'
}
}
},
'confirm': {
text: [
_('are you sure?'),
_('if the code is invalid, all data will be lost.'),
_('this is irreversible.')
],
buttons: {
'yes': {
text: _('yes'),
nextScene: {1: 'inputImport'},
onChoose: Engine.enableSelection
},
'no': {
text: _('no'),
nextScene: 'end'
}
}
},
'inputImport': {
text: [_('put the save code here.')],
textarea: '',
buttons: {
'okay': {
text: _('import'),
nextScene: 'end',
onChoose: Engine.import64
},
'cancel': {
text: _('cancel'),
nextScene: 'end'
}
}
}
}
});
},
generateExport64: function(){
var string64 = Base64.encode(localStorage.gameState);
string64 = string64.replace(/\s/g, '');
string64 = string64.replace(/\./g, '');
string64 = string64.replace(/\n/g, '');
return string64;
},
export64: function() {
Engine.saveGame();
var string64 = Engine.generateExport64();
Engine.enableSelection();
Events.startEvent({
title: _('Export'),
scenes: {
start: {
text: [_('save this.')],
textarea: string64,
readonly: true,
buttons: {
'done': {
text: _('got it'),
nextScene: 'end',
onChoose: Engine.disableSelection
}
}
}
}
});
Engine.autoSelect('#description textarea');
},
import64: function(string64) {
Engine.disableSelection();
string64 = string64.replace(/\s/g, '');
string64 = string64.replace(/\./g, '');
string64 = string64.replace(/\n/g, '');
var decodedSave = Base64.decode(string64);
localStorage.gameState = decodedSave;
location.reload();
},
event: function(cat, act) {
if(typeof ga === 'function') {
ga('send', 'event', cat, act);
}
},
confirmDelete: function() {
Events.startEvent({
title: _('Restart?'),
scenes: {
start: {
text: [_('restart the game?')],
buttons: {
'yes': {
text: _('yes'),
nextScene: 'end',
onChoose: Engine.deleteSave
},
'no': {
text: _('no'),
nextScene: 'end'
}
}
}
}
});
},
deleteSave: function(noReload) {
if(typeof Storage != 'undefined' && localStorage) {
var prestige = Prestige.get();
window.State = {};
localStorage.clear();
Prestige.set(prestige);
}
if(!noReload) {
location.reload();
}
},
share: function() {
Events.startEvent({
title: _('Share'),
scenes: {
start: {
text: [_('bring your friends.')],
buttons: {
'facebook': {
text: _('facebook'),
nextScene: 'end',
onChoose: function() {
window.open('https://www.facebook.com/sharer/sharer.php?u=' + Engine.SITE_URL, 'sharer', 'width=626,height=436,location=no,menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no');
}
},
'google': {
text:_('google+'),
nextScene: 'end',
onChoose: function() {
window.open('https://plus.google.com/share?url=' + Engine.SITE_URL, 'sharer', 'width=480,height=436,location=no,menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no');
}
},
'twitter': {
text: _('twitter'),
nextScene: 'end',
onChoose: function() {
window.open('https://twitter.com/intent/tweet?text=A%20Dark%20Room&url=' + Engine.SITE_URL, 'sharer', 'width=660,height=260,location=no,menubar=no,resizable=no,scrollbars=yes,status=no,toolbar=no');
}
},
'reddit': {
text: _('reddit'),
nextScene: 'end',
onChoose: function() {
window.open('http://www.reddit.com/submit?url=' + Engine.SITE_URL, 'sharer', 'width=960,height=700,location=no,menubar=no,resizable=no,scrollbars=yes,status=no,toolbar=no');
}
},
'close': {
text: _('close'),
nextScene: 'end'
}
}
}
}
},
{
width: '400px'
});
},
findStylesheet: function(title) {
for(var i=0; i<document.styleSheets.length; i++) {
var sheet = document.styleSheets[i];
if(sheet.title == title) {
return sheet;
}
}
return null;
},
isLightsOff: function() {
var darkCss = Engine.findStylesheet('darkenLights');
if ( darkCss != null && !darkCss.disabled ) {
return true;
}
return false;
},
turnLightsOff: function() {
var darkCss = Engine.findStylesheet('darkenLights');
if (darkCss == null) {
$('head').append('<link rel="stylesheet" href="css/dark.css" type="text/css" title="darkenLights" />');
$('.lightsOff').text(_('lights on.'));
$SM.set('config.lightsOff', true, true);
} else if (darkCss.disabled) {
darkCss.disabled = false;
$('.lightsOff').text(_('lights on.'));
$SM.set('config.lightsOff', true,true);
} else {
$("#darkenLights").attr("disabled", "disabled");
darkCss.disabled = true;
$('.lightsOff').text(_('lights off.'));
$SM.set('config.lightsOff', false, true);
}
},
triggerHyperMode: function(){
Engine.options.doubleTime = !Engine.options.doubleTime;
if(Engine.options.doubleTime)
$('.hyper').text(_('classic.'));
else
$('.hyper').text(_('hyper.'));
$SM.set('config.hyperMode', Engine.options.doubleTime, false);
},
// Gets a guid
getGuid: function() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
},
activeModule: null,
travelTo: function(module) {
if(Engine.activeModule != module) {
var currentIndex = Engine.activeModule ? $('.location').index(Engine.activeModule.panel) : 1;
$('div.headerButton').removeClass('selected');
module.tab.addClass('selected');
var slider = $('#locationSlider');
var stores = $('#storesContainer');
var panelIndex = $('.location').index(module.panel);
var diff = Math.abs(panelIndex - currentIndex);
slider.animate({left: -(panelIndex * 700) + 'px'}, 300 * diff);
if($SM.get('stores.wood') !== undefined) {
// FIXME Why does this work if there's an animation queue...?
stores.animate({right: -(panelIndex * 700) + 'px'}, 300 * diff);
}
Engine.activeModule = module;
module.onArrival(diff);
if(Engine.activeModule == Room || Engine.activeModule == Path) {
// Don't fade out the weapons if we're switching to a module
// where we're going to keep showing them anyway.
if (module != Room && module != Path) {
$('div#weapons').animate({opacity: 0}, 300);
}
}
if(module == Room || module == Path) {
$('div#weapons').animate({opacity: 1}, 300);
}
Notifications.printQueue(module);
}
},
/* Move the stores panel beneath top_container (or to top: 0px if top_container
* either hasn't been filled in or is null) using transition_diff to sync with
* the animation in Engine.travelTo().
*/
moveStoresView: function(top_container, transition_diff) {
var stores = $('#storesContainer');
// If we don't have a storesContainer yet, leave.
if(typeof(stores) === 'undefined') return;
if(typeof(transition_diff) === 'undefined') transition_diff = 1;
if(top_container === null) {
stores.animate({top: '0px'}, {queue: false, duration: 300 * transition_diff});
}
else if(!top_container.length) {
stores.animate({top: '0px'}, {queue: false, duration: 300 * transition_diff});
}
else {
stores.animate({
top: top_container.height() + 26 + 'px'
},
{
queue: false,
duration: 300 * transition_diff
});
}
},
log: function(msg) {
if(this._log) {
console.log(msg);
}
},
updateSlider: function() {
var slider = $('#locationSlider');
slider.width((slider.children().length * 700) + 'px');
},
updateOuterSlider: function() {
var slider = $('#outerSlider');
slider.width((slider.children().length * 700) + 'px');
},
getIncomeMsg: function(num, delay) {
return _("{0} per {1}s", (num > 0 ? "+" : "") + num, delay);
//return (num > 0 ? "+" : "") + num + " per " + delay + "s";
},
keyDown: function(e) {
e = e || window.event;
if(!Engine.keyPressed && !Engine.keyLock) {
Engine.pressed = true;
if(Engine.activeModule.keyDown) {
Engine.activeModule.keyDown(e);
}
}
return jQuery.inArray(e.keycode, [37,38,39,40]) < 0;
},
keyUp: function(e) {
Engine.pressed = false;
if(Engine.activeModule.keyUp) {
Engine.activeModule.keyUp(e);
}
else
{
switch(e.which) {
case 38: // Up
case 87:
if(Engine.activeModule == Outside || Engine.activeModule == Path) {
Engine.activeModule.scrollSidebar('up');
}
Engine.log('up');
break;
case 40: // Down
case 83:
if (Engine.activeModule == Outside || Engine.activeModule == Path) {
Engine.activeModule.scrollSidebar('down');
}
Engine.log('down');
break;
case 37: // Left
case 65:
if(Engine.activeModule == Ship && Path.tab)
Engine.travelTo(Path);
else if(Engine.activeModule == Path && Outside.tab){
Engine.activeModule.scrollSidebar('left', true);
Engine.travelTo(Outside);
}else if(Engine.activeModule == Outside && Room.tab){
Engine.activeModule.scrollSidebar('left', true);
Engine.travelTo(Room);
}
Engine.log('left');
break;
case 39: // Right
case 68:
if(Engine.activeModule == Room && Outside.tab)
Engine.travelTo(Outside);
else if(Engine.activeModule == Outside && Path.tab){
Engine.activeModule.scrollSidebar('right', true);
Engine.travelTo(Path);
}else if(Engine.activeModule == Path && Ship.tab){
Engine.activeModule.scrollSidebar('right', true);
Engine.travelTo(Ship);
}
Engine.log('right');
break;
}
}
return false;
},
swipeLeft: function(e) {
if(Engine.activeModule.swipeLeft) {
Engine.activeModule.swipeLeft(e);
}
},
swipeRight: function(e) {
if(Engine.activeModule.swipeRight) {
Engine.activeModule.swipeRight(e);
}
},
swipeUp: function(e) {
if(Engine.activeModule.swipeUp) {
Engine.activeModule.swipeUp(e);
}
},
swipeDown: function(e) {
if(Engine.activeModule.swipeDown) {
Engine.activeModule.swipeDown(e);
}
},
disableSelection: function() {
document.onselectstart = eventNullifier; // this is for IE
document.onmousedown = eventNullifier; // this is for the rest
},
enableSelection: function() {
document.onselectstart = eventPassthrough;
document.onmousedown = eventPassthrough;
},
autoSelect: function(selector) {
$(selector).focus().select();
},
handleStateUpdates: function(e){
},
switchLanguage: function(dom){
var lang = $(dom).data("language");
if(document.location.href.search(/[\?\&]lang=[a-z_]+/) != -1){
document.location.href = document.location.href.replace( /([\?\&]lang=)([a-z_]+)/gi , "$1"+lang );
}else{
document.location.href = document.location.href + ( (document.location.href.search(/\?/) != -1 )?"&":"?") + "lang="+lang;
}
},
saveLanguage: function(){
var lang = decodeURIComponent((new RegExp('[?|&]lang=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
if(lang && typeof Storage != 'undefined' && localStorage) {
localStorage.lang = lang;
}
},
setTimeout: function(callback, timeout, skipDouble){
if( Engine.options.doubleTime && !skipDouble ){
Engine.log('Double time, cutting timeout in half');
timeout /= 2;
}
return setTimeout(callback, timeout);
}
};
function eventNullifier(e) {
return $(e.target).hasClass('menuBtn');
}
function eventPassthrough(e) {
return true;
}
})();
function inView(dir, elem){
var scTop = $('#main').offset().top;
var scBot = scTop + $('#main').height();
var elTop = elem.offset().top;
var elBot = elTop + elem.height();
if( dir == 'up' ){
// STOP MOVING IF BOTTOM OF ELEMENT IS VISIBLE IN SCREEN
return ( elBot < scBot );
}else if( dir == 'down' ){
return ( elTop > scTop );
}else{
return ( ( elBot <= scBot ) && ( elTop >= scTop ) );
}
}
function scrollByX(elem, x){
var elTop = parseInt( elem.css('top'), 10 );
elem.css( 'top', ( elTop + x ) + "px" );
}
//create jQuery Callbacks() to handle object events
$.Dispatch = function( id ) {
var callbacks, topic = id && Engine.topics[ id ];
if ( !topic ) {
callbacks = jQuery.Callbacks();
topic = {
publish: callbacks.fire,
subscribe: callbacks.add,
unsubscribe: callbacks.remove
};
if ( id ) {
Engine.topics[ id ] = topic;
}
}
return topic;
};
$(function() {
Engine.init();
});