-
Notifications
You must be signed in to change notification settings - Fork 0
/
TypeFic.ts
104 lines (94 loc) · 2.73 KB
/
TypeFic.ts
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
/*
TypeFic interactive fiction framework
Designed and developed by Benny Mattis.
*/
export type startingInputs = {
currentBook: book,
currentChapter: string,
currentPageIndex: number,
currentVariables?: {}
}
export type readOutputs = {
text: string,
choices: string[],
}
export type state = {
currentBook: book,
currentChapter: string,
currentPageIndex: number,
currentVariables: {[key: string]: any},
gameOver: boolean
}
export type choiceGroup = {
[key: string]: (currentState: state) => void
}
export type chapter = {
chapterPages: (string | ((currentState: state) => string))[],
chapterEndingChoices: choiceGroup
}
export type book = {
bookChapters: {[key: string]: chapter},
bookVariables?: {[key: string]: any}
}
export class TypeFic {
gameState: state;
constructor(startingState: startingInputs) {
this.gameState = {
...startingState,
gameOver: false,
currentVariables: {}
};
if ('bookVariables' in this.gameState.currentBook) {
for (const variable in this.gameState.currentBook.bookVariables) {
this.gameState.currentVariables[variable] = this.gameState.currentBook.bookVariables[variable];
}
}
}
read(input: string = ''): {text: string, choices: string[]} {
let output: readOutputs = {
text: '',
choices: ['']
};
if (this.gameState.gameOver) {
output.text = 'game over.';
return output;
}
const oldChapter = this.gameState.currentBook.bookChapters[this.gameState.currentChapter];
const oldChapterChoicePageIndex: number = oldChapter.chapterPages.length - 1;
let oldChoices: choiceGroup;
let oldPage: string | ((currentState: state) => string);
const changingChapter: boolean = this.gameState.currentPageIndex == oldChapterChoicePageIndex
if (changingChapter) {
oldPage = oldChapter.chapterPages[oldChapterChoicePageIndex];
oldChoices = oldChapter.chapterEndingChoices;
}
else {
oldPage = oldChapter.chapterPages[this.gameState.currentPageIndex];
oldChoices = {
'continue': (currentState: state) => {
currentState.currentPageIndex++;
return;
}
}
}
if (!input) {
if (typeof oldPage == "string") {
output.text = oldPage;
} else if (typeof oldPage == "function") {
output.text = oldPage(this.gameState);
}
output.choices = Object.keys(oldChoices);
return output;
}
else if (input in oldChoices) {
oldChoices[input](this.gameState);
if (changingChapter) this.gameState.currentPageIndex = 0;
return this.read();
}
else {
output.text = 'invalid input: "' + String(input) + '"';
output.choices = Object.keys(oldChoices);
return output;
}
}
}