-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
hangman.js
356 lines (309 loc) · 11 KB
/
hangman.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
/*
* Hangman chat plugin
* By bumbadadabum and Zarel. Art by crobat.
*/
'use strict';
const maxMistakes = 6;
class Hangman extends Rooms.RoomGame {
/**
* @param {ChatRoom | GameRoom} room
* @param {User} user
* @param {string} word
* @param {string?} [hint]
*/
constructor(room, user, word, hint = '') {
super(room);
this.gameNumber = ++room.gameNumber;
this.gameid = 'hangman';
this.title = 'Hangman';
this.creator = user.userid;
this.word = word;
this.hint = hint;
this.incorrectGuesses = 0;
/** @type {string[]} */
this.guesses = [];
/** @type {string[]} */
this.letterGuesses = [];
this.lastGuesser = '';
/** @type {string[]} */
this.wordSoFar = [];
for (const letter of word) {
if (/[a-zA-Z]/.test(letter)) {
this.wordSoFar.push('_');
} else {
this.wordSoFar.push(letter);
}
}
}
/**
* @param {string} word
* @param {User} user
*/
guess(word, user) {
if (user.userid === this.creator) return user.sendTo(this.room, "You can't guess in your own hangman game.");
let sanitized = word.replace(/[^A-Za-z ]/g, '');
let normalized = toID(sanitized);
if (normalized.length < 1) return user.sendTo(this.room, "Guess too short.");
if (sanitized.length > 30) return user.sendTo(this.room, "Guess too long.");
for (const guessid of this.guesses) {
if (normalized === toID(guessid)) return user.sendTo(this.room, "Your guess has already been guessed.");
}
if (sanitized.length > 1) {
if (!this.guessWord(sanitized, user.name)) {
user.sendTo(this.room, "Invalid guess");
} else {
this.room.send(`${user.name} guessed "${sanitized}"!`);
}
} else {
if (!this.guessLetter(sanitized, user.name)) {
user.sendTo(this.room, "Invalid guess");
}
}
}
/**
* @param {string} letter
* @param {string} guesser
*/
guessLetter(letter, guesser) {
letter = letter.toUpperCase();
if (this.guesses.includes(letter)) return false;
if (this.word.toUpperCase().includes(letter)) {
for (let i = 0; i < this.word.length; i++) {
if (this.word[i].toUpperCase() === letter) {
this.wordSoFar[i] = this.word[i];
}
}
if (!this.wordSoFar.includes('_')) {
this.incorrectGuesses = -1;
this.guesses.push(letter);
this.letterGuesses.push(`${letter}1`);
this.lastGuesser = guesser;
this.finish();
return true;
}
this.letterGuesses.push(`${letter}1`);
} else {
this.incorrectGuesses++;
this.letterGuesses.push(`${letter}0`);
}
this.guesses.push(letter);
this.lastGuesser = guesser;
this.update();
return true;
}
/**
* @param {string} word
* @param {string} guesser
*/
guessWord(word, guesser) {
let ourWord = toID(this.word);
let guessedWord = toID(word);
if (ourWord === guessedWord) {
for (let [i, letter] of this.wordSoFar.entries()) {
if (letter === '_') {
this.wordSoFar[i] = this.word[i];
}
}
this.incorrectGuesses = -1;
this.guesses.push(word);
this.lastGuesser = guesser;
this.finish();
return true;
} else if (ourWord.length === guessedWord.length) {
this.incorrectGuesses++;
this.guesses.push(word);
this.lastGuesser = guesser;
this.update();
return true;
}
return false;
}
hangingMan() {
return `<img width="120" height="120" src="//${Config.routes.client}/fx/hangman${this.incorrectGuesses === -1 ? 7 : this.incorrectGuesses}.png" />`;
}
generateWindow() {
let result = 0;
if (this.incorrectGuesses === maxMistakes) {
result = 1;
} else if (!this.wordSoFar.includes('_')) {
result = 2;
}
const color = result === 1 ? 'red' : (result === 2 ? 'green' : 'blue');
const message = result === 1 ? 'Too bad! The mon has been hanged.' : (result === 2 ? 'The word has been guessed. Congratulations!' : 'Hangman');
let output = `<div class="broadcast-${color}">`;
output += `<p style="text-align:left;font-weight:bold;font-size:10pt;margin:5px 0 0 15px">${message}</p>`;
output += `<table><tr><td style="text-align:center;">${this.hangingMan()}</td><td style="text-align:center;width:100%;word-wrap:break-word">`;
let wordString = this.wordSoFar.join('');
if (result === 1) {
let word = this.word;
wordString = wordString.replace(/_+/g, (match, offset) =>
`<font color="#7af87a">${word.substr(offset, match.length)}</font>`
);
}
if (this.hint) output += Chat.html`<div>(Hint: ${this.hint})</div>`;
output += `<p style="font-weight:bold;font-size:12pt;letter-spacing:3pt">${wordString}</p>`;
if (this.guesses.length) {
if (this.letterGuesses.length) {
output += 'Letters: ' + this.letterGuesses.map(g =>
`<strong${g[1] === '1' ? '' : ' style="color: #DBA"'}>${Chat.escapeHTML(g[0])}</strong>`
).join(', ');
}
if (result === 2) {
output += Chat.html`<br />Winner: ${this.lastGuesser}`;
} else if (this.guesses[this.guesses.length - 1].length === 1) {
// last guess was a letter
output += Chat.html` <small>– ${this.lastGuesser}</small>`;
} else {
output += Chat.html`<br />Guessed: ${this.guesses[this.guesses.length - 1]} <small>– ${this.lastGuesser}</small>`;
}
}
output += '</td></tr></table></div>';
return output;
}
/**
* @param {User} user
* @param {boolean} [broadcast]
*/
display(user, broadcast = false) {
if (broadcast) {
this.room.add(`|uhtml|hangman${this.gameNumber}|${this.generateWindow()}`);
} else {
user.sendTo(this.room, `|uhtml|hangman${this.gameNumber}|${this.generateWindow()}`);
}
}
update() {
this.room.add(`|uhtmlchange|hangman${this.gameNumber}|${this.generateWindow()}`);
if (this.incorrectGuesses === maxMistakes) {
this.finish();
}
}
end() {
this.room.add(`|uhtmlchange|hangman${this.gameNumber}|<div class="infobox">(The game of hangman was ended.)</div>`);
this.room.add("The game of hangman was ended.");
delete this.room.game;
}
finish() {
this.room.add(`|uhtmlchange|hangman${this.gameNumber}|<div class="infobox">(The game of hangman has ended – scroll down to see the results)</div>`);
this.room.add(`|html|${this.generateWindow()}`);
delete this.room.game;
}
}
/** @type {ChatCommands} */
const commands = {
hangman: {
create: 'new',
new(target, room, user, connection) {
let text = Chat.filter(this, target, user, room, connection);
if (target !== text) return this.errorReply("You are not allowed to use filtered words in hangmans.");
let params = text.split(',');
if (!this.can('minigame', null, room)) return false;
// @ts-ignore
if (room.hangmanDisabled) return this.errorReply("Hangman is disabled for this room.");
if (!this.canTalk()) return;
if (room.game) return this.errorReply(`There is already a game of ${room.game.title} in progress in this room.`);
if (!params) return this.errorReply("No word entered.");
let word = params[0].replace(/[^A-Za-z '-]/g, '');
if (word.replace(/ /g, '').length < 1) return this.errorReply("Enter a valid word");
if (word.length > 30) return this.errorReply("Phrase must be less than 30 characters.");
if (word.split(' ').some(w => w.length > 20)) return this.errorReply("Each word in the phrase must be less than 20 characters.");
if (!/[a-zA-Z]/.test(word)) return this.errorReply("Word must contain at least one letter.");
let hint;
if (params.length > 1) {
hint = params.slice(1).join(',').trim();
if (hint.length > 150) return this.errorReply("Hint too long.");
}
const game = new Hangman(room, user, word, hint);
room.game = game;
game.display(user, true);
this.modlog('HANGMAN');
return this.addModAction(`A game of hangman was started by ${user.name}.`);
},
createhelp: ["/hangman create [word], [hint] - Makes a new hangman game. Requires: % @ # & ~"],
guess(target, room, user) {
if (!target) return this.parse('/help guess');
if (!room.game || room.game.gameid !== 'hangman') return this.errorReply("There is no game of hangman running in this room.");
if (!this.canTalk()) return;
const game = /** @type {Hangman} */ (room.game);
game.guess(target, user);
},
guesshelp: [
`/hangman guess [letter] - Makes a guess for the letter entered.`,
`/hangman guess [word] - Same as a letter, but guesses an entire word.`,
],
stop: 'end',
end(target, room, user) {
if (!this.can('minigame', null, room)) return false;
if (!this.canTalk()) return;
if (!room.game || room.game.gameid !== 'hangman') return this.errorReply("There is no game of hangman running in this room.");
const game = /** @type {Hangman} */ (room.game);
game.end();
this.modlog('ENDHANGMAN');
return this.privateModAction(`(The game of hangman was ended by ${user.name}.)`);
},
endhelp: ["/hangman end - Ends the game of hangman before the man is hanged or word is guessed. Requires: % @ # & ~"],
disable(target, room, user) {
if (!this.can('gamemanagement', null, room)) return;
// @ts-ignore
if (room.hangmanDisabled) {
return this.errorReply("Hangman is already disabled.");
}
// @ts-ignore
room.hangmanDisabled = true;
if (room.chatRoomData) {
// @ts-ignore
room.chatRoomData.hangmanDisabled = true;
Rooms.global.writeChatRoomData();
}
return this.sendReply("Hangman has been disabled for this room.");
},
enable(target, room, user) {
if (!this.can('gamemanagement', null, room)) return;
// @ts-ignore
if (!room.hangmanDisabled) {
return this.errorReply("Hangman is already enabled.");
}
// @ts-ignore
delete room.hangmanDisabled;
if (room.chatRoomData) {
// @ts-ignore
delete room.chatRoomData.hangmanDisabled;
Rooms.global.writeChatRoomData();
}
return this.sendReply("Hangman has been enabled for this room.");
},
display(target, room, user) {
if (!room.game || room.game.title !== 'Hangman') return this.errorReply("There is no game of hangman running in this room.");
if (!this.runBroadcast()) return;
room.update();
const game = /** @type {Hangman} */ (room.game);
game.display(user, this.broadcasting);
},
''(target, room, user) {
return this.parse('/help hangman');
},
},
hangmanhelp: [
`/hangman allows users to play the popular game hangman in PS rooms.`,
`Accepts the following commands:`,
`/hangman create [word], [hint] - Makes a new hangman game. Requires: % @ # & ~`,
`/hangman guess [letter] - Makes a guess for the letter entered.`,
`/hangman guess [word] - Same as a letter, but guesses an entire word.`,
`/hangman display - Displays the game.`,
`/hangman end - Ends the game of hangman before the man is hanged or word is guessed. Requires: % @ # & ~`,
`/hangman [enable/disable] - Enables or disables hangman from being started in a room. Requires: # & ~`,
],
guess(target, room, user) {
if (!room.game) return this.errorReply("There is no game running in this room.");
if (!this.canTalk()) return;
// @ts-ignore
if (!room.game.guess) return this.errorReply("You can't guess anything in this game.");
// @ts-ignore
room.game.guess(target, user);
},
guesshelp: [
`/guess - Shortcut for /hangman guess.`,
`/hangman guess [letter] - Makes a guess for the letter entered.`,
`/hangman guess [word] - Same as a letter, but guesses an entire word.`,
],
};
exports.commands = commands;