-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathCYOAwesome.js
1969 lines (1732 loc) · 59.8 KB
/
CYOAwesome.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
/*
CYOAwesome (2022 update) by @mcfunkypants
TODO - must have
- clicking links during animation ignored - innerHTML is bad
- only run code on same line if prev bool was true
- main menu before playing
- save and dumb load: with no go() at all
- Dialogue (press any key)..
- if first line is ignore due to code, don't render it as a brbr
TODO - nice to have
- flip book js from gamedevwell
- game over and the end and restart- load game button
- AD&D stats rolling 4-1d6
- Text effects (boom) to fix, check iscool on each non tag word
- test full project flow
- real sample game that is actually a fun IF
- >= <=
- !=
- HAS ANY GOLD = HAS GOLD = GOLD? any quantity
- [1d3] [1] [2] [3] shorthand for roll = and roll ==
- insert/embed another scene eg {STATUS}
- more than one parser at the same time: locations and companion chatter
- [GOTO SCENE] immediately run another scene after this one is idle
- [PREV] to previous scene
- game settings (volume etc)
- Timed choices (golf)
- shake HOLD roll onUp golf dice
- game state not saved on edit
- editor window button bar
- credits and props
- coolify fix: shiver shake
- dialog animator
- a nice logo
- fix the twitter account
- wysiwyg editing in place
- while editing, stay on current (re-parsed) scene
- localstorage edit window
- undo
- map view
- inventory view
- quests! parts mcguffins progress
- progress bars
- string entry (what is your name)
- number entry (haggle) slider
- use with (mix objects)
- d&d style combat
- xp and levelups
- allow abstract scumm verb menus
- game settings gui
- game not saved online
- games listing
- game search
- nice debug messages
- live console
- auto-suggest
- beta test login
- optimize: only parse current scene on edit
- obfuscate game data to hassle view-source cheaters
- version numbers
- map with SAW unlocks
- fast travel signposts
- logins
- more fonts
- several templates (font+background+ornaments)
- command-prompt mode: "TAVERN> _"
- keyboard (arrow key / tab) controls
- touch testing
- gamepad controls
- SUBTLE css transitions on many things
- make every word a <span> and add to DOM don't use innerHTML
- decide upon author copyrights (editable scriptkiddie allowed?)
- twitter bot for approved submissions
- player ratings like IFDB etc etc damn portal stuff
- how-to guide
- video tutorials
- a way to get money
- supporters can export html
- supporters can export win, mac, linux, android, ios, xbox, etc
- game jams
- multiplayer collaborative editing
- automap
- room meta xy
- game metas
- dropzone image uploader
- php image cleaner
- php zip
- email verifications
- social media integrations
- all the meta tags in html
- games are static websites CYOAwesome/play/MyGame/
TODONE!
x if we are at a DEAD END automatically give a return path to prev scene. HACKY...
x delete all prev choice buttons on go, not just un <a>
x if first line after scene is blank, don't render it as a brbr
x test all logic
x > <
x ==
x insert inventory quantity
x game is two divs: so_far and dynamic_scene
x save story_so_far as pure text
x remove walkthough on load_game_state
x expositions do not count as a scene change?
x multiple choice buttons
x localstorage game state
x localstorage game walkthrough
x random [25% of the time]
x optimize: only animate current scene
x visual novel mode (cls)
*/
// for no globals, uncomment next line and last line of file
// then edit the html to refer to game.functions()
// var game = new CYOAwesome(); function CYOAwesome() {
"use strict"; // ensure clean clode
var debugmode = true; // no console log if false
var CLEARSCREEN_EACH_SCENE = false; // after the user makes a choice
var CLEARSCREEN_BEFORE_IMAGES = false; // any time we add a new image
// this should probably be false if you only want to use use a menu of choices
var LINKIFY_STORY_TEXT = true; // automagically add <a> to scene names
var DOWNLOAD_STORY_TXT = false; // false: use the value of a textarea, true: ajax downloads story.txt
var fastmode = false; // no text animation if we're editing
var hurry = false; // user wants to fast fwd this scene
// game data: reset in init()
var src = ""; // the entire text full game source code
var firstscene = ""; // string name
var scene = []; // each scene holds an array of string lines
var scenelist = []; // array of scene names for quick access
var code_result = true; // boolean for last code result
var sceneCount = 0; // total in entire game
var last_cls_scene = ""; // used to fix in dead ends
var second_last_cls_scene = ""; // used to fix in dead ends
// game state: reset in init()
var currentscene = ""; // string name
var turn_number = 0; // incremented every click
var visited_scenes = []; // so we know where we've been for SAW,1ST
var inventory = []; // keys/values for HAS,NO,GET,DEL,PUT,>,<,=,+,-,?
var walkthrough = []; // every link linked in order
var story_so_far = ""; // optimization: remember the past html
var ms_per_word = 50; // text animation speed
var prevlink = ""; // name of last clicked word
// html elements
var gamediv = null; // holds entire game
var story_source_textarea = null; // source code embedded inside the html
var gui_TL = null; // in game header
var gui_TR = null; // in game header
var currentscene_div = null; // where dynamic animated text goes
var story_so_far_div = null; // non-interactive past story events
var currentchoices_div = null; // for multiple choices so we can delete
// HUD (gui) elements
var stats_div = null;
var inventory_div = null;
var map_div = null;
var quests_div = null;
// source code for HUD elements
var stats_div_src = null;
var inventory_div_src = null;
var map_div_src = null;
var quests_div_src = null;
// animated word by word
var anim_str = "";
var anim_num = 0;
var anim_has_link = false;
// back up previous text and clear out links
var the_scene_so_far = ""; // html ripped every frame TODO: optimize
function init(story_txt)
{
if (debugmode) console.log("------------------------------------------------");
if (debugmode) console.log("CYOAwesome v0.6 by Christer McFunkypants Kaitila");
if (debugmode) console.log("------------------------------------------------");
init_browser();
if (story_txt != undefined)
{
src = story_txt;
}
else // load story txt from a textarea in the html body
{
if (!story_source_textarea)
console.log("ERROR: no story data found! The html needs a <textarea id='game-source'>")
else
src = story_source_textarea.value;
}
if (debugmode) console.log(src.length + " bytes of source text.");
// reset game state
firstscene = "";
currentscene = "INTRO"; // so we avoid errors on src that doesn't start with a scene name
scene = [];
scenelist = [];
sceneCount = 0;
visited_scenes = [];
inventory = [];
//inventory["CLUE"] = 1; // works
turn_number = 0;
code_result = true;
// clean up the story source
src = src.replace(/\r\n/g, "\n"); // change CRLF to LF
src = src.replace(/\n\n/g, "\n<br><br>\n"); // change double blank lines to breaks
var line = src.split('\n'); // split each line
line = line.map(trimStr); // run on each element
line = line.filter(notBlank); // discard empty ones
if (debugmode) console.log(line.length + " lines found.");
// put each line into the proper scene
for (var pnum=0; pnum<line.length; pnum++)
{
if (isUpperCase(line[pnum])) // new scene! ENTIRE LINE IS UPPERCASE
{
currentscene = line[pnum];
if (scene[currentscene] != null)
{
if (debugmode) console.log("ERROR: duplicate scene name: " + currentscene);
}
else
{
//if (debugmode) console.log("scene: " + currentscene);
scene[currentscene] = [];
sceneCount++;
scenelist.push(currentscene.toUpperCase());
if (!firstscene) firstscene = currentscene;
}
}
else
{
// first or last line of scene? no need for blank lines
if ((line[pnum]=='<br><br>') &&
(
(line[pnum+1] && isUpperCase(line[pnum+1])) || // is NEXT line a section?
(line[pnum-1] && isUpperCase(line[pnum-1])) // or prev?
))
{
//if (debugmode) console.log("Stripping double blank line " + pnum + " in scene " + currentscene);
}
else
{
// add this line to the current scene
if (!scene[currentscene])
{
if (debugmode) console.log("WARNING: creating missing scene: " + currentscene);
scene[currentscene] = [];
}
scene[currentscene].push(line[pnum]);
}
}
}
//srcdiv.style.display = 'none';
if (debugmode) {
console.log(sceneCount + " scenes created.");
var all_scene_names_found = Object.keys(scene);
console.log(all_scene_names_found.join(', '));
}
}
// grab references to a few key html elements
function init_browser()
{
if (debugmode) console.log('init_browser');
// grab html elements
gamediv = document.getElementById("game");
currentscene_div = document.getElementById("current_scene");
currentchoices_div = document.getElementById("current_choices");
story_so_far_div = document.getElementById("story_so_far");
gui_TL = document.getElementById('gui_TL');
gui_TR = document.getElementById('gui_TR');
story_source_textarea = document.getElementById("game_source");
// HUD (gui) elements
stats_div = document.getElementById("stats_div");
inventory_div = document.getElementById("inventory_div");
map_div = document.getElementById("map_div");
quests_div = document.getElementById("quests_div");
// source code for HUD elements
if (stats_div) stats_div_src = stats_div.innerHTML;
if (inventory_div) inventory_div_src = inventory_div.innerHTML;
if (map_div) map_div_src = map_div.innerHTML;
if (quests_div) quests_div_src = quests_div.innerHTML;
// Enable the tab character when editing
enableTab('game_source');
// block the BACK BUTTON
// FIXME this is UX hack but people keep
// pressing the back button or reload by accident
/*
window.onbeforeunload = function(e)
{
var dialogText = 'Quit game?';
e.returnValue = dialogText;
return dialogText;
};
*/
}
function trimStr(str) {
return str.trim();
}
function isUpperCase(str) {
return str === str.toUpperCase();
}
function notBlank(str) {
return str != "";
}
// make any string useable in a regex (we need to escape certain characters)
function preg_quote( str ) {
return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1");
}
// words that could get fun css styles
var onomatopoeia = ['argh','achoo','ahem','bang','bash','bam','bark','bawl','beep',
'belch','blab','blare','blurt','boing','boink','bonk','bong','boo','boo-hoo','boom',
'bow-wow','brring','bubble','bump','burp','buzz','cackle','chatter','cheep','chirp',
'chomp','choo-choo','chortle','clang','clash','clank','clap','clack','clatter','click',
'clink','clip clop','cluck','clunk','cock a doodle doo','cough','crack','crackle',
'crash','creak','croak','crunch','cuckoo','ding','ding dong','drip','fizz','flick',
'flip','flip-flop','flop','flutter','giggle','glug','glup','groan','growl','grunt',
'guffaw','gurgle','hack','haha','hack','hiccup','hiss','hohoho','honk','hoot','howl',
'huh','hum','jangle','jingle','ker-ching','kerplunk','knock','la','meow','moan','moo',
'mumble','munch','murmur','mutter','neigh','oink','ouch','ooze','phew','ping',
'ping pong','pitter patter','plink','plop','pluck','plunk','poof','pong','pop','pow',
'purr','quack','rattle','ribbit','ring','rip','roar','rumble','rush','rustle','screech',
'shuffle','shush','sizzle','slap','slash','slish','slither','slosh','slurp','smack',
'snap','snarl','sniff','snip','snore','snort','spit','splash','splat','splatter','splish',
'splosh','squawk','squeak','squelch','squish','sway','swish','swoosh','thud','thump',
'thwack','tic-toc','tinkle','trickle','twang','tweet','ugh','vroom','waffle','whack',
'whallop','wham','whimper','whip','whirr','whish','whisper','whizz','whoop','whoosh',
'woof','yelp','yikes','zap','zing','zip','zoom','hot','heat','burn','burning','blazing',
'fire','cold','frozen','freeze','ice','chilly','frosty','frost','iced','molten','melt',
'melted','melting','bashed','bash','smashed','smash','broke',
'shattered','beat','punched','hit','slapped','shot','fired','shook','shake','jump',
'tilt','wave','shudder','shake','vibrate','wiggle','wobble','loose','broken','glithy',
'unsteady','drunk','wobbly','shaky','bounced','bounce','rolled','roll','break','broken',
'destroyed','exploded','destruction','death','strong','stronger','weak',
'weaker','angry','sad','mad','hurt','scared','frightened','tired'];
var onomatopoeia_regex = new RegExp('(\\b)(' + onomatopoeia.join('|') + ')(\\b)', 'ig'); // word boundaries // (^|\s) and ($|\s) for entire words
function coolify(str)
{
return str.replace(onomatopoeia_regex, "$1<b class='$2'>$2</b>$3"); // classname gets found
}
// wrap case insensitively matching words in <b> tags
/*
function boldify(haystack, needle) //
{
var prefix = "<b>";// class='$1'>";
var suffix = "</b>";
return (haystack+'').replace( new RegExp( "(" + preg_quote( needle ) + ")" , 'gi' ), prefix + "$1" + suffix );
}
*/
function megalinkify(text) // look for all scenes and add links
{
if (!LINKIFY_STORY_TEXT) return text;
for (var lookfor in scenelist) {
//if (debugmode) console.log("Looking for " + scenelist[lookfor] + " in " + currentscene);
if (scenelist[lookfor] != currentscene) // no self links
{
text = linkify(text,scenelist[lookfor]);
}
}
return text;
}
// wrap case insensitively matching words in <a> tags
function linkify(haystack, needle) // look for ONE scene
{
if (!LINKIFY_STORY_TEXT) return haystack;
var prefix = "<a onclick=\"go('$1',this)\">";
var suffix = "</a>";
return (haystack+'').replace( new RegExp( "(" + preg_quote( needle ) + ")" , 'gi' ), prefix + "$1" + suffix );
}
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
function lastWord(str)
{
return str.split(" ").splice(-1)[0];
}
function nodoublespaces(str)
{
return str.replace(/ +(?= )/g,'');
}
function random_int_range_inclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function IsNumeric(val) {
return Number(parseFloat(val))==val;
}
// turn a string into a number
// it might be a dice roll or a stat
function quantify(str)
{
var int = 0;
if (debugmode) console.log("quantify " + str);
if (inventory[str] != undefined)
{
if (debugmode) console.log("quantify got an item name");
str = ''+inventory[str];
}
if (((str.includes("D")) &&
((IsNumeric(str[0])) || // "3d6"
(IsNumeric(str[1]))))) // "d20"
{
var num = 1;
var die = 6;
if (debugmode) console.log("quantify rolling: " + str);
var chunk = str.split('D');
num = chunk[0];
die = chunk[1];
if (!num) num = 1; // eg d6 gets us a null and a 6
//if (debugmode) console.log('Rolling ' + num + ' d' + die);
var result = 0;
var nextroll = 0;
for (var roll = 0; roll < num; roll++)
{
nextroll = random_int_range_inclusive(1,die);
result += nextroll;
// we could use unicode
//Die face-1 ⚀ U+2680 ⚀
//Die face-2 ⚁ U+2681 ⚁
//Die face-3 ⚂ U+2682 ⚂
//Die face-4 ⚃ U+2683 ⚃
//Die face-5 ⚄ U+2684 ⚄
//Die face-6 ⚅ U+2685 ⚅
// great images
//if (die==6) text += "<div class='dice"+nextroll+"'></div>";
//if (die==6) text += "&#" + (9855 + nextroll) + "; ";
}
if (debugmode) console.log('quantify rolled a ' + result);
int = result;
}
else // just a number
{
if (debugmode) console.log('quantify probably got a number.');
int = parseInt(str);
if (isNaN(int)) int = 0;
if (int==undefined) int = 0;
if (int==null) int = 0;
if (int=='') int = 0;
}
return int;
}
var S_PLURAL = "s"; // suffix from last inserted inventory quantity
var left_right = 'right'; // toggled odd and even class names for isdialog lines
////////////////////////////////////////////////////////
function parse_line(str) // main workhorse of the engine
{
// for each character
var incode = false;
var text = "";
var code = "";
var codeUP = "";
var skip = false;
var verb = "HAS";
var quantity = 1;
var item = "GOLD";
var isdialog = false;
var isbutton = false;
var run_code_now = true;
var pendingDialogFaceIMG = ''; // NPC face images
var do_not_linkify = false; // only true on images so we don't linkify the html/url
if (str.startsWith('//'))
{
if (debugmode) console.log('// SKIPPING A COMMENT');
return "";
}
if (str == undefined)
{
if (debugmode) console.log('WARNING: parsed a blank line. Ignoring.');
return "";
}
if (str[0] == "\"") // starts with a quotation mark?
{
if (debugmode) console.log('Dialog mode!');
isdialog = true;
}
if (str[0] == "-") // multiple choice list?
{
//if (debugmode) console.log('Button:');
str = str.slice(1).trim(); // strip off the dash
isbutton = true;
}
// look at each character, executing [code] in square brackets
for (var i = 0, len = str.length; i < len; i++)
{
if (str[i]=='[')
{
incode = true;
code = "";
}
else if (str[i]==']') // end of a code block! process if required
{
incode = false;
codeUP = code.toUpperCase();
//if (debugmode) console.log('['+codeUP+']');
if (!isbutton)
{
//if (debugmode) console.log('GOT CODE: ' + codeUP); // TODO actually parse!
var code_clean = codeUP.replace('?',' ?');
code_clean = code_clean.replace('>',' > ');
code_clean = code_clean.replace('<',' < ');
code_clean = code_clean.replace('++',' + 1');
code_clean = code_clean.replace('--',' - 1');
code_clean = code_clean.replace('+',' + ');
code_clean = code_clean.replace('-',' - ');
code_clean = code_clean.replace('PICK UP',' GET ');
code_clean = code_clean.replace('!=',' NOT ');
code_clean = code_clean.replace('==',' EQUALS ');
code_clean = code_clean.replace('=',' = ');
code_clean = code_clean.replace('THE PLAYER','');
code_clean = code_clean.replace('DO ',''); // spaces inserted to avoid false matches eg "flower" contains "we"
code_clean = code_clean.replace('WE ','');
code_clean = code_clean.replace('YOU ','');
code_clean = code_clean.replace('WAS ','');
code_clean = code_clean.replace('IS ','');
code_clean = code_clean.replace('USER ','');
code_clean = code_clean.replace('PLAYER ','');
code_clean = code_clean.replace('IF ','');
code_clean = code_clean.replace('WHEN ','');
code_clean = code_clean.replace('DOES ','');
code_clean = code_clean.replace('ONLY ','');
code_clean = code_clean.replace(' TIMES','');
code_clean = code_clean.replace('!','');
code_clean = nodoublespaces(code_clean);
code_clean = code_clean.trim();
var code_split = code_clean.split(' ');
var code_token_count = code_split.length;
// debug the command after string cleaning
if (debugmode && code_split.length>1) console.log('['+code_split[0]+','+code_split[1]+','+code_split[2]+','+code_split[3]+']');
// THREE WORDS OR MORE
if (code_token_count > 2) // "GET 10 GOLD", "has > 5 gold", "has 5 gold ?", "has a gold"
{
// if (debugmode) console.log('code_token_count '+code_token_count);
verb = code_split[0];
quantity = quantify(code_split[1]);
if (code_split[1]=='A') quantity = 1;
if (code_split[1]=='AN') quantity = 1;
if (code_split[1]=='THE') quantity = 1;
if (code_split[1]=='ONE') quantity = 1;
if (code_split[1]=='NO') quantity = 0;
item = code_split[2];
// [HP EQUALS 5 ?]
if (code_split[1] == 'EQUALS')
{
if (debugmode) console.log('eq');
verb = 'HAS';
item = code_split[0];
quantity = quantify(code_split[2]);
}
// [HP 100 ?]
if (code_split[2] == '?')
{
if (debugmode) console.log('?');
verb = 'HAS';
item = code_split[0];
quantity = quantify(code_split[1]);
}
// handle [key + 1]
if (code_split[1] == '+')
{
if (debugmode) console.log('+');
verb = 'GET';
quantity = quantify(code_split[2]);
item = code_split[0];
}
if (code_split[1] == '-')
{
if (debugmode) console.log('-');
verb = 'DROP';
quantity = quantify(code_split[2]);
item = code_split[0];
}
// set is different from adding
if (code_split[1] == '=')
{
if (debugmode) console.log('=');
verb = 'SET';
quantity = quantify(code_split[2]);
item = code_split[0];
}
if (code_split[1] == 'NOT')
{
if (debugmode) console.log('not');
verb = 'NOT';
quantity = quantify(code_split[2]);
item = code_split[0];
}
if (code_split[1] == '>')
{
if (debugmode) console.log('>');
verb = 'HASMORETHAN';
quantity = quantify(code_split[2]);
item = code_split[0];
}
else if (code_split[1] == '<')
{
if (debugmode) console.log('<');
verb = 'HASLESSTHAN';
quantity = quantify(code_split[2]);
item = code_split[0];
}
else if (code_split[3] == '?') // eg [gold = 5 ?]
{
if (debugmode) console.log('? pos 3');
verb = 'HAS';
item = code_split[0];
quantity = quantify(code_split[2]);
}
if (item == 'HAS') // [has > 5 gold]
{
item = code_split[3];
}
}
// TWO WORDS
else if (code_token_count == 2) // "get gold?", "has key", "saw boat", "is angry", 'no key'
{
if (debugmode) console.log('code_token_count '+code_token_count);
verb = code_split[0];
quantity = 1;
item = code_split[1];
if (code_split[0] == 'NO')
{
verb = 'HAS';
quantity = 0;
item = code_split[1];
}
if (code_split[1] == '?') // eg [gold ?]
{
if (debugmode) console.log('?');
verb = 'HAS';
item = code_split[0];
quantity = 1;
}
}
// ONE WORD
else if (code_token_count == 1) // "1st" "else" "KEY" or "GOLD+1" or "FUN++" or "KEY?" or "key>5"
{
if (debugmode) console.log('code_token_count '+code_token_count);
if (codeUP.endsWith("?"))
{
if (debugmode) console.log("Question mark means verb is HAS");
verb = "HAS";
}
else
{
verb = code_split[0]; // 1st
}
quantity = 1;
item = code_split[0];
}
if (code_token_count==1)
{
if (verb == '1ST')
{
if (debugmode) console.log('1st');
code_result = (visited_scenes[currentscene] <= 1);
if (debugmode) console.log(currentscene + " visits: " + visited_scenes[currentscene] + " so code_result=" + code_result);
skip = !code_result;
}
/*
else if (!skip && (
(verb.includes("D")) &&
((IsNumeric(verb[0])) || // "3d6"
(IsNumeric(verb[1]))))) // "d20"
{
var num = 1;
var die = 6;
if (debugmode) console.log("Dice roll: " + verb);
var chunk = verb.split('D');
num = chunk[0];
die = chunk[1];
if (!num) num = 1; // eg d6 gets us a null and a 6
if (debugmode) console.log('Rolling ' + num + ' d' + die);
var result = 0;
var nextroll = 0;
for (var roll = 0; roll < num; roll++)
{
nextroll = random_int_range_inclusive(1,die);
result += nextroll;
// we could use unicode
//Die face-1 ⚀ U+2680 ⚀
//Die face-2 ⚁ U+2681 ⚁
//Die face-3 ⚂ U+2682 ⚂
//Die face-4 ⚃ U+2683 ⚃
//Die face-5 ⚄ U+2684 ⚄
//Die face-6 ⚅ U+2685 ⚅
// great images
//if (die==6) text += "<div class='dice"+nextroll+"'></div>";
if (die==6) text += "&#" + (9855 + nextroll) + "; ";
}
text += " = " +result;
}
*/
else if (!skip && (
endsWith(codeUP,".PNG") ||
endsWith(codeUP,".JPG") ||
endsWith(codeUP,".GIF")
))
{
if (debugmode) console.log("Adding image: " + code + " cls=" + CLEARSCREEN_BEFORE_IMAGES);
if (CLEARSCREEN_BEFORE_IMAGES) clearscreen(); // fixme does this bug stuff?
// special case: inside dialog means a VN style NPC face
if (isdialog)
{
pendingDialogFaceIMG = "<img class='dialog_image' src='img/" + code + "'>";
}
else // normal in-text image full size
{
text = text + "<img class='scene_image' src='img/" + code + "'>";
}
do_not_linkify = true;
verb = "";
item = "";
quantity = "";
}
else if (codeUP == 'S') // quantity suffix from previous inventory insert
{
text += S_PLURAL; // a global that is either "" or "s" // TODO: sometimes should be "es"?
verb = "";
}
else if (codeUP == 'ELSE')
{
if (debugmode) console.log('else');
// do nothing in this state
}
else // regular single word is assume an INVENTORY quantity...
{
if (debugmode) console.log("quantity="+inventory[item]);
if (inventory[item]!=undefined) // insert quantity
{
text += int_to_words(inventory[item]);
if (inventory[item] == 1)
S_PLURAL = "";
else
S_PLURAL = "s";
verb = "";
}
else
{
text += "no";
S_PLURAL = "s";
verb = "";
}
}
} // is 1 token long
if (isNaN(quantity)) quantity = 1;
run_code_now = !isbutton; // just remember the scene name to goto when we click
if (run_code_now)
{
if (verb!="" && debugmode) console.log('verb:'+verb+' quantity:'+quantity+' item:'+item);
if (!skip && (verb == 'SET'))
{
if (debugmode) console.log('setting');
inventory[item] = quantity;
if (debugmode) console.log('(we have exactly '+inventory[item]+' '+item+')');
}
if (!skip && (verb == 'GET' || verb == 'GETS' || verb == 'TAKE' || verb == 'TAKES' || verb == 'GRAB' || verb == 'OBTAIN'))
{
if (debugmode) console.log('getting');
if (!inventory[item]) inventory[item] = 0; // avoid undefined
inventory[item] += quantity;
if (debugmode) console.log('(we now have '+inventory[item]+' '+item+')');
}
if (!skip && (verb == 'PUT' || verb == 'DROP' || verb == 'LOSE' || verb == 'GIVE' || verb == 'DESTROY' || verb == 'DELETE' || verb == 'SUBTRACT'))
{
if (debugmode) console.log('dropping');
if (!inventory[item]) inventory[item] = 0; // avoid undefined
inventory[item] -= quantity;
if (debugmode) console.log('(we now have '+inventory[item]+' '+item+')');
}
if (!skip && (verb == 'NOT'))
{
if (debugmode) console.log('not');
if (inventory[item] != quantity)
{
if (debugmode) console.log('(Yes, we do not have '+quantity+' '+item+', we have '+inventory[item]+')');
code_result = true;
}
else
{
if (debugmode) console.log('(No, we do have '+quantity+' '+item+', we have '+inventory[item]+')');
code_result = false;
}
skip = !code_result;
}
if (!skip && (verb == 'HASLESSTHAN'))
{
if (inventory[item] < quantity)
{
if (debugmode) console.log('(Yes, we have less than '+quantity+' '+item+', we have '+inventory[item]+')');
code_result = true;
}
else
{
if (debugmode) console.log('(No, we do not have less than '+quantity+' '+item+', we have '+inventory[item]+')');
code_result = false;
}
skip = !code_result;
}
if (!skip && (verb == 'HASMORETHAN'))
{
if (inventory[item] > quantity)
{
if (debugmode) console.log('(Yes, we have more than '+quantity+' '+item+', we have '+inventory[item]+')');
code_result = true;
}
else
{
if (debugmode) console.log('(No, we do not have more than '+quantity+' '+item+', we have '+inventory[item]+')');
code_result = false;
}
skip = !code_result;
}
if (!skip && (verb == 'HAS' || verb == 'IS' || verb == 'GOT' || verb == 'WAS' || verb == 'FOUND' || verb == 'HOLDING' || verb == 'HAVE'))
{
if (debugmode) console.log('has');
if (inventory[item] == quantity) // FIXME: what about has gold? we need ANYAMOUNT quantity
{
if (debugmode) console.log('(Yes, we have '+quantity+' '+item+')');
code_result = true;
}
else
{
if (debugmode) console.log('(No, we do not have '+quantity+' '+item+', we have '+inventory[item]+')');
code_result = false;
}
skip = !code_result;
}
if (!skip && (verb == 'NO')) // do we NOT have this in our inventory?
{
if (debugmode) console.log('no');
if (inventory[item] != 0) //quantity)
{
if (debugmode) console.log('(No, we DO have some '+item+', we have '+inventory[item]+')');
code_result = false;
}
else
{
if (debugmode) console.log('(Yes, we do NOT have some '+item+')');
code_result = true;
}
skip = !code_result;
}
if (codeUP == 'ELSE')
{
if (debugmode) console.log('else');
skip = code_result;
if (debugmode) console.log('skip='+skip);
}
// if (debugmode) console.log('code_result='+code_result);
} // if run_code_now
} // if !isbutton
} // end if this char was ]
else if (incode) // more code incoming
{
code = code + str[i];
}
else // regular text, keep going
{
text += str[i];
}
}
if (!skip) // conditional logic may be in effect
{
// search for any scenes to link automagically
// unless we are in a choice button
if (!(isbutton && code_clean != undefined) && (do_not_linkify==false) && LINKIFY_STORY_TEXT)
{
text = megalinkify(text);
}
else
{
//if (debugmode) console.log('Not linkifying this line: '+text);
}
// make onomatopoeias like "shake" animate
//text = coolify(text); // FIXME: what if inside an url? // BUGGY TODO
if (isdialog) // handle character dialog with alternating left/right word bubbles
{
if (left_right == 'left') left_right = 'right'; else left_right = 'left';
text = "<span class='dialog"+ left_right + "'>" + text + "</span>";
// special case: an img inside a dialog means a VN style "face"
// FIXME: I don't like doing it this way: maybe define pos of an img in code?
// eg at front or at end of a line? [IMG] "quote" [IMG]
if (pendingDialogFaceIMG)
{
if (debugmode) console.log('Changing dialog face on the '+left_right+' to ' + pendingDialogFaceIMG);
document.getElementById('face_'+left_right).innerHTML = pendingDialogFaceIMG;
pendingDialogFaceIMG = '';
}
}
if (isbutton) // links to the scene with name [code]
{
if (codeUP != undefined)
{
if (debugmode) console.log('Button: ['+codeUP+']:' + text);
text = "<a class='choice' onclick=\"go('" + codeUP + "',this)\">" + text + "</a>";
}
else // - Text with no [link]
{
if (debugmode) console.log('ERROR: Button ['+text+'] does nothing (no scene name in square brackets)');
text = "<a class='choice' onclick=\"go('" + "" + "',this)\">" + text + "</a>";
}
currentchoices_div.innerHTML += text;
//if (debugmode) console.log('choice html is ' + currentchoices_div.innerHTML);
return "";
}
else // not a button
{
return text + " "; // \n might be nicer?
}
}
else
{