-
Notifications
You must be signed in to change notification settings - Fork 1
/
jzip.html
862 lines (809 loc) · 24.9 KB
/
jzip.html
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
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="jzip.js"></script>
<script src="map.js"></script>
<script src="storage.js"></script>
<meta name="google-signin-scope" content="https://www.googleapis.com/auth/drive">
<meta name="google-signin-client_id" content="225627196149-0b14oj1dbo6uomb7skb56lu8ocpvb8cn.apps.googleusercontent.com">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script src="https://apis.google.com/js/client.js"></script>
<link href="jzip.css" rel="stylesheet" type="text/css">
<link href="storage.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="statuswindow">
<span class="builtin" id="time">Time:</span>
<span class="builtin" id="moves">Moves:</span>
<span class="builtin" id="score">Score:</span>
</div>
<div id="touchkey">
Touch here to press <b>Space</b>
</div>
<div id="inputline">
<input id="input" type="text">
<span class="prompt"><b>></b></span>
</div>
<div id="mapcontainer">
<div class="handle"></div>
<div class="menu">
<span class="save">Save map</span>
<span class="open">Open map</span>
</div>
<div class="view"></div>
</div>
<div class="dialog" id="storagedialog">
<h1 class="save">Save <span class="basename"></span>…</h1>
<h1 class="open">Open <span class="basename"></span>…</h1>
<div class="server option open">
<h2 class="open">…from server.</h2>
<select>
</select>
<button>
<span class="open">Open</span>
</button>
</div>
<div class="local option">
<h2 class="save">…on this browser</h2>
<h2 class="open">…from this browser</h2>
<input class="save" type="text" placeholder="New file"/>
<div class="hasfiles">
<select>
<option value="" class="null save">New file</option>
<optgroup label="Existing files">
</optgroup>
</select>
</div>
<button>
<span class="save">Save</span>
<span class="open">Open</span>
</button>
</div>
<div class="file option">
<h2 class="save">…on this computer</h2>
<h2 class="open">…from this computer</h2>
<div class="save">
<a download="save.sav" class="downloadlink" href="">Download <span class="basename"></span>…</a>
</div>
<div class="open">
<input type="file"/>
<button>
<span class="save">Save</span>
<span class="open">Open</span>
</button>
</div>
</div>
<div class="drive option">
<h2 class="save">…on Google Drive</h2>
<h2 class="open">…from Google Drive</h2>
<div class="signedin">
<input class="save" type="text" placeholder="New file"/>
<div class="hasfiles">
<select>
<option value="" class="null save">New file</option>
<optgroup label="Existing files">
</optgroup>
</select>
</div>
<button>
<span class="save">Save</span>
<span class="open">Open</span>
</button>
</div>
<div class="signedout">
<div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>
</div>
</div>
</div>
<script>
(function(){
var $input = $('#input'), focusInput = true
, $statw = $('#statuswindow')
, $mapcontainer = $('#mapcontainer')
, storage = Storage()
, ls = window.localStorage || null
, history = ( ls && JSON.parse(ls.getItem('jszipHistory')||'[]') ) || []
, hindex = history.length
, autocomplete = {}, sortedWords = []
, automap = {}, lastDirection=null, lastRoom=null, map = RoomMap($mapcontainer), playerObject=null
, hmax = 100 // size of command history
, moveCount = 0 // number of commands entered
, keyCallback = null
, lineCallback = null
, CLIENT_ID = '961409091716-f13l7n45n8u0uvkjqc9vjjddndd40jgs.apps.googleusercontent.com'
, SCOPES = 'https://www.googleapis.com/auth/drive'
, ztypes = {
H_SCREEN_ROWS: 32,
H_SCREEN_COLUMNS: 33,
H_SCREEN_LEFT: 34,
H_SCREEN_RIGHT: 35,
H_SCREEN_TOP: 36,
H_SCREEN_BOTTOM: 37,
H_MAX_CHAR_WIDTH: 38,
H_MAX_CHAR_HEIGHT: 39,
H_FILLER1: 40,
'PARENT': 0,
NEXT: 1,
CHILD: 2
};
// hook key events up to input widget (closure for local variables)
function setupInput() {
var prefix=null, currentSuggestions=[], suggestionIndex=0, tBefore, tAfter, stem='';
// select a range of characters in the input box
function selectRange(start,end) {
var i=$input[0], v = $input.val(), l=v.length;
if (i.setSelectionRange) {
i.focus();
i.setSelectionRange(start,end);
} else if (i.createTextRange) {
var range = i.createTextRange();
range.collapse(true);
range.moveStart('character', start);
range.select();
}
}
function getCaretPosition() {
if (document.selection) {
var sel = document.selection.createRange ();
sel.moveStart ('character', -$input.val().length);
return sel.text.length;
}
return $input[0].selectionStart || 0;
}
// make storage module Google auth2 handler available
window.onSignIn = storage.onSignIn;
$input.focus().keydown(function(e) {
var v = $input.val(), last, pos;
//console.log(e.keyCode);
switch(e.keyCode) {
case 9: // Tab
if (prefix===null) {
// find current last word
pos = getCaretPosition();
tBefore = v.substr(0,pos);
tAfter = v.substr(pos);
tAfter = tAfter.substr(tAfter.indexOf(' ')+0); // drop everything till first space
last = tBefore.lastIndexOf(' ')+1
prefix = tBefore.substr(last);
stem = v.substr(0,last);
currentSuggestions = getAutocompleteList(prefix);
//console.log(prefix,currentSuggestions);
suggestionIndex=0;
//console.log(getCaretPosition());
}
// cycle through suggestions
if (suggestionIndex < currentSuggestions.length) {
var t = stem+currentSuggestions[suggestionIndex];
$input.val(t+tAfter);
selectRange(tBefore.length,t.length);
suggestionIndex++;
if (suggestionIndex == currentSuggestions.length) suggestionIndex=0;
}
e.preventDefault();
break;
case 38: // Cursor up
if (hindex>0) {
if (v!=='') { history[hindex] = v; }
$input.val(history[--hindex]);
}
e.preventDefault();
break;
case 40: // Cursor down
if (hindex<history.length) {
if (v!=='') { history[hindex] = v; }
$input.val(history[++hindex]);
}
e.preventDefault();
break;
case 13: // Enter
if (v!=='') {
hindex = history.length;
history[hindex++] = v;
// only keep the last hmax commands in the history
if (hindex>hmax) {
history=history.slice(-hmax);
hindex=hmax;
}
ls.setItem('jszipHistory',JSON.stringify(history))
}
if (lineCallback) {
$input.val('');
lineCallback(v);
} else {
e.preventDefault();
}
break;
case 32: // space
// accept current suggestion
if (prefix!==null) {
prefix=null;
$input.val(v+' ');
e.preventDefault();
}
break;
default:
// invalidate the current autocomplete prefix
prefix=null;
}
e.stopPropagation();
});
};
setupInput();
// hook key events up to document
$(document).keydown(function(e) {
//console.log(e.keyCode);
if (keyCallback) {
keyCallback(e.keyCode);
} else {
switch(e.keyCode) {
case 27: // ESC
// if dialog open
$('.dialog').fadeOut();
step();
break;
case 78: // n
case 104: // Numpad 8 (n)
if (lineCallback) { lineCallback('n',true); }
break;
case 69: // e
case 102: // Numpad 6 (e)
if (lineCallback) { lineCallback('e',true); }
break;
case 83: // s
case 98: // Numpad 2 (s)
if (lineCallback) { lineCallback('s',true); }
break;
case 87: // w
case 100: // Numpad 4 (w)
if (lineCallback) { lineCallback('w',true); }
break;
case 103: // Numpad 7 (nw)
if (lineCallback) { lineCallback('nw',true); }
break;
case 105: // Numpad 9 (ne)
if (lineCallback) { lineCallback('ne',true); }
break;
case 99: // Numpad 3 (se)
if (lineCallback) { lineCallback('se',true); }
break;
case 97: // Numpad 1 (sw)
if (lineCallback) { lineCallback('sw',true); }
break;
case 85: // u
if (lineCallback) { lineCallback('u',true); }
break;
case 68: // d
if (lineCallback) { lineCallback('d',true); }
break;
}
}
});
// hide input widgets
$('#inputline').hide();
$('#readkey').hide();
// setup map widget
function setupMap() {
var shown=false;
$('.handle',$mapcontainer).on('click', function(){
shown = !shown;
$mapcontainer.css('right',shown?'80%':'');
});
$('.menu>.save',$mapcontainer).on('click', function() {
storage.save( {
basename: 'automap',
pattern: '.+\.zmap',
local: 'jszipMaps',
data: JSON.stringify(automap)
} );
});
$('.menu>.open',$mapcontainer).on('click', function() {
storage.open( {
basename: 'automap',
pattern: '.+\.zmap',
local: 'jszipMaps',
binary: false,
callback: function(data) {
if (data===null) {
error('Loading automap failed.');
} else {
automap = JSON.parse(data);
map.update(automap);
}
}
} );
});
map.update(automap);
}
setupMap();
// functions to be called from the c code
var out = window['output'] = {
buf:'',
col:0, row: 0,
rowspan: [], line: [],
emptyLine: '',
text: true,
reverse: false, bold: false, emph: false, fixed: false
}, argstore = window['argstore']={};
var writeChar = window['jsWriteChar'] = function(c) {
function flushBuffer() {
addToAutocomplete(out.buf);
out.buf += closeAttributes()
var $line = $('<div class="output"></div>').html(out.buf).insertBefore($('#inputline'));
scrollBottom();
out.buf = openAttributes()
}
//if(String.fromCharCode(c)=='>') console.log('jsWriteChar',c,String.fromCharCode(c));
if (window['globalvars']['h_type']<=3) {
// Z3 and below
if (c==13 || c==10 ) {
if (out.text) {
flushBuffer();
} else {
out.rowspan[out.row-1].text(out.buf);
out.buf='';
}
} else {
out.buf += String.fromCharCode(c);
}
} else {
// higher versions (Z5, Z8 etc.)
if (out.text) {
// output text
if (c==13 || c==10 ) {
flushBuffer();
} else {
out.buf += String.fromCharCode(c);
}
} else {
// update status line
var l = out.line[out.row-1]
, r = out.rowspan[out.row-1]
, i = out.col-1;
if (l && r) {
l = l.substr(0,i) + String.fromCharCode(c) + l.substr(i+1);
r.text(l);
out.line[out.row-1] = l;
out.col++;
}// else {
// console.log('writing out of status area');
//}
}
}
}
window['jsPrintString'] = function(s) {
var c,t='',p=s,l=[];
while(c=Module.getValue(p++, 'i8')) {
writeChar(c);
t+=String.fromCharCode(c);
l.push(c)
}
//if (l.length>0) console.log('printstring',p-s,s,p,t,l);
}
window['jsFlushTo'] = function(s) {
//console.log('jsFlushTo(',s,')');
var c=$('#'+s);
if (out.buf=='') {
c.hide();
} else {
c.text(out.buf).show();
out.buf='';
}
}
window['jsSetWindow'] = function(w) {
var newwin;
console.log('z_set_window(',w,')');
if (w==='status') {
newwin=false;
} else if (w==='text') {
newwin=true;
} else {
throw Error("Unknown window type");
}
// flush on window change from text->status
if (out.text && !newwin) {
// is this just the prompt char?
if (out.buf==='>') {
out.buf='';
} else {
writeChar(13);
}
}
out.text = newwin;
}
window['jsBlankStatus'] = function() {
console.log('blank_status()');
}
window['jsMoveCursor'] = function(row,col) {
console.log("z_set_cursor",out.text,row,col,out.buf);
out.row=row;
out.col=col;
}
window['jsSplitWindow'] = function(lines) {
var cols = out.emptyLine.length;
console.log('z_split_window',lines);
$('body').css('padding-top',(lines+1)+'em');
if (lines) {
$statw.show().css('height',lines+'em');
$('.statusrow',$statw).remove();
out.rowspan=[];
for (var i=0; i<lines; ++i) {
// make sure length is exactly cols
if (out.line[i]===undefined) {
out.line[i]=out.emptyLine;
}
out.line[i]=out.line[i].substr(0,cols) + out.emptyLine.substr(out.line[i].length);
// rebuild span
out.rowspan[i] = $('<span class="statusrow"></span>').css('top',i+'.5em').text(out.line[i]).attr('id','row'+(i+1)).appendTo($statw);
}
} else {
$statw.hide();
}
}
window['jsSetAttribute'] = function( normal,reverse, bold, emph, fixed ) {
out.buf += closeAttributes();
out.reverse = ~~reverse;
out.bold = ~~bold;
out.emph = ~~emph;
out.fixed = ~~fixed;
out.buf += openAttributes();
//console.log('jsSetAttribute',JSON.stringify(out));
}
// * For Z3 games this is called when drawing the fixed format status line
// * For Z5 and above games this is called as soon at the game returns to the
// input prompt. The id is the parent object of the player. The player object
// is guessed below
var registerLocation = window['jsRegisterLocation'] = function(id,name) {
//console.log('register location:',id,name, lastRoom,lastDirection);
var update=false
, name = name || out.buf;
// store current room number and name
if (id!==lastRoom) {
// add transition to last room
if (lastRoom!==null && (lastRoom in automap) && lastDirection!==null) {
if (automap[lastRoom][lastDirection] !== id) {
automap[lastRoom][lastDirection]=id;
update = true;
}
}
// add new room
if (!(id in automap)) {
automap[id] = {'name': name};
map.clear();
map.update(automap);
} else {
if (update) {
map.clear();
map.update(automap);
}
}
map.highlight(id);
lastRoom=id;
}
// update if anything has changed
if (update) {
}
}
// tasks
function taskGetLine(e) {
var t=e.timeout,h=null;
// prepare Autocomplete word list
prepareAutocomplete();
// automapping based on heuristically determined playerObject Z5,Z8 games
if (playerObject!==null) {
var p = parentObject(playerObject);
registerLocation(p,objectName(p));
}
// display input line
$('#inputline').val('').show();
if(focusInput) $input.focus();
scrollBottom();
out.buf='';
lineCallback=function(text, nofocus) {
var i,l=text.length;
focusInput = !nofocus;
// clean up
$('#inputline').hide();
$input.blur();
lineCallback=null;
if (h) clearTimeout(h);
// set the last direction to guide the automapper
lastDirection = parseDirection(text);
// increase moveCount
moveCount++;
// echo input
$('#inputline')
.before($('<div class="echo"></div>')
.text('> '+text)
.click(function(e){
// make previous input clickable for tablets
$input.val(text).focus();
}));
// put text into buffer
for (i=0;i<l;++i) {
Module.setValue(e.buffer+i,text.charCodeAt(i),'i8');
}
jsrGetLine(e.cbuf, e.buffer, l, 13, e.timeout, e.action_routine );
step();
};
// set up a timeout
if (t>0) {
h = setTimeout(function(){
$('#inputline').hide();
$input.blur();
lineCallback=null;
jsrGetLine(e.cbuf, e.buffer, 0, -1, e.timeout, e.action_routine );
step();
},t*1000);
}
}
function taskInputCharacter(e) {
var t=e.timeout,h=null;
// display readkey bar (for touch devices)
$('#touchkey').show().on('click', function() {
//clean up
keyCallback = null;
if (h) clearTimeout(h);
// hide readkey bar
$('#touchkey').hide().off('click');
jsrInputCharacter(32, t);
step();
});
keyCallback = function(c) {
//clean up
keyCallback = null;
if (h) clearTimeout(h);
// TODO: we might want to check if the t needs to be the remaining time...
jsrInputCharacter(c, t);
step();
}
// set up a timeout
if (t > 0) {
h = setTimeout(function(){
keyCallback = null;
jsrInputCharacter(-1, t);
step();
}, t * 1000);
}
}
function taskSave() {
storage.save( {
basename: 'savegame',
pattern: '.+\.sav',
local: 'jszipSaves',
data: FS.readFile('save.sav'),
callback: function(success,msg) {
if (!success) {
error("Save failed! " + success + (msg||''));
}
step();
}
} );
FS.unlink('save.sav');
}
function taskRestore(e) {
storage.open( {
basename: 'savegame',
pattern: '.+\.sav',
local: 'jszipSaves',
callback: function(data) {
if (data===null) {
error('Restore failed.');
} else {
FS.createDataFile('/', 'save.sav', data, true, true);
zRestore(e.count,e.o0,e.o1,e.o2);
FS.unlink('save.sav');
}
step();
}
} );
}
// exported functions
var spinupJS = Module.cwrap('spinupJS', 'number', ['string'])
, interpret = Module.cwrap('interpret', 'number')
, jsrGetLine = Module.cwrap('jsrGetLine', 'number', ['number','number','number','number','number','number'])
, jsrInputCharacter = Module.cwrap('jsrInputCharacter', 'number', ['number','number'])
, jsrResizeWindow = Module.cwrap('jsrResizeWindow', 'number', ['number'])
, zRestore = Module.cwrap('z_restore', 'number', ['number','number','number','number'])
, printObject = Module.cwrap('z_print_obj', 'number', ['number'])
, readObject = Module.cwrap('read_object', 'number', ['number','number'])
, getObjectAddress = Module.cwrap('get_object_address', 'number', ['number']);
window['zLoadVariable'] = Module.cwrap('load_variable', 'number', ['number']);
// helper functions
function scrollBottom() {
$('body').hide().show(0)[0].scrollTop=$('body').height()
}
function error(t) {
$('<div class="error"></div>').text(t).insertBefore($('#inputline'));
}
function addToAutocomplete(text) {
// add words from text to autocomplete hash (with current moveCount)
var words = text.split(/[\s,.!?)(]+/), i, l=words.length, word;
for (i=0; i<l; ++i) {
word = words[i].toLowerCase();
if (/^[a-zA-Z-]+$/.test(word) && word.length>2) {
autocomplete[word]=moveCount;
}
}
}
function prepareAutocomplete() {
// expire words from more than 5 moves back
var word;
sortedWords=[];
for (word in autocomplete) {
if (autocomplete.hasOwnProperty(word)) {
if (autocomplete[word]+5<moveCount) {
delete autocomplete[word];
} else {
sortedWords.push(word);
}
}
}
sortedWords.sort();
//console.log(sortedWords);
}
function getAutocompleteList(p) {
// get a list of all candidate words in the AC list
if (p==='') return [];
// do linear search (simpler)
var l=sortedWords.length, a, b;
// get start of slice (first candidate)
for(a=0; a<l && p>sortedWords[a]; ++a);
for(b=a; b<l && sortedWords[b].indexOf(p)==0; ++b);
return sortedWords.slice(a,b);
}
function parseDirection(command) {
// try to parse user input to store the last geiven direction of movement
var v=command.toLowerCase().replace(/^\s+/,'').replace(/\s+$/,'');
if (/^n$|^north$|^go north$/.test(v)) return 'n';
if (/^e$|^east$|^go east$/.test(v)) return 'e';
if (/^s$|^south$|^go south$/.test(v)) return 's';
if (/^w$|^west$|^go west$/.test(v)) return 'w';
if (/^u$|^up$|^upstairs$|^go up$/.test(v)) return 'u';
if (/^d$|^down$|^downstairs$|^go down$/.test(v)) return 'd';
if (/^ne$|^northeast$|^go northeast$/.test(v)) return 'ne';
if (/^nw$|^northwest$|^go northwest$/.test(v)) return 'nw';
if (/^se$|^southeast$|^go southeast$/.test(v)) return 'se';
if (/^sw$|^southwest$|^go southwest$/.test(v)) return 'sw';
return null;
}
function testScreenWidth() {
var $s = $('<span class="statusrow"></span>').css({ position: 'relative', top: '-1000px'}).appendTo($('body'))
, sw = $(window).width()
, i, j, t, a='WMx. l', w, c=null, wc;
for (i=0; i<a.length; ++i) {
t='';
for (j=0; j<100; ++j) { t+=a[i]; }
$s.text(t);
w = $s.width()/100.0;
wc = Math.floor(sw/w);
// we test a few characters. they should all have the _same_ width. Just in case something weird goes on, take the smallest char number that fits.
if( c===null || c>wc ) {
c=wc;
}
}
$s.remove();
return c-2; // -2 to account for padding
}
function openAttributes() {
var t='';
if (out.reverse) t += '<span style="reverse">';
if (out.bold) t += '<b>';
if (out.emph) t += '<i>';
if (out.fixed) t += '<tt>';
return t;
}
function closeAttributes() {
var t='';
// close in reverse order to produce valid html
if (out.fixed) t += '</tt>';
if (out.emph) t += '</i>';
if (out.bold) t += '</b>';
if (out.reverse) t += '</span>';
return t;
}
function objectName(obj) {
// save output buffer
var t=out.text, b=out.buf, r;
out.buf='';
printObject(obj);
r=out.buf;
// restore output buffer
out.text=t; out.buf=b;
return r;
}
function parentObject(obj) {
var adr = getObjectAddress(obj);
return readObject(adr,ztypes.PARENT);
}
// prepare global variable object
window.globalvars = {};
// call interpreter
function step() {
try {
interpret();
} catch(e) {
console.log('Exception:',e);
switch(e.task||'') {
case 'getLine':
taskGetLine(e);
break;
case 'inputCharacter':
taskInputCharacter(e);
break;
case 'z_save':
taskSave();
break
case 'z_restore':
taskRestore(e);
break
default:
error("jzip.js terminated. Reload the page to play again.");
throw e;
}
}
}
// Start z-machine
function startGame(data) {
if (data===null) {
error('no game selected');
return;
} else {
FS.createDataFile('/', 'game.z5', data, true, true);
spinupJS('game.z5');
}
// set the screen witdth in monospace characters (and update on resize)
function setupScreen() {
var w = testScreenWidth();
function update(w) {
// set variable and line template
window['globalvars']['screen_cols'] = w;
out.emptyLine = Array(w+1).join(" ")
// clear status buffer
for (var i=0; i<out.line.length; ++i) {
out.line[i]=out.emptyLine;
}
}
$(window).on('resize',function() {
// update the screen_cols variable and z-machine register on resize
w = testScreenWidth();
jsrResizeWindow(w);
update(w);
});
update(w);
};
setupScreen();
// at this point the globalvars object is populated
// automapping for >Z3 games is challenging
if (window['globalvars']['h_type']>3) {
// search for player object
//"(self object)" "yourself"
// TODO find number of objects
var i, name;
for (i=0; i<200; ++i) {
name = objectName(i);
if (name=='(self object)' || name=='(self obj)' || name=='yourself') {
console.log('found potential player',i);
playerObject=i;
break;
}
}
}
step();
}
storage.open( {
pattern: '.+\.z.',
basename: 'story file',
server: {
'data/woman.z8': '"Inside Woman" (Andy Phillips)',
'data/curses.z5': '"Curses" (Graham Nelson)',
'data/minster.z5': '"Christminster (Gareth Rees)',
'data/anchor.z8': '"Anchorhead" (Michael S. Gentry)',
'data/tangle.z5': '"Spider and Web" (Andrew Plotkin)'
},
callback: startGame
} );
})();
</script>
</body>
</html>