-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand.ts
More file actions
588 lines (533 loc) · 18.6 KB
/
command.ts
File metadata and controls
588 lines (533 loc) · 18.6 KB
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
const commands = new Map<string, Command<boolean>>(),
aliases = new Map<string, string>();
type CommandExecutor = (this: Game, ...args: (string | undefined)[]) => void;
type CommandInfo = {
short: string,
long: string,
signatures: {
args: {
name: string,
optional?: boolean,
type: string[],
rest?: boolean;
}[],
noexcept: boolean;
}[];
};
class Command<Invertible extends boolean = false> {
#name: string;
get name() { return this.#name; }
#executor: CommandExecutor;
run(args: (string | undefined)[] = []) { this.#executor.call(this.#game, ...args); }
#game: Game;
#inverse!: Invertible extends true ? Command<true> : undefined;
get inverse() { return this.#inverse; }
#info: CommandInfo;
get info() { return this.#info; }
static createInvertiblePair(name: string, on: CommandExecutor, off: CommandExecutor, game: Game, infoOn: CommandInfo, infoOff?: CommandInfo) {
const plus = new Command<true>(
`+${name}`,
on,
game,
infoOn
),
minus = new Command<true>(
`-${name}`,
off,
game,
infoOff ?? infoOn
);
plus.#inverse = minus;
minus.#inverse = plus;
}
constructor(name: string, executor: CommandExecutor, game: Game, info: CommandInfo) {
this.#name = name;
this.#executor = executor.bind(game);
this.#game = game;
this.#info = info;
if (this.#info.signatures.length == 0)
console.warn(`No signatures given for command '${this.#name}'`);
else {
this.#info.signatures.forEach((signature, index) => {
const args = signature.args;
if (args.length != 0) {
for (
let i = 0, l = args.length - 2, arg = args[0];
i < l;
i++, arg = args[i]
) {
if (arg.rest) {
arg.rest = false;
console.warn(`Found illegal rest argument in info string of command '${this.#name}' (signature ${index}, argument '${arg.name}', position ${i})`);
}
}
if (new Set(args.map(arg => arg.name)).size != args.length) {
console.error(`Found duplicate argument names in info string of command '${this.#name}' (signature ${index})`);
}
}
});
}
if (commands.has(this.#name)) {
console.warn(`Overwriting command '${this.#name}'`);
}
commands.set(this.#name, this);
}
}
enum MessageType {
Log = "log",
Important = "important",
Warn = "warn",
SevereWarn = "severe_warn",
Error = "error",
FatalError = "fatal_error"
}
interface ConsoleData {
readonly timestamp: number,
readonly type: MessageType,
readonly content: string | {
readonly main: string,
readonly detail: string | string[];
};
}
function setupBuiltIns(game: Game) {
const createMovementCommand = (name: keyof Player["movement"]) => {
Command.createInvertiblePair(
name,
function() {
const player = this.player;
if (!player) return;
player.movement[name] = true;
},
function() {
const player = this.player;
if (!player) return;
player.movement[name] = false;
},
game,
{
short: `Moves the player in the '${name}' direction.`,
long: `Starts moving the player in the '${name}' direction when invoked.`,
signatures: [
{
args: [],
noexcept: true
}
]
},
{
short: `Halts the player's movement in the '${name}' direction.`,
long: `Stops moving the player in the '${name}' direction when invoked.`,
signatures: [
{
args: [],
noexcept: true
}
]
}
);
},
createSlotCommand = (slot: number) => {
new Command(
`slot${slot}`,
function() {
const player = this.player;
if (!player) return;
player.setActiveItemIndex(slot);
},
game,
{
short: `Attempts to switch to the item in slot ${slot}.`,
long: `When invoked, an attempt to swap to slot ${slot} will be made.`,
signatures: [
{
args: [],
noexcept: true
}
]
}
);
};
createMovementCommand("up");
createMovementCommand("left");
createMovementCommand("down");
createMovementCommand("right");
for (let i = 0; i < Inventory.maxSlots; i++)
createSlotCommand(i);
new Command(
"last_item",
function() {
const player = this.player;
if (!player) return;
player.setActiveItemIndex(player.previousItemIndex);
},
game,
{
short: "Attempts to switch to the last item the player deployed.",
long: "When invoked, the player's last active slot will be switched to, if possible.",
signatures: [
{
args: [],
noexcept: true
}
]
}
);
Command.createInvertiblePair(
"attack",
function() {
const player = this.player;
if (!player || player.attacking) return;
player.attacking = true;
player.activeItem?.useItem();
},
function() {
const player = this.player;
if (!player || !player.attacking) return;
player.attacking = false;
},
game,
{
short: "Starts attacking",
long: "When invoked, the player will start trying to attack as if the attack button was held down. Does nothing if the player isn't attacking.",
signatures: [
{
args: [],
noexcept: true
}
]
},
{
short: "Stops attacking",
long: "When invoked, the player will stop trying to attack, as if the attack button was released. Does nothing if the player isn't attacking.",
signatures: [
{
args: [],
noexcept: true
}
]
}
);
new Command(
"toggle_console",
function() {
game.console.toggle();
},
game,
{
short: "Toggles the game's console.",
long: "When invoked, this command will close the console if it is open, and will open the console if it is closed.",
signatures: [
{
args: [],
noexcept: true
}
]
}
);
new Command(
"clear",
function() {
game.console.clear();
},
game,
{
short: "Clears the console",
long: "When invoked, the game console's contents will be erased.",
signatures: [
{
args: [],
noexcept: true
}
]
}
);
new Command(
"echo",
function(...messages) {
game.console.log((messages ?? []).join(" "));
},
game,
{
short: "Echoes whatever is passed to it.",
long: "When invoked with any number of arguments, the arguments will be re-printed to the console in same order they were given.",
signatures: [
{
args: [
{
name: "args",
optional: true,
type: ["string[]"],
rest: true
}
],
noexcept: true
}
]
}
);
/*
Attempt to convert "simple" key names, like "e",
into the correct KeyboardEvent.code name ("KeyE")
*/
function attemptConversionToCode(key: string) {
if (key.length != 1)
return key;
if (key.match(/[a-z]/i))
key = `Key${key.toUpperCase()}`;
if (key.match(/[0-9]/i))
key = `Digit${key}`;
// never happens
return key;
}
new Command(
"bind",
function(key, query) {
if (key === undefined || query === undefined) {
Console.error(`Error: expected 2 arguments, received ${arguments.length}`);
return;
}
key = attemptConversionToCode(key);
(
keybinds.get(key) ?? (() => {
const array: (string | Command)[] = [];
keybinds.set(key, array);
return array;
})()
).push(query);
},
game,
{
short: "Binds an input to an action.",
long: "Given the name of an input (such as a key or mouse button) and a console query, this command establishes a new link between the two.<br>"
+ `For alphanumeric keys, simply giving the ley as-is (e.g. "a", or "1") will do. However, keys with no textual representation, or that represent`
+ `punctuation will have to given by name, such as "Enter" or "Period".<br>`
+ `Remember that if your query contains spaces, you must enclose the whole query in double quotes ("") so that it is properly parsed.`,
signatures: [
{
args: [
{
name: "input",
type: ["string"]
},
{
name: "query",
type: ["string"]
}
],
noexcept: true
}
]
}
);
new Command(
"unbind",
function(key) {
if (key === undefined) {
Console.error(`Error: expected an argument, received none`);
return;
}
key = attemptConversionToCode(key);
keybinds.delete(key);
},
game,
{
short: "Removes all actions from a given input.",
long: "Given the name of an input (refer to the <code>bind</code> command for more information on naming), this command removes all actions bound to it.",
signatures: [
{
args: [
{
name: "input",
type: ["string"]
}
],
noexcept: true
}
]
}
);
new Command(
"unbind_all",
function() {
keybinds.clear();
},
game,
{
short: "Removes all keybinds.",
long: "When invoked, all inputs will have their actions removed, <em>except the key bound to the console, which cannot be unbound.</em>",
signatures: [
{
args: [],
noexcept: true
}
]
}
);
new Command(
"alias",
function(name, query) {
if (name === undefined || query === undefined) {
Console.error(`Error: expected 2 arguments, received ${arguments.length}`);
return;
}
if (commands.has(name)) {
Console.error(`Error: cannot override built-in command '${name}'`);
return;
}
aliases.set(name, query);
},
game,
{
short: "Creates a shorthand for a console query.",
long: "This command's first argument is the alias' name, and its second is the query; an <em>alias</em> is created, which can be called like any "
+ "other command. When the alias is called, the query said alias is bound to will be executed, as if it had been entered into the console manually.<br>"
+ `If the query contains spaces, remember to wrap the whole thing in double quotes ("") so it can be parsed correctly. An alias' name cannot match that `
+ "of a built-in command. However, if it matches an existing alias, said existing alias will be replaced by the new one.",
signatures: [
{
args: [
{
name: "alias_name",
type: ["string"]
},
{
name: "query",
type: ["string"]
}
],
noexcept: false
}
]
}
);
new Command(
"list_binds",
function(key) {
key = key && attemptConversionToCode(key);
const logBinds = (actions: (Command | string)[], key: string) => {
Console.log({
main: `Actions bound to input '${key}'`,
detail: actions.map(bind => bind instanceof Command ? bind.name : bind).join("\n")
});
};
if (key) {
const actions = keybinds.get(key);
if (actions) {
logBinds(actions, key);
} else {
Console.error(`The input '${key}' hasn't been bound to any action.`);
}
} else {
keybinds.forEach(logBinds);
}
},
game,
{
short: "Lists all the actions bound to a key, or all the keys and their respective actions.",
long: "If this command is invoked without an argument, all keys which have an action to them will be printed, along with "
+ "the actions bound to each respective key. If it is invoked with an input's name, then only the actions bound to that input "
+ "will be shown, if any.",
signatures: [
{
args: [],
noexcept: true
},
{
args: [
{
name: "input_name",
type: ["string"]
}
],
noexcept: false
}
]
}
);
new Command(
"list_alias",
function(name) {
if (name === undefined) {
Console.error(`Error: expected an argument, received none`);
return;
}
const alias = aliases.get(name);
if (alias) {
Console.log(`Alias '${name}' is defined as '${alias}'`);
} else {
Console.error(`No alias named '${name}' exists`);
}
},
game,
{
short: "Gives the definition of an alias.",
long: "When given the name of an alias, if that alias exists, this command will print the query associated with it.",
signatures: [
{
args: [
{
name: "alias_name",
type: ["string"]
}
],
noexcept: false
}
]
}
);
new Command(
"help",
function(name) {
if (name === undefined) {
Console.log({ main: "List of commands", detail: [...commands.keys()] });
Console.log({ main: "List of aliases", detail: [...aliases.keys()] });
} else {
const command = commands.get(name);
if (!command) {
Console.error(`Cannot find command named '${name}'`);
return;
}
const info = command.info;
Console.log({
main: info.short,
detail: [
info.long,
...info.signatures.map(
signature => {
const noexcept = signature.noexcept ? `<span class="command-desc-noexcept">noexcept</span> ` : "",
commandName = `<span class="command-desc-cmd-name">${command.name}</span>`,
args = signature.args.length
? " " + signature.args.map(
arg => `<em>${arg.optional ? "..." : ""}${arg.name}${arg.optional ? "?" : ""}: ${arg.type.map(type => `<span class="command-desc-arg-type">${type}</span>`).join(" | ")}</em>`
).join(", ")
: "";
return `<code>${noexcept + commandName + args}</code>`;
}
)
]
});
}
},
game,
{
short: "Displays help about a certain command, or a list of commands and aliases.",
long: "If given the name of a command, this command logs that command's help info. If not given an argument, this command "
+ "logs a list of all defined commands and aliases. Passing the name of an alias to this command results in an error.",
signatures: [
{
args: [],
noexcept: true
},
{
args: [
{
name: "command_name",
type: ["string"]
}
],
noexcept: false
}
]
}
);
}