-
Notifications
You must be signed in to change notification settings - Fork 487
/
Game.js
402 lines (352 loc) 路 11.1 KB
/
Game.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
import fs from 'fs';
import path from 'path';
import globby from 'globby';
import { getLevel, runLevel } from '@warriorjs/core';
import GameError from './GameError';
import Profile from './Profile';
import ProfileGenerator from './ProfileGenerator';
import getLevelConfig from './utils/getLevelConfig';
import getWarriorNameSuggestions from './utils/getWarriorNameSuggestions';
import loadTowers from './loadTowers';
import printFailureLine from './ui/printFailureLine';
import printLevelReport from './ui/printLevelReport';
import printLevel from './ui/printLevel';
import printLine from './ui/printLine';
import printPlay from './ui/printPlay';
import printSeparator from './ui/printSeparator';
import printSuccessLine from './ui/printSuccessLine';
import printTowerReport from './ui/printTowerReport';
import printWarningLine from './ui/printWarningLine';
import printWelcomeHeader from './ui/printWelcomeHeader';
import requestChoice, { SEPARATOR } from './ui/requestChoice';
import requestConfirmation from './ui/requestConfirmation';
import requestInput from './ui/requestInput';
const gameDirectory = 'warriorjs';
/** Class representing a game. */
class Game {
/**
* Creates a game.
*
* @param {string} runDirectoryPath The directory under which to run the game.
* @param {number} practiceLevel The level to practice.
* @param {boolean} silencePlay Whether to suppress play log or not.
* @param {number} delay The delay between each turn in seconds.
* @param {boolean} assumeYes Whether to answer yes to every question or not.
*/
constructor(runDirectoryPath, practiceLevel, silencePlay, delay, assumeYes) {
this.runDirectoryPath = runDirectoryPath;
this.practiceLevel = practiceLevel;
this.silencePlay = silencePlay;
this.delay = delay * 1000;
this.assumeYes = assumeYes;
this.gameDirectoryPath = path.join(this.runDirectoryPath, gameDirectory);
}
/**
* Starts the game.
*/
async start() {
printWelcomeHeader();
try {
this.towers = loadTowers();
this.profile = await this.loadProfile();
if (this.profile.isEpic()) {
await this.playEpicMode();
} else {
await this.playNormalMode();
}
} catch (err) {
if (
err instanceof GameError ||
err.message.startsWith('Invalid Player code')
) {
printFailureLine(err.message);
} else {
throw err;
}
}
}
/**
* Loads a profile into the game.
*
* If the game is being run from a profile directory, that profile will be
* loaded. If not, the player will be given the option to choose a profile.
*
* @returns {Profile} The loaded profile.
*/
async loadProfile() {
const profile = Profile.load(this.runDirectoryPath, this.towers);
if (profile) {
return profile;
}
return this.chooseProfile();
}
/**
* Gives the player the option to choose one of the available profiles.
*
* If there are no profiles available in the game directory or the player
* chooses to, creates a new profile.
*
* @returns {Profile} The chosen profile.
*/
async chooseProfile() {
const profiles = this.getProfiles();
if (profiles.length) {
const newProfileChoice = 'New profile';
const profileChoices = [...profiles, SEPARATOR, newProfileChoice];
const profile = await requestChoice('Choose a profile:', profileChoices);
if (profile !== newProfileChoice) {
return profile;
}
}
return this.createProfile();
}
/**
* Returns the profiles available in the game directory.
*
* @returns {Profile[]} The available profiles.
*/
getProfiles() {
const profileDirectoriesPaths = this.getProfileDirectoriesPaths();
return profileDirectoriesPaths.map(profileDirectoryPath =>
Profile.load(profileDirectoryPath, this.towers),
);
}
/**
* Creates a new profile.
*
* @returns {Profile} The created profile.
*/
async createProfile() {
const warriorNameSuggestions = getWarriorNameSuggestions();
const warriorName = await requestInput(
'Enter a name for your warrior:',
warriorNameSuggestions,
);
if (!warriorName) {
throw new GameError(
'Your warrior must have a name if you want him or her to become a legend!',
);
}
const towerChoices = this.towers;
const tower = await requestChoice('Choose a tower:', towerChoices);
const profileDirectoryPath = path.join(
this.gameDirectoryPath,
`${warriorName}-${tower.id}`.toLowerCase().replace(/[^a-z0-9]+/g, '-'),
);
const profile = new Profile(warriorName, tower, profileDirectoryPath);
if (this.isExistingProfile(profile)) {
printWarningLine(
`There's already a warrior named ${warriorName} climbing the ${tower} tower.`,
);
const replaceExisting = await requestConfirmation(
'Do you want to replace your existing profile for this tower?',
);
if (!replaceExisting) {
throw new GameError('Unable to continue without a profile.');
}
printLine('Replacing existing profile...');
} else {
profile.makeProfileDirectory();
}
return profile;
}
/**
* Checks if the given profile exists in the game directory.
*
* @param {Profile} profile A profile to check existance for.
*
* @returns {boolean} Whether the profile exists or not..
*/
isExistingProfile(profile) {
const profileDirectoriesPaths = this.getProfileDirectoriesPaths();
return profileDirectoriesPaths.some(
profileDirectoryPath => profileDirectoryPath === profile.directoryPath,
);
}
/**
* Returns the paths to the profiles available in the game directory.
*
* @returns {string[]} The paths to the available profiles.
*/
getProfileDirectoriesPaths() {
this.ensureGameDirectory();
const profileDirectoryPattern = path.join(this.gameDirectoryPath, '*');
return globby.sync(profileDirectoryPattern, { onlyDirectories: true });
}
/**
* Ensures the game directory exists.
*/
ensureGameDirectory() {
try {
if (!fs.statSync(this.gameDirectoryPath).isDirectory()) {
throw new GameError(
'A file named warriorjs exists at this location. Please change the directory under which you are running warriorjs.',
);
}
} catch (err) {
if (err.code !== 'ENOENT') {
throw err;
}
fs.mkdirSync(this.gameDirectoryPath);
}
}
/**
* Plays through epic mode.
*/
async playEpicMode() {
this.delay /= 2;
if (this.practiceLevel) {
const hasPracticeLevel = this.profile.tower.hasLevel(this.practiceLevel);
if (!hasPracticeLevel) {
throw new GameError(
'Unable to practice non-existent level, try another.',
);
}
await this.playLevel(this.practiceLevel);
} else {
let levelNumber = 0;
let playing = true;
while (playing) {
levelNumber += 1;
playing = await this.playLevel(levelNumber); // eslint-disable-line no-await-in-loop
}
this.profile.updateEpicScore();
}
}
/**
* Plays through normal mode.
*/
async playNormalMode() {
if (this.practiceLevel) {
throw new GameError(
'Unable to practice level while not in epic mode, remove -l option.',
);
}
if (this.profile.levelNumber === 0) {
this.prepareNextLevel();
printSuccessLine(
`First level has been generated. See ${this.profile.getReadmeFilePath()} for instructions.`,
);
} else {
await this.playLevel(this.profile.levelNumber);
}
}
/**
* Plays the level with the given number.
*
* @param {number} levelNumber The number of the level to play.
*
* @returns {boolean} Whether playing can continue or not (for epic mode),
*/
async playLevel(levelNumber) {
const levelConfig = getLevelConfig(levelNumber, this.profile);
const level = getLevel(levelConfig);
printLevel(level);
const playerCode = this.profile.readPlayerCode();
const { events, passed, score } = runLevel(levelConfig, playerCode);
if (!this.silencePlay) {
await printPlay(levelNumber, events, this.delay);
}
printSeparator();
if (!passed) {
printFailureLine(
`Sorry, you failed level ${levelNumber}. Change your script and try again.`,
);
if (levelConfig.clue && !this.profile.isShowingClue()) {
const showClue =
this.assumeYes ||
(await requestConfirmation(
'Would you like to read the additional clues for this level?',
));
if (showClue) {
this.profile.requestClue();
this.generateProfileFiles();
printSuccessLine(
`See ${this.profile.getReadmeFilePath()} for the clues.`,
);
}
}
return false;
}
const hasNextLevel = this.profile.tower.hasLevel(levelNumber + 1);
if (hasNextLevel) {
printSuccessLine('Success! You have found the stairs.');
} else {
printSuccessLine(
'CONGRATULATIONS! You have climbed to the top of the tower.',
);
}
const { aceScore } = levelConfig;
printLevelReport(this.profile, score, aceScore);
const { warriorScore, timeBonus, clearBonus } = score;
const totalScore = warriorScore + timeBonus + clearBonus;
this.profile.tallyPoints(levelNumber, totalScore, aceScore);
if (this.profile.isEpic()) {
if (!hasNextLevel && !this.practiceLevel) {
printTowerReport(this.profile);
}
} else {
await this.requestNextLevel();
}
return hasNextLevel;
}
/**
* Gives the player the option to continue on to the next level.
*
* If the last level has already being reached, the player can choose to
* continue on to epic mode.
*/
async requestNextLevel() {
if (this.profile.tower.hasLevel(this.profile.levelNumber + 1)) {
const continueToNextLevel =
this.assumeYes ||
(await requestConfirmation(
'Would you like to continue on to the next level?',
true,
));
if (continueToNextLevel) {
this.prepareNextLevel();
printSuccessLine(
`See ${this.profile.getReadmeFilePath()} for updated instructions.`,
);
} else {
printLine(
'Staying on current level. Try to earn more points next time.',
);
}
} else {
const continueToEpicMode =
this.assumeYes ||
(await requestConfirmation(
'Would you like to continue on to epic mode?',
true,
));
if (continueToEpicMode) {
this.prepareEpicMode();
printSuccessLine('Run warriorjs again to play epic mode.');
}
}
}
/**
* Prepares the next level.
*/
prepareNextLevel() {
this.profile.goToNextLevel();
this.generateProfileFiles();
}
/**
* Generates the profile files.
*/
generateProfileFiles() {
const levelConfig = getLevelConfig(this.profile.levelNumber, this.profile);
const level = getLevel(levelConfig);
new ProfileGenerator(this.profile, level).generate();
}
/**
* Prepares the epic mode.
*/
prepareEpicMode() {
this.profile.enableEpicMode();
}
}
export default Game;