-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
422 lines (388 loc) · 13.8 KB
/
main.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
let global = {
baseURL: "https://mudnix.dantefalzone.repl.co",
frontendVersion: "0.5.2",
backendVersion: null,
messageEventSource: null,
autoLogoutEventSource: null,
alreadyReadMessages: [],
divider: "================",
user: {
isLoggedIn: false,
username: null,
password: null
},
helpMessages: {
"help": "print a list of all commands",
"clear": "try it and see ;)",
"echo \"<string>\"": "prints <string> to stdout",
"sha256 \"<string>\"": "prints the SHA-256 hash of <string> to stdout",
"new-user": "create a new account",
"login": "log in to an existing user account",
"logout": "log out of your account",
"say \"<message>\"": "broadcasts <message> to everyone in your area",
"goto \"<location>\"": "moves you to <location>",
"map": "lists all the locations adjacent to your current location as clickable links",
"open-chest": "opens a treasure chest if you've found one",
"inventory": "shows you what's in your inventory",
"check-connection": "listen to see if the server is online",
"conn": "alias for `check-connection`",
"whos-here": "tells you who is in your area in-game",
"w": "alias for `whos-here`"
},
activeTreasureChest: null
};
const mudnixAsciiArt = `\
███╗ ███╗██╗ ██╗ ██╗███╗ ██╗██╗██╗ ██╗
████╗ ████║██║ ██║ ██║████╗ ██║╚═╝╚██╗██╔╝
██╔████╔██║██║ ██║ ██████║██╔██╗ ██║██║ ╚███╔╝
██║╚██╔╝██║██║ ██║██╔══██║██║╚██╗██║██║ ██╔██╗
██║ ╚═╝ ██║╚██████╔╝╚██████║██║ ╚████║██║██╔╝ ██╗
╚═╝ ╚═╝ ╚═════╝ ╚═════╝╚═╝ ╚═══╝╚═╝╚═╝ ╚═╝`;
function getCredentials(term, usernamePrompt, passwordPrompt, callback) {
term.read(usernamePrompt).then(function(username) {
global.user.username = username;
}).then(function() {
term.set_mask(true);
term.read(passwordPrompt).then(function(password) {
global.user.password = password;
term.set_mask(false);
}).then(callback);
});
}
/*
to machine-readable representation, e.g.
"public library of Spam Village" => "Spam_Village::public_library"
*/
function toLocationId(locationString) {
return locationString.split(" of ")
.map(substr => substr.replace(" ", "_"))
.reverse()
.join("::");
}
/*
to human-readable representation, e.g.
"Spam_Village::public_library" => "public library of Spam Village"
*/
function toHumanReadable(locationIdString) {
return locationIdString.split("::")
.map(substr => substr.replace("_", " "))
.reverse()
.join(" of ")
}
function checkConnection(term) {
let eventSource = new EventSource(
global.baseURL + "/check-connection",
{ withCredentials: false }
);
eventSource.onmessage = function(event) {
let eventObject = JSON.parse(event.data);
if (eventObject.alive) {
term.echo(`Server is alive. Count: ${eventObject.count}`);
}
}
return eventSource;
}
function pingServer() {
let term = $.terminal.active();
term.echo("Checking connection to server.");
let eventSource = checkConnection(term);
term.read("press Enter to stop ").then(function() {
eventSource.close();
});
}
function help() {
let term = $.terminal.active();
term.echo("List of currently supported commands:");
for (let key of Object.keys(global.helpMessages)) {
term.echo(`${key}: ${global.helpMessages[key]}`);
}
}
function sha256(str) {
let term = $.terminal.active();
term.echo("SHA-256 hash of " + str + ":");
fetch(`${global.baseURL}/hash/sha256?s=${str}`)
.then((response) => response.text())
.then((text) => term.echo(text));
}
function gotoLocation(destLocation) {
let term = $.terminal.active();
fetch(
global.baseURL +
"/game/goto?username=" + global.user.username +
"&password=" + global.user.password +
"&new_location_id=" + toLocationId(destLocation)
).then(response => response.json()).then(function(responseObject) {
if (responseObject["succeeded"]) {
term.echo(responseObject["info"]);
if (responseObject["active_treasure_chest"] !== null) {
global.activeTreasureChest = responseObject["active_treasure_chest"];
term.echo("You have encountered a treasure chest. Run `open-chest` to open it.");
} else if (global.activeTreasureChest !== null) {
global.activeTreasureChest = null;
}
} else {
term.error("Unable to move your character.\nReason: " + responseObject["err"]);
term.error(
"Perhaps you forgot to put the destination in quotation marks?"
);
}
});
}
function login() {
let term = $.terminal.active();
if (global.user.isLoggedIn) {
term.error("You are already logged in.");
} else {
getCredentials(term, "Username: ", "Password: ", function() {
fetch(
`${global.baseURL}/user/login?username=${global.user.username}&password=${global.user.password}`
).then(response => response.json()).then(function(responseObject) {
global.user.isLoggedIn = responseObject["logged_in"];
if (global.user.isLoggedIn) {
term.echo("You have successfully logged in.");
term.echo("Remember to log out before you leave so your character will be safe.");
term.echo(global.divider);
global.messageEventSource = new EventSource(
global.baseURL +
"/game/message-queue?username=" + global.user.username +
"&password=" + global.user.password,
{ withCredentials: false }
);
global.messageEventSource.onmessage = function(event) {
let eventObject = JSON.parse(event.data);
if (eventObject.succeeded) {
for (let message of eventObject.queue) {
if (!global.alreadyReadMessages.some(function(readMessage) {
return JSON.stringify(readMessage) === JSON.stringify(message)
})) {
term.echo(`${message.user}: ${message.text}`);
global.alreadyReadMessages.push(message);
}
}
}
}
global.autoLogoutEventSource = new EventSource(
global.baseURL +
"/user/autologout?username=" + global.user.username +
"&password=" + global.user.password,
{ withCredentials: false }
);
global.autoLogoutEventSource.onmessage = function(event) {
let eventObject = JSON.parse(event.data);
if (eventObject.succeeded && eventObject.info === "logout") {
logout();
term.error("You have been automatically logged out due to inactivity.");
}
};
term.set_prompt(responseObject.username + "> ");
term.echo(responseObject.info);
} else {
term.error("You have not logged in.\nReason: " + responseObject["err"]);
}
});
});
}
}
function logout() {
let term = $.terminal.active();
if (!global.user.isLoggedIn) {
term.error("You must be logged in to log out.");
} else {
fetch(
`${global.baseURL}/user/logout?username=${global.user.username}&password=${global.user.password}`
).then(response => response.json()).then(function(responseObject) {
if (responseObject["logged_out"]) {
global.user.isLoggedIn = false;
global.user.username = null;
global.user.password = null;
global.messageEventSource.close();
global.messageEventSource = null;
global.autoLogoutEventSource.close();
global.autoLogoutEventSource = null;
term.echo("You have successfully logged out.");
term.set_prompt("mudnix> ");
} else {
term.error("You have not logged out.\nReason: " + responseObject["err"]);
}
});
}
}
function newUser() {
let term = $.terminal.active();
getCredentials(term, "Enter your desired username: ", "Enter your desired password: ", function() {
fetch(
`${global.baseURL}/user/new-user?username=${global.user.username}&password=${global.user.password}`,
{ method: "POST" }
).then((response) => response.text()).then((text) => term.echo(text));
});
}
function adminTeleport(destLocation) {
let term = $.terminal.active();
fetch(
global.baseURL +
"/game/tp?username=" + global.user.username +
"&password=" + global.user.password +
"&new_location=" + destLocation
).then(response => response.json()).then(function(responseObject) {
if (responseObject.succeeded) {
term.echo(responseObject.info);
} else {
term.error("Unable to move your character.\nReason: " + responseObject["err"]);
}
});
}
function map() {
let term = $.terminal.active();
fetch(
`${global.baseURL}/game/map?username=${global.user.username}&password=${global.user.password}`
).then(response => response.json()).then(function(responseObject) {
if (responseObject.succeeded) {
term.echo("Locations adjacent to you (click to travel to a location):");
for (let locationId of responseObject.locations) {
let link =
`<a href="javascript:void(0);"
onclick="gotoLocation('${locationId}');"
style="color:#FFFF00">${toHumanReadable(locationId)}</a>`;
term.echo($(link));
}
} else {
term.error("Unable to retrieve the requested data.\nReason: " + responseObject["err"]);
}
});
}
function openChest() {
let term = $.terminal.active();
if (!global.user.isLoggedIn) {
term.error("You are not logged in.");
} else if (global.activeTreasureChest === null) {
term.error("You are not near a treasure chest.");
} else {
term.echo("You open the treasure chest.");
if (global.activeTreasureChest.contents.length === 0) {
term.echo("The chest is empty.");
} else {
term.echo("The chest contains the following items:");
for (let item of global.activeTreasureChest.contents) {
term.echo(item.name);
}
term.echo("You take the items from the chest and add them to your inventory.");
}
fetch(
global.baseURL +
"/game/close-chest?username=" + global.user.username +
"&password=" + global.user.password
).then(response => response.json()).then(function(responseObject) {
term.echo(responseObject.info);
global.activeTreasureChest = null;
});
}
}
function inventory() {
let term = $.terminal.active();
if (!global.user.isLoggedIn) {
term.error("You are not logged in.");
} else {
fetch(
global.baseURL +
"/user/inventory?username=" + global.user.username +
"&password=" + global.user.password
).then(response => response.json()).then(function(responseObject) {
if (responseObject.succeeded) {
responseObject.inventory.forEach(function(item) {
term.echo(global.divider);
term.echo(`Item: ${item.name} (quantity ${item.qty})`);
term.echo(`Rarity: ${item.rarity}`);
term.echo(`Description: ${item.description}`);
});
} else {
term.error("Unable to get inventory.");
term.error("Reason: " + responseObject.err);
}
});
}
}
function say(message) {
let term = $.terminal.active();
fetch(
global.baseURL +
"/game/say?username=" + global.user.username +
"&password=" + global.user.password +
"&message=" + message,
{ method: "POST" }
).then(response => response.text()).then(function(response) {
if (response !== "Ok") {
term.error("Your message was not sent.");
term.error("Error message: " + response);
}
});
}
function whosHere() {
let term = $.terminal.active();
if (!global.user.isLoggedIn) {
term.error("You are not logged in.");
} else {
fetch(
global.baseURL +
"/game/whos-here?username=" + global.user.username +
"&password=" + global.user.password
).then(response => response.json()).then(function(responseObject) {
if (responseObject.succeeded) {
term.echo(`Your location is the ${toHumanReadable(responseObject.active_location)}.`);
let nearbyUsers = responseObject.nearby_users
.filter(user => user !== global.user.username);
if (nearbyUsers.length === 0) {
term.echo("No one else is here.");
} else {
term.echo("Other users that are here:");
nearbyUsers.forEach(user => term.echo(user));
}
} else {
term.error("Unable to complete request. Reason: " + responseObject.err);
}
});
}
}
function setUpTerminal() {
$("body").terminal({
// utility commands
"echo": function(str) { this.echo(str); },
"help": help,
"sha256": sha256,
"check-connection": pingServer,
"conn": pingServer,
// account management commands
"new-user": newUser,
"login": login,
"logout": logout,
// game commands
"tp": adminTeleport,
"goto": gotoLocation,
"map": map,
"open-chest": openChest,
"inventory": inventory,
"say": say,
"whos-here": whosHere,
"w": whosHere
}, {
greetings: `${mudnixAsciiArt}
Client v${global.frontendVersion} backend v${global.backendVersion} (pre-alpha)
${global.divider}
Type "new-user" to create a new account.
Type "login" if you already have an account.
Type "help" for a list of commands.`,
name: "mudnix",
prompt: "mudnix> "
});
}
fetch(`${global.baseURL}/version`)
.then(response => response.text())
.then(function(version) { global.backendVersion = version })
.then(function() { $(setUpTerminal) });
window.onbeforeunload = function() {
if (global.user.isLoggedIn) {
logout();
return "";
} else {
return null;
}
}