-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
953 lines (803 loc) Β· 25.5 KB
/
index.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
// global properties, assigned with let for easy overriding by the user
let disk;
// store user input history
let inputs = [''];
let inputsPos = 0;
// define list style
let bullet = 'β’';
// reference to the input element
let input = document.querySelector('#input');
// add any default values to the disk
// disk -> disk
let init = (disk) => {
const initializedDisk = Object.assign({}, disk);
initializedDisk.rooms = disk.rooms.map((room) => {
// number of times a room has been visited
room.visits = 0;
return room;
});
if (!initializedDisk.inventory) {
initializedDisk.inventory = [];
}
if (!initializedDisk.characters) {
initializedDisk.characters = [];
}
initializedDisk.characters = initializedDisk.characters.map(char => {
// player's conversation history with this character
char.chatLog = [];
return char;
});
return initializedDisk;
};
// register listeners for input events
let setup = () => {
input.addEventListener('keypress', (e) => {
const ENTER = 13;
if (e.keyCode === ENTER) {
applyInput();
}
});
input.addEventListener('keydown', (e) => {
input.focus();
const UP = 38;
const DOWN = 40;
const TAB = 9;
if (e.keyCode === UP) {
navigateHistory('prev');
} else if (e.keyCode === DOWN) {
navigateHistory('next');
} else if (e.keyCode === TAB) {
e.stopPropagation();
e.preventDefault()
autocomplete();
}
});
input.addEventListener('focusout', () => {
input.focus({preventScroll: true});
});
};
// convert the disk to JSON and store it
// (optionally accepts a name for the save)
let save = (name = 'save') => {
const save = JSON.stringify(disk, (key, value) => typeof value === 'function' ? value.toString() : value);
localStorage.setItem(name, save);
println(`Game saved.`)
};
// restore the disk from storage
// (optionally accepts a name for the save)
let load = (name = 'save') => {
const save = localStorage.getItem(name);
if (!save) {
println(`Save file not found.`);
return;
}
disk = JSON.parse(save, (key, value) => {
try {
return eval(value);
} catch (error) {
return value;
}
});
println(`Game loaded.`)
enterRoom(disk.roomId);
};
// list player inventory
let inv = () => {
if (!disk.inventory.length) {
println(`You don't have any items in your inventory.`);
return;
}
println(`You have the following items in your inventory:`);
disk.inventory.filter(i => i).forEach(item => {
println(`${bullet} ${getName(item.name)}`);
});
};
// show room description
let look = () => {
const room = getRoom(disk.roomId);
if (typeof room.onLook === 'function') {
room.onLook({disk, println});
}
println(room.desc)
};
// look in the passed way
// string -> nothing
let lookThusly = (str) => println(`You look ${str}.`);
// look at the passed item or character
// array -> nothing
let lookAt = (args) => {
const [_, name] = args;
const item = getItemInInventory(name) || getItemInRoom(name, disk.roomId);
if (item) {
// Look at an item.
if (item.desc) {
println(item.desc);
} else {
println(`You don\'t notice anything remarkable about it.`);
}
if (typeof(item.onLook) === 'function') {
item.onLook({disk, println, getRoom, enterRoom, item});
}
} else {
const character = getCharacter(name, getCharactersInRoom(disk.roomId));
if (character) {
// Look at a character.
if (character.desc) {
println(character.desc);
} else {
println(`You don't notice anything remarkable about them.`);
}
if (typeof(character.onLook) === 'function') {
character.onLook({disk, println, getRoom, enterRoom, item});
}
} else {
println(`You don't see any such thing.`);
}
}
};
// list available exits
let go = () => {
const room = getRoom(disk.roomId);
const exits = room.exits;
if (!exits) {
println(`There's nowhere to go.`);
return;
}
println(`Where would you like to go? Available directions are:`);
exits.forEach((exit) => {
const rm = getRoom(exit.id);
if (!rm) {
return;
}
const dir = getName(exit.dir).toUpperCase();
// include room name if player has been there before
const directionName = rm.visits > 0
? `${dir} - ${rm.name}`
: dir
println(`${bullet} ${directionName}`);
});
};
// find the exit with the passed direction in the given list
// string, array -> exit
let getExit = (dir, exits) => exits.find(exit =>
Array.isArray(exit.dir)
? exit.dir.includes(dir)
: exit.dir === dir
);
// go the passed direction
// string -> nothing
let goDir = (dir) => {
const room = getRoom(disk.roomId);
const exits = room.exits;
if (!exits) {
println(`There's nowhere to go.`);
return;
}
const nextRoom = getExit(dir, exits);
if (!nextRoom) {
println(`There is no exit in that direction.`);
return;
}
if (nextRoom.block) {
println(nextRoom.block);
return;
}
enterRoom(nextRoom.id);
};
// shortcuts for cardinal directions
let n = () => goDir('north');
let s = () => goDir('south');
let e = () => goDir('east');
let w = () => goDir('west');
let ne = () => goDir('northeast');
let se = () => goDir('southeast');
let nw = () => goDir('northwest');
let sw = () => goDir('southwest');
// if there is one character in the room, engage that character in conversation
// otherwise, list characters in the room
let talk = () => {
const characters = getCharactersInRoom(disk.roomId);
// assume players wants to talk to the only character in the room
if (characters.length === 1) {
talkToOrAboutX('to', getName(characters[0].name));
return;
}
// list characters in the room
println(`You can talk TO someone or ABOUT some topic.`);
chars();
};
// speak to someone or about some topic
// string, string -> nothing
let talkToOrAboutX = (preposition, x) => {
const room = getRoom(disk.roomId);
if (preposition !== 'to' && preposition !== 'about') {
println(`You can talk TO someone or ABOUT some topic.`);
return;
}
const character =
preposition === 'to' && getCharacter(x, getCharactersInRoom(room.id))
? getCharacter(x, getCharactersInRoom(room.id))
: disk.conversant;
let topics;
// give the player a list of topics to choose from for the character
const listTopics = () => {
// capture reference to the current conversation
disk.conversation = topics;
if (topics.length) {
const availableTopics = topics.filter(topic => topicIsAvailable(character, topic));
if (availableTopics.length) {
println(`What would you like to discuss?`);
availableTopics.forEach(topic => println(`${bullet} ${topic.option ? topic.option : topic.keyword.toUpperCase()}`));
println(`${bullet} NOTHING`);
} else {
endConversation();
}
} else if (Object.keys(topics).length) {
println(`Select a response:`);
Object.keys(topics).forEach(topic => println(`${bullet} ${topics[topic].option}`));
} else {
endConversation();
}
};
if (preposition === 'to') {
if (!getCharacter(x)) {
println(`There is no one here by that name.`);
return;
}
if (!getCharacter(getName(x), getCharactersInRoom(room.id))) {
println(`There is no one here by that name.`);
return;
}
if (!character.topics) {
println(`You have nothing to discuss with ${getName(character.name)} at this time.`);
return;
}
if (typeof(character.topics) === 'string') {
println(character.topics);
return;
}
if (typeof(character.onTalk) === 'function') {
character.onTalk({disk, println, getRoom, enterRoom, room, character});
}
topics = typeof character.topics === 'function'
? character.topics({println, room})
: character.topics;
if (!topics.length && !Object.keys(topics).length) {
println(`You have nothing to discuss with ${getName(character.name)} at this time.`);
return;
}
// initialize the chat log if there isn't one yet
character.chatLog = character.chatLog || [];
disk.conversant = character;
listTopics(topics);
} else if (preposition === 'about') {
if (!disk.conversant) {
println(`You need to be in a conversation to talk about something.`);
return;
}
const character = eval(disk.conversant);
if (getCharactersInRoom(room.id).includes(disk.conversant)) {
const response = x.toLowerCase();
if (response === 'nothing') {
endConversation();
println(`You end the conversation.`);
} else if (disk.conversation && disk.conversation[response]) {
disk.conversation[response].onSelected();
} else {
const topic = disk.conversation.length && conversationIncludesTopic(disk.conversation, response);
const isAvailable = topic && topicIsAvailable(character, topic);
if (isAvailable) {
if (topic.line) {
println(topic.line);
}
if (topic.onSelected) {
topic.onSelected({disk, println, getRoom, enterRoom, room, character});
}
// add the topic to the log
character.chatLog.push(getKeywordFromTopic(topic));
} else {
println(`You talk about ${removePunctuation(x)}.`);
println(`Type the capitalized KEYWORD to select a topic.`);
}
}
// continue the conversation.
if (disk.conversation) {
topics = typeof character.topics === 'function'
? character.topics({println, room})
: character.topics;
listTopics(character);
}
} else {
println(`That person is no longer available for conversation.`);
disk.conversant = undefined;
disk.conversation = undefined;
}
}
};
// list takeable items in room
let take = () => {
const room = getRoom(disk.roomId);
const items = (room.items || []).filter(item => item.isTakeable);
if (!items.length) {
println(`There's nothing to take.`);
return;
}
println(`The following items can be taken:`);
items.forEach(item => println(`${bullet} ${getName(item.name)}`));
};
// take the item with the given name
// string -> nothing
let takeItem = (itemName) => {
const room = getRoom(disk.roomId);
const findItem = item => objectHasName(item, itemName);
let itemIndex = room.items && room.items.findIndex(findItem);
if (typeof itemIndex === 'number' && itemIndex > -1) {
const item = room.items[itemIndex];
if (item.isTakeable) {
disk.inventory.push(item);
room.items.splice(itemIndex, 1);
if (typeof item.onTake === 'function') {
item.onTake({disk, println, room, getRoom, enterRoom, item});
} else {
println(`You took the ${getName(item.name)}.`);
}
} else {
println(item.block || `You can't take that.`);
}
} else {
itemIndex = disk.inventory.findIndex(findItem);
if (typeof itemIndex === 'number' && itemIndex > -1) {
println(`You already have that.`);
} else {
println(`You don't see any such thing.`);
}
}
};
// list useable items in room and inventory
let use = () => {
const room = getRoom(disk.roomId);
const useableItems = (room.items || [])
.concat(disk.inventory)
.filter(item => item.onUse);
if (!useableItems.length) {
println(`There's nothing to use.`);
return;
}
println(`The following items can be used:`);
useableItems.forEach((item) => {
println(`${bullet} ${getName(item.name)}`)
});
};
// use the item with the given name
// string -> nothing
let useItem = (itemName) => {
const item = getItemInInventory(itemName) || getItemInRoom(itemName, disk.roomId);
if (!item) {
println(`You don't have that.`);
return;
}
if (item.use) {
console.warn(`Warning: The "use" property for Items has been renamed to "onUse" and support for "use" has been deprecated in text-engine 2.0. Please update your disk, renaming any "use" methods to be called "onUse" instead.`);
item.onUse = item.use;
}
if (!item.onUse) {
println(`That item doesn't have a use.`);
return;
}
// use item and give it a reference to the game
if (typeof item.onUse === 'string') {
const use = eval(item.onUse);
use({disk, println, getRoom, enterRoom, item});
} else if (typeof item.onUse === 'function') {
item.onUse({disk, println, getRoom, enterRoom, item});
}
};
// list items in room
let items = () => {
const room = getRoom(disk.roomId);
const items = (room.items || []);
if (!items.length) {
println(`There's nothing here.`);
return;
}
println(`You see the following:`);
items
.forEach(item => println(`${bullet} ${getName(item.name)}`));
}
// list characters in room
let chars = () => {
const room = getRoom(disk.roomId);
const chars = getCharactersInRoom(room.id);
if (!chars.length) {
println(`There's no one here.`);
return;
}
println(`You see the following:`);
chars
.forEach(char => println(`${bullet} ${getName(char.name)}`));
};
// display help menu
let help = () => {
const instructions = `The following commands are available:
LOOK: 'look at key'
TAKE: 'take book'
GO: 'go north'
USE: 'use door'
TALK: 'talk to mary'
ITEMS: list items in the room
INV: list inventory items
SAVE: save the current game
LOAD: load the last saved game
HELP: this help menu
`;
println(instructions);
};
// handle say command with no args
let say = () => println([`Say what?`, `You don't say.`]);
// say the passed string
// string -> nothing
let sayString = (str) => println(`You say ${removePunctuation(str)}.`);
// retrieve user input (remove whitespace at beginning or end)
// nothing -> string
let getInput = () => input.value.trim();
// objects with methods for handling commands
// the array should be ordered by increasing number of accepted parameters
// e.g. index 0 means no parameters ("help"), index 1 means 1 parameter ("go north"), etc.
// the methods should be named after the command (the first argument, e.g. "help" or "go")
// any command accepting multiple parameters should take in a single array of parameters
// if the user has entered more arguments than the highest number you've defined here, we'll use the last set
let commands = [
// no arguments (e.g. "help", "chars", "inv")
{
inv,
i: inv, // shortcut for inventory
look,
l: look, // shortcut for look
go,
n,
s,
e,
w,
ne,
se,
sw,
nw,
talk,
t: talk, // shortcut for talk
take,
get: take,
items,
use,
chars,
help,
say,
save,
load,
restore: load,
},
// one argument (e.g. "go north", "take book")
{
look: lookThusly,
go: goDir,
take: takeItem,
get: takeItem,
use: useItem,
say: sayString,
save: x => save(x),
load: x => load(x),
restore: x => load(x),
x: x => lookAt([null, x]), // IF standard shortcut for look at
t: x => talkToOrAboutX('to', x), // IF standard shortcut for talk
},
// two+ arguments (e.g. "look at key", "talk to mary")
{
look: lookAt,
say(args) {
const str = args.reduce((cur, acc) => cur + ' ' + acc, '');
sayString(str);
},
talk: args => talkToOrAboutX(args[0], args[1]),
x: args => lookAt([null, ...args]),
},
];
// process user input & update game state (bulk of the engine)
let applyInput = () => {
const input = getInput();
inputs.push(input);
inputsPos = inputs.length;
println(`> ${input}`);
const val = input.toLowerCase();
setInput(''); // reset input field
const exec = (cmd, arg) => {
if (cmd) {
cmd(arg);
} else if (disk.conversation) {
println(`Type the capitalized KEYWORD to select a topic.`);
} else {
println(`Sorry, I didn't understand your input. For a list of available commands, type HELP.`);
}
};
let args = val.split(' ')
// remove articles (except for the say command, which prints back what the user said)
if (args[0] !== 'say') {
args = args.filter(arg => arg !== 'a' && arg !== 'an' && arg != 'the');
}
const [command, ...arguments] = args;
const room = getRoom(disk.roomId);
if (arguments.length === 1) {
exec(commands[1][command], arguments[0]);
} else if (command === 'take' && arguments.length) {
// support for taking items with spaces in the names
// (just tries to match on the first word)
takeItem(arguments[0]);
} else if (command === 'use' && arguments.length) {
// support for using items with spaces in the names
// (just tries to match on the first word)
useItem(arguments[0]);
} else if (arguments.length >= commands.length) {
exec(commands[commands.length - 1][command], arguments);
} else if (room.exits && getExit(command, room.exits)) {
// handle shorthand direction command, e.g. "EAST" instead of "GO EAST"
goDir(command);
} else if (disk.conversation && (disk.conversation[command] || conversationIncludesTopic(disk.conversation, command))) {
talkToOrAboutX('about', command);
} else {
exec(commands[arguments.length][command], arguments);
}
};
// allows wrapping text in special characters so println can convert them to HTML tags
// string, string, string -> string
let addStyleTags = (str, char, tagName) => {
let odd = true;
while (str.includes(char)) {
const tag = odd ? `<${tagName}>` : `</${tagName}>`;
str = str.replace(char, tag);
odd = !odd;
}
return str;
};
// overwrite user input
// string -> nothing
let setInput = (str) => {
input.value = str;
// on the next frame, move the cursor to the end of the line
setTimeout(() => {
input.selectionStart = input.selectionEnd = input.value.length;
});
};
// render output, with optional class
// (string | array | fn -> string) -> nothing
let println = (line, className) => {
// bail if string is null or undefined
if (!line) {
return;
}
str =
// if this is an array of lines, pick one at random
Array.isArray(line) ? pickOne(line)
// if this is a method returning a string, evaluate it
: typeof line === 'function' ? line()
// otherwise, line should be a string
: line;
const output = document.querySelector('#output');
const newLine = document.createElement('div');
if (className) {
newLine.classList.add(className);
}
// add a class for styling prior user input
if (line[0] === '>') {
newLine.classList.add('user');
}
// support for markdown-like bold, italic & underline tags
if (className !== 'img') {
str = addStyleTags(str, '__', 'u');
str = addStyleTags(str, '**', 'b');
str = addStyleTags(str, '*', 'i');
}
// maintain line breaks
while (str.includes('\n')) {
str = str.replace('\n', '<br>');
}
output.appendChild(newLine).innerHTML = str;
window.scrollTo(0, document.body.scrollHeight);
};
// predict what the user is trying to type
let autocomplete = () => {
const room = getRoom(disk.roomId);
const words = input.value.toLowerCase().trim().split(/\s+/);
const wordsSansStub = words.slice(0, words.length - 1);
const itemNames = (room.items || []).concat(disk.inventory).map(item => item.name);
const stub = words[words.length - 1];
let options;
if (words.length === 1) {
// get the list of options from the commands array
// (exclude one-character commands from auto-completion)
const allCommands = commands
.reduce((acc, cur) => acc.concat(Object.keys(cur)), [])
.filter(cmd => cmd.length > 1);
options = [...new Set(allCommands)];
if (disk.conversation) {
options = Array.isArray(disk.conversation)
? options.concat(disk.conversation.map(getKeywordFromTopic))
: Object.keys(disk.conversation);
options.push('nothing');
}
} else if (words.length === 2) {
const optionMap = {
talk: ['to', 'with', 'about'],
fly: ['to'].concat(disk.rooms.filter((r) => r.isFlyableFrom).map(r => r.id)),
take: itemNames,
use: itemNames,
go: (room.exits || []).map(exit => exit.dir),
look: ['at'],
};
options = optionMap[words[0]];
} else if (words.length === 3) {
const characterNames = (getCharactersInRoom(room.id) || []).map(character => character.name);
const optionMap = {
to: characterNames,
at: characterNames.concat(itemNames),
};
options = (optionMap[words[1]] || []).flat().map(string => string.toLowerCase());
if (words[0] === 'fly'){
options = disk.rooms.filter((r) => r.isFlyableFrom).map(r => r.id);
}
}
const stubRegex = new RegExp(`^${stub}`);
const matches = (options || []).flat().filter(option => option.match(stubRegex));
if (!matches.length) {
return;
}
if (matches.length > 1) {
const longestCommonStartingSubstring = (arr1) => {
const arr = arr1.concat().sort();
const a1 = arr[0];
const a2 = arr[arr.length-1];
const L = a1.length;
let i = 0;
while (i < L && a1.charAt(i) === a2.charAt(i)) {
i++;
}
return a1.substring(0, i);
};
input.value = [...wordsSansStub,longestCommonStartingSubstring(matches)].join(' ');
} else {
input.value = [...wordsSansStub, matches[0]].join(' ');
}
};
// select previously entered commands
// string -> nothing
let navigateHistory = (dir) => {
if (dir === 'prev') {
inputsPos--;
if (inputsPos < 0) {
inputsPos = 0;
}
} else if (dir === 'next') {
inputsPos++;
if (inputsPos > inputs.length) {
inputsPos = inputs.length;
}
}
setInput(inputs[inputsPos] || '');
};
// get random array element
// array -> any
let pickOne = arr => arr[Math.floor(Math.random() * arr.length)];
// return the first name if it's an array, or the only name
// string | array -> string
let getName = name => typeof name === 'object' ? name[0] : name;
// retrieve room by its ID
// string -> room
let getRoom = (id) => disk.rooms.find(room => room.id === id);
// remove punctuation marks from a string
// string -> string
let removePunctuation = str => str.replace(/[.,\/#?!$%\^&\*;:{}=\_`~()]/g,"");
// remove extra whitespace from a string
// string -> string
let removeExtraSpaces = str => str.replace(/\s{2,}/g," ");
// move the player into room with passed ID
// string -> nothing
let enterRoom = (id) => {
const room = getRoom(id);
if (!room) {
println(`That exit doesn't seem to go anywhere.`);
return;
}
println(room.img, 'img');
if (room.name) {
println(`${getName(room.name)}`, 'room-name');
}
if (room.visits === 0) {
println(room.desc);
}
room.visits++;
disk.roomId = id;
if (typeof room.onEnter === 'function') {
room.onEnter({disk, println, getRoom, enterRoom});
}
// reset any active conversation
delete disk.conversation;
delete disk.conversant;
};
// determine whether the object has the passed name
// item | character, string -> bool
let objectHasName = (obj, name) => {
const compareNames = n => n.toLowerCase().includes(name.toLowerCase());
return Array.isArray(obj.name)
? obj.name.find(compareNames)
: compareNames(obj.name);
}
// get a list of all characters in the passed room
// string -> characters
let getCharactersInRoom = (roomId) => disk.characters.filter(c => c.roomId === roomId);
// get a character by name from a list of characters
// string, characters -> character
let getCharacter = (name, chars = disk.characters) => chars.find(char => objectHasName(char, name));
// get item by name from room with ID
// string, string -> item
let getItemInRoom = (itemName, roomId) => {
const room = getRoom(roomId);
return room.items && room.items.find(item => objectHasName(item, itemName))
};
// get item by name from inventory
// string -> item
let getItemInInventory = (name) => disk.inventory.find(item => objectHasName(item, name));
// retrieves a keyword from a topic
// topic -> string
let getKeywordFromTopic = (topic) => {
if (topic.keyword) {
return topic.keyword;
}
// find the keyword in the option (the word in all caps)
const keyword = removeExtraSpaces(removePunctuation(topic.option))
// separate words by spaces
.split(' ')
// find the word that is in uppercase
// (must be at least 2 characters long)
.find(w => w.length > 1 && w.toUpperCase() === w)
.toLowerCase();
return keyword;
};
// determine whether the passed conversation includes a topic with the passed keyword
// conversation, string -> boolean
let conversationIncludesTopic = (conversation, keyword) => {
// NOTHING is always an option
if (keyword === 'nothing') {
return true;
}
if (Array.isArray(disk.conversation)) {
return disk.conversation.find(t => getKeywordFromTopic(t) === keyword);
}
return disk.conversation[keyword];
};
// determine whether the passed topic is available for discussion
// character, topic -> boolean
let topicIsAvailable = (character, topic) => {
// topic has no prerequisites, or its prerequisites have been met
const prereqsOk = !topic.prereqs || topic.prereqs.every(keyword => character.chatLog.includes(keyword));
// topic is not removed after read, or it hasn't been read yet
const readOk = !topic.removeOnRead || !character.chatLog.includes(getKeywordFromTopic(topic));
return prereqsOk && readOk;
};
// end the current conversation
let endConversation = () => {
disk.conversant = undefined;
disk.conversation = undefined;
};
// load the passed disk and start the game
// disk -> nothing
let loadDisk = (uninitializedDisk) => {
// initialize the disk
disk = init(uninitializedDisk);
// start the game
enterRoom(disk.roomId);
// start listening for user input
setup();
// focus on the input
input.focus();
};
// npm support
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = loadDisk;
}