Spaces:
Running
Running
File size: 34,330 Bytes
5c2ed06 |
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 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 |
/**
* Scavengers Games Plugin
* Pokemon Showdown - http://pokemonshowdown.com/
*
* This plugin stores the different possible game modes and twists that take place in scavengers room
*
* @license MIT license
*/
import { ScavengerHunt, type ScavengerHuntPlayer, sanitizeAnswer } from './scavengers';
import { Utils } from '../../lib';
export type TwistEvent = (this: ScavengerHunt, ...args: any[]) => void;
interface Twist {
name: string;
id: string;
isGameMode?: true;
desc?: string;
[eventid: string]: string | number | TwistEvent | boolean | undefined;
}
type GameModeFunction = (this: ScavengerGameTemplate, ...args: any[]) => void;
interface GameMode {
name: string;
id: string;
mod: Twist;
round?: number;
leaderboard?: true;
teamAnnounce?: GameModeFunction;
getPlayerTeam?: GameModeFunction;
advanceTeam?: GameModeFunction;
[k: string]: any;
}
function toSeconds(time: string) {
// hhmmss => ss
const parts = time.split(':').reverse();
return parts.map((value, index) => parseInt(value) * (60 ** index)).reduce((a, b) => a + b);
}
class Leaderboard {
data: { [userid: string]: AnyObject };
constructor() {
this.data = {};
}
addPoints(name: string, aspect: string, points: number, noUpdate?: boolean) {
const userid: string = toID(name);
if (!userid || userid === 'constructor' || !points) return this;
if (!this.data[userid]) this.data[userid] = { name };
if (!this.data[userid][aspect]) this.data[userid][aspect] = 0;
this.data[userid][aspect] += points;
if (!noUpdate) this.data[userid].name = name; // always keep the last used name
return this; // allow chaining
}
visualize(sortBy: string): Promise<({ rank: number } & AnyObject)[]>;
visualize(sortBy: string, userid: string): Promise<({ rank: number } & AnyObject) | undefined>;
visualize(sortBy: string, userid?: string) {
// FIXME: this is not how promises work
// return a promise for async sorting - make this less exploitable
return new Promise((resolve, reject) => {
let lowestScore = Infinity;
let lastPlacement = 1;
const ladder = Utils.sortBy(
Object.entries(this.data).filter(([u, bit]) => sortBy in bit),
([u, bit]) => -bit[sortBy]
).map(([u, bit], i) => {
if (bit[sortBy] !== lowestScore) {
lowestScore = bit[sortBy];
lastPlacement = i + 1;
}
return {
rank: lastPlacement,
...bit,
} as { rank: number } & AnyObject;
}); // identify ties
if (userid) {
const rank = ladder.find(entry => toID(entry.name) === userid);
resolve(rank);
} else {
resolve(ladder);
}
});
}
async htmlLadder(): Promise<string> {
const data = await this.visualize('points');
return `<div class="ladder" style="overflow-y: scroll; max-height: 170px;"><table style="width: 100%"><tr><th>Rank</th><th>Name</th><th>Points</th></tr>${data.map(line =>
`<tr><td>${line.rank}</td><td>${line.name}</td><td>${line.points}</td></tr>`).join('')
}</table></div>`;
}
}
const TWISTS: { [k: string]: Twist } = {
perfectscore: {
name: 'Perfect Score',
id: 'perfectscore',
desc: "Players who finish the hunt without submitting a single wrong answer get a shoutout!",
onLeave(player) {
if (!this.leftGame) this.leftGame = [];
this.leftGame.push(player.id);
},
onSubmitPriority: 1,
onSubmit(player, value) {
const currentQuestion = player.currentQuestion;
if (!player.answers) player.answers = {};
if (!player.answers[currentQuestion]) player.answers[currentQuestion] = [];
if (player.answers[currentQuestion].includes(value)) return;
player.answers[currentQuestion].push(value);
},
onComplete(player, time, blitz) {
const isPerfect = !this.leftGame?.includes(player.id) &&
Object.values(player.answers).every((attempts: any) => attempts.length <= 1);
return { name: player.name, time, blitz, isPerfect };
},
onAfterEndPriority: 1,
onAfterEnd(isReset) {
if (isReset) return;
const perfect = this.completed.filter(entry => entry.isPerfect).map(entry => entry.name);
if (perfect.length) {
this.announce(Utils.html`${Chat.toListString(perfect)} ${perfect.length > 1 ? 'have' : 'has'} completed the hunt without a single wrong answer!`);
}
},
},
bonusround: {
name: 'Bonus Round',
id: 'bonusround',
desc: "Players can choose whether or not they choose to complete the 4th question.",
onAfterLoad() {
if (this.questions.length === 3) {
this.announce('This twist requires at least four questions. Please reset the hunt and make it again.');
this.huntLocked = true;
} else {
this.questions[this.questions.length - 1].hint += ' (You may choose to skip this question using ``/scavenge skip``.)';
}
},
onAnySubmit(player) {
if (this.huntLocked) {
player.sendRoom('The hunt was not set up correctly. Please wait for the host to reset the hunt and create a new one.');
return true;
}
},
onSubmitPriority: 1,
onSubmit(player, value) {
const currentQuestion = player.currentQuestion;
if (value === 'skip' && currentQuestion + 1 === this.questions.length) {
player.sendRoom('You have opted to skip the current question.');
player.skippedQuestion = true;
this.onComplete(player);
return true;
}
},
onComplete(player, time, blitz) {
const noSkip = !player.skippedQuestion;
return { name: player.name, time, blitz, noSkip };
},
onAfterEndPriority: 1,
onAfterEnd(isReset) {
if (isReset) return;
const noSkip = this.completed.filter(entry => entry.noSkip).map(entry => entry.name);
if (noSkip.length) {
this.announce(Utils.html`${Chat.toListString(noSkip)} ${noSkip.length > 1 ? 'have' : 'has'} completed the hunt without skipping the last question!`);
}
},
},
incognito: {
name: 'Incognito',
id: 'incognito',
desc: "Upon answering the last question correctly, the player's finishing time will not be announced in the room! Results will only be known at the end of the hunt.",
onCorrectAnswer(player, value) {
if (player.currentQuestion + 1 >= this.questions.length) {
this.runEvent('PreComplete', player);
player.sendRoom(`Congratulations! You have gotten the correct answer.`);
player.sendRoom(`This is a special style where finishes aren't announced! To see your placement, wait for the hunt to end. Until then, it's your secret that you finished!`);
return false;
}
},
onPreComplete(player) {
const now = Date.now();
const time = Chat.toDurationString(now - this.startTime, { hhmmss: true });
const canBlitz = this.completed.length < 3;
const blitz = now - this.startTime <= 60000 && canBlitz &&
(this.room.settings.scavSettings?.blitzPoints?.[this.gameType] || this.gameType === 'official');
const result = this.runEvent('Complete', player, time, blitz) || { name: player.name, time, blitz };
this.preCompleted = this.preCompleted ? [...this.preCompleted, result] : [result];
player.completed = true;
player.destroy();
},
onEnd() {
this.completed = this.preCompleted || [];
},
},
spamfilter: {
name: 'Spam Filter',
id: 'spamfilter',
desc: 'Every wrong answer adds 30 seconds to your final time!',
onIncorrectAnswer(player: ScavengerHuntPlayer, value: string) {
if (!player.incorrect) player.incorrect = [];
const id = `${player.currentQuestion}-${value}`;
if (player.incorrect.includes(id)) return;
player.incorrect.push(id);
},
onComplete(player, time, blitz) {
const seconds = toSeconds(time);
if (!player.incorrect) return { name: player.name, total: seconds, blitz, time, original_time: time };
const total = seconds + (30 * player.incorrect.length);
const finalTime = Chat.toDurationString(total * 1000, { hhmmss: true });
if (total > 60) blitz = false;
return { name: player.name, total, blitz, time: finalTime, original_time: time };
},
onConfirmCompletion(player, time, blitz, place, result) {
blitz = result.blitz;
time = result.time;
const deductionMessage = player.incorrect?.length ?
Chat.count(player.incorrect, 'incorrect guesses', 'incorrect guess') :
"Perfect!";
return `<em>${Utils.escapeHTML(player.name)}</em> has finished the hunt! (Final Time: ${time} - ${deductionMessage}${(blitz ? " - BLITZ" : "")})`;
},
onEnd() {
Utils.sortBy(this.completed, entry => entry.total);
},
},
blindincognito: {
name: 'Blind Incognito',
id: 'blindincognito',
desc: "Upon completing the last question, neither you nor other players will know if the last question is correct! You may be in for a nasty surprise when the hunt ends!",
onAnySubmit(player, value) {
if (player.precompleted) {
player.sendRoom(`That may or may not be the right answer - if you aren't confident, you can try again!`);
return true;
}
},
onCorrectAnswer(player, value) {
if (player.currentQuestion + 1 >= this.questions.length) {
this.runEvent('PreComplete', player);
player.sendRoom(`That may or may not be the right answer - if you aren't confident, you can try again!`);
return true;
}
},
onIncorrectAnswer(player, value) {
if (player.currentQuestion + 1 >= this.questions.length) {
player.sendRoom(`That may or may not be the right answer - if you aren't confident, you can try again!`);
return false;
}
},
onPreComplete(player) {
const now = Date.now();
const time = Chat.toDurationString(now - this.startTime, { hhmmss: true });
const canBlitz = this.completed.length < 3;
const blitz = now - this.startTime <= 60000 && canBlitz &&
(this.room.settings.scavSettings?.blitzPoints?.[this.gameType] || this.gameType === 'official');
const result = this.runEvent('Complete', player, time, blitz) || { name: player.name, time, blitz };
this.preCompleted = this.preCompleted ? [...this.preCompleted, result] : [result];
player.precompleted = true;
},
onEnd() {
this.completed = this.preCompleted || [];
},
},
timetrial: {
name: 'Time Trial',
id: 'timetrial',
desc: "Time starts when the player starts the hunt!",
onAfterLoad() {
if (this.questions.length === 3) {
this.announce('This twist requires at least four questions. Please reset the hunt and make it again.');
this.huntLocked = true;
}
this.altIps = {};
this.startTimes = {};
},
onJoin(user: User) {
if (!Config.noipchecks) {
const altIp = user.ips.find(ip => this.altIps[ip] && this.altsIps[ip].id !== user.id);
if (altIp) {
user.sendTo(this.room, `You already have started the hunt as ${this.altIps[altIp].name}.`);
return true;
}
}
if (!this.startTimes[user.id]) this.startTimes[user.id] = Date.now();
if (this.addPlayer(user)) {
this.cacheUserIps(user);
delete this.leftHunt[user.id];
user.sendTo(this.room, "You joined the scavenger hunt! Use the command /scavenge to answer.");
this.onSendQuestion(user);
} else {
user.sendTo(this.room, "You have already joined the hunt.");
}
return true;
},
onLeave(player) {
for (const ip of player.joinIps) {
this.altIps[ip] = { id: player.id, name: player.name };
}
},
onAnySubmit(player) {
if (this.huntLocked) {
player.sendRoom('The hunt was not set up correctly. Please wait for the host to reset the hunt and create a new one.');
return true;
}
},
onComplete(player, time, blitz) {
const now = Date.now();
const takenTime = now - this.startTimes[player.id];
const result = {
name: player.name,
id: player.id,
time: Chat.toDurationString(takenTime, { hhmmss: true }),
duration: takenTime,
blitz,
};
this.completed.push(result);
const place = Utils.formatOrder(this.completed.length);
this.announce(
Utils.html`<em>${result.name}</em> is the ${place} player to finish the hunt! (${takenTime}${(blitz ? " - BLITZ" : "")})`
);
Utils.sortBy(this.completed, entry => entry.duration);
player.destroy(); // remove from user.games;
return true;
},
},
scavengersfeud: {
id: 'scavengersfeud',
name: 'Scavengers Feud',
desc: 'After completing the hunt, players will guess what the most common incorrect answer for each question is.',
onAfterLoad() {
this.guesses = {};
this.incorrect = this.questions.map(() => ({}));
this.questions.push({
hint: 'Please enter what you think are the most common incorrect answers to each question. (Enter your guesses in the order of the previous questions, and separate them with a comma)',
answer: ['Any'],
spoilers: [],
});
},
onIncorrectAnswer(player: ScavengerHuntPlayer, value: string) {
const curr = player.currentQuestion;
if (!this.incorrect[curr][value]) this.incorrect[curr][value] = [];
if (this.incorrect[curr][value].includes(player.id)) return;
this.incorrect[curr][value].push(player.id);
},
onSubmitPriority: 1,
onSubmit(player, jumble, value) {
const currentQuestion = player.currentQuestion;
if (currentQuestion + 1 === this.questions.length) {
this.guesses[player.id] = value.split(',').map((part: string) => sanitizeAnswer(part));
this.onComplete(player);
return true;
}
},
onEnd() {
this.questions = this.questions.slice(0, -1); // remove the automatically added last question.
},
onAfterEnd(isReset) {
if (isReset) return;
const buffer = [];
for (const [idx, data] of this.incorrect.entries()) {
// collate the data for each question
let collection = [];
for (const str in data) {
collection.push({ count: data[str].length, value: str });
}
collection = collection.sort((a, b) => b.count - a.count);
const maxValue = collection[0]?.count || 0;
const matches = collection
.filter(pair => pair.count === maxValue)
.map(pair => pair.value);
const matchedPlayers = [];
for (const playerid in this.guesses) {
const guesses = this.guesses[playerid];
if (matches.includes(guesses[idx])) matchedPlayers.push(playerid);
}
// display the data
const matchDisplay = matches.length ? matches.join(', ') : 'No wrong answers!';
const playerDisplay = matches.length ?
matchedPlayers.length ? `- ${matchedPlayers.join(', ')}` : '- No one guessed correctly!' :
'';
buffer.push(`Q${idx + 1}: ${matchDisplay} ${playerDisplay}`);
}
this.announce(`<h3>Most common incorrect answers:</h3>${buffer.join('<br />')}`);
},
},
minesweeper: {
id: 'minesweeper',
name: 'Minesweeper',
desc: 'The huntmaker adds \'mines\' to the hunt using `!(mine)` - players that dodge all mines get extra points, while the huntmaker gets points every time a mine is hit.',
onAfterLoad() {
this.guesses = this.questions.map(() => []);
this.mines = [];
for (const question of this.questions) {
this.mines.push(question.answer.filter(ans => ans.startsWith('!')));
question.answer = question.answer.filter(ans => !ans.startsWith('!'));
}
if ((this.mines as string[][]).some(mineSet => mineSet.length === 0)) {
this.announce('This twist requires at least one mine for each question. Please reset the hunt and make it again.');
this.huntLocked = true;
}
},
onEditQuestion(questionNumber: number, questionAnswer: string, value: string) {
if (questionAnswer === 'question') questionAnswer = 'hint';
if (!['hint', 'answer'].includes(questionAnswer)) return false;
let answer: string[] = [];
if (questionAnswer === 'answer') {
answer = value.split(';').map(p => p.trim());
}
if (!questionNumber || questionNumber < 1 || questionNumber > this.questions.length || (!answer && !value)) {
return false;
}
questionNumber--; // indexOf starts at 0
if (questionAnswer === 'answer') {
// These two lines are the only difference from the original
this.mines[questionNumber] = answer.filter(ans => ans.startsWith('!'));
this.questions[questionNumber].answer = answer.filter(ans => !ans.startsWith('!'));
} else {
this.questions[questionNumber].hint = value;
}
this.announce(`The ${questionAnswer} for question ${questionNumber + 1} has been edited.`);
if (questionAnswer === 'hint') {
for (const p in this.playerTable) {
this.playerTable[p].onNotifyChange(questionNumber);
}
}
return true;
},
onAnySubmit(player) {
if (this.huntLocked) {
player.sendRoom('The hunt was not set up correctly. Please wait for the host to reset the hunt and create a new one.');
return true;
}
},
onIncorrectAnswer(player: ScavengerHuntPlayer, value: string) {
const curr = player.currentQuestion;
if (!this.guesses[curr][player.id]) this.guesses[curr][player.id] = new Set();
this.guesses[curr][player.id].add(sanitizeAnswer(value));
throw new Chat.ErrorMessage("That is not the answer - try again!");
},
onShowEndBoard(endedBy?: User) {
const sliceIndex = this.gameType === 'official' ? 5 : 3;
const hosts = Chat.toListString(this.hosts.map(h => `<em>${Utils.escapeHTML(h.name)}</em>`));
const mines: { mine: string, users: string[] }[][] = [];
for (const mineSet of this.mines as string[][]) {
mines.push(mineSet.map(mine => ({ mine: mine.substr(1), users: [] as string[] })));
}
for (const player of Object.values(this.playerTable)) {
if (!player) continue;
if (player.mines) {
for (const { index, mine } of player.mines) {
mines[index].find(obj => obj.mine === mine)?.users.push(player.name);
}
}
}
for (const mineSet of mines) mineSet.sort();
this.announce(
`The ${this.gameType ? `${this.gameType} ` : ""}scavenger hunt by ${hosts} was ended ${(endedBy ? "by " + Utils.escapeHTML(endedBy.name) : "automatically")}.<br />` +
`${this.completed.slice(0, sliceIndex).map((p, i) => `${Utils.formatOrder(i + 1)} place: <em>${Utils.escapeHTML(p.name)}</em> <span style="color: lightgreen;">[${p.time}]</span>.<br />`).join("")}` +
`${this.completed.length > sliceIndex ? `Consolation Prize: ${this.completed.slice(sliceIndex).map(e => `<em>${Utils.escapeHTML(e.name)}</em> <span style="color: lightgreen;">[${e.time}]</span>`).join(', ')}<br />` : ''}<br />` +
`<details style="cursor: pointer;"><summary>Solution: </summary><br />` +
`${this.questions.map((q, i) => (
`${i + 1}) ${this.formatOutput(q.hint)} <span style="color: lightgreen">[<em>${Utils.escapeHTML(q.answer.join(' / '))}</em>]</span><br/>` +
`<details style="cursor: pointer;"><summary>Mines: </summary>${mines[i].map(({ mine, users }) => Utils.escapeHTML(`${mine}: ${users.join(' / ') || '-'}`)).join('<br />')}</details>`
)).join("<br />")}` +
`</details>`
);
return true;
},
onEnd(isReset) {
if (isReset) return;
for (const [q, guessObj] of this.guesses.entries()) {
const mines: string[] = this.mines[q];
for (const [playerId, guesses] of Object.entries(guessObj)) {
const player = this.playerTable[playerId];
if (!player) continue;
if (!player.mines) player.mines = [];
(player.mines as { index: number, mine: string }[]).push(...mines
.filter(mine => (guesses as Set<string>).has(sanitizeAnswer(mine)))
.map(mine => ({ index: q, mine: mine.substr(1) })));
}
}
},
onAfterEndPriority: 1,
onAfterEnd(isReset) {
if (isReset) return;
const noMines = [];
for (const { name } of this.completed) {
const player = this.playerTable[toID(name)];
if (!player) continue;
if (!player.mines?.length) noMines.push(name);
}
if (noMines.length) {
this.announce(Utils.html`${Chat.toListString(noMines)} ${noMines.length > 1 ? 'have' : 'has'} completed the hunt without hitting a single mine!`);
// Points are awarded manually
}
},
},
};
const MODES: { [k: string]: GameMode | string } = {
ko: 'kogames',
kogames: {
name: 'KO Games',
id: 'kogames',
mod: {
name: 'KO Games',
id: 'KO Games',
isGameMode: true,
onLoad() {
this.allowRenames = false; // don't let people change their name in the middle of the hunt.
},
onJoin(user: User) {
const game = this.room.scavgame!;
if (game.playerlist && !game.playerlist.includes(user.id)) {
user.sendTo(this.room, 'You are not allowed to join this scavenger hunt.');
return true;
}
},
onAfterEnd() {
const game = this.room.scavgame!;
if (!this.completed.length) {
this.announce('No one has completed the hunt - the round has been void.');
return;
}
game.round++;
// elimination
if (!game.playerlist) {
game.playerlist = this.completed.map(entry => toID(entry.name));
this.announce(`Round ${game.round} - ${Chat.toListString(this.completed.map(p => `<em>${p.name}</em>`))} have successfully completed the last hunt and have moved on to the next round!`);
} else {
let eliminated = [];
const completed = this.completed.map(entry => toID(entry.name)) as string[];
if (completed.length === game.playerlist.length) {
eliminated.push(completed.pop()); // eliminate one
game.playerlist = game.playerlist.filter(userid => completed.includes(userid));
} else {
eliminated = game.playerlist.filter(userid => !completed.includes(userid));
for (const username of eliminated) {
const userid = toID(username);
game.playerlist = game.playerlist.filter(pid => pid !== userid);
}
}
this.announce(`Round ${game.round} - ${Chat.toListString(eliminated.map(n => `<em>${n}</em>`))} ${Chat.plural(eliminated, 'have', 'has')} been eliminated! ${Chat.toListString(game.playerlist.map(p => `<em>${this.playerTable[p].name}</em>`))} have successfully completed the last hunt and have moved on to the next round!`);
}
// process end of game
if (game.playerlist.length === 1) {
const winningUser = Users.get(game.playerlist[0]);
const winner = winningUser ? winningUser.name : game.playerlist[0];
this.announce(`Congratulations to the winner - ${winner}!`);
game.destroy();
} else if (!game.playerlist.length) {
this.announce('Everyone has been eliminated! Better luck next time!');
game.destroy();
}
},
},
round: 0,
playerlist: null,
},
scav: 'scavengergames',
scavgames: 'scavengergames',
scavengergames: {
name: 'Scavenger Games',
id: 'scavengergames',
mod: {
name: 'Scavenger Games',
id: 'scavengergames',
isGameMode: true,
onLoad() {
this.allowRenames = false; // don't let people change their name in the middle of the hunt.
this.setTimer(1);
},
onJoin(user) {
const game = this.room.scavgame!;
if (game.playerlist && !game.playerlist.includes(user.id)) {
user.sendTo(this.room, 'You are not allowed to join this scavenger hunt.');
return true;
}
},
onAfterEnd() {
const game = this.room.scavgame!;
if (!this.completed.length) {
this.announce('No one has completed the hunt - the round has been void.');
return;
}
game.round++;
let eliminated: string[] = [];
if (!game.playerlist) {
game.playerlist = this.completed.map(entry => toID(entry.name) as string);
} else {
const completed = this.completed.map(entry => toID(entry.name) as string);
eliminated = game.playerlist.filter(userid => !completed.includes(userid));
for (const username of eliminated) {
const userid = toID(username);
game.playerlist = game.playerlist.filter(pid => pid !== userid);
}
}
this.announce(`Round ${game.round} - ${Chat.toListString(eliminated.map(n => `<em>${n}</em>`))} ${eliminated.length ? `${Chat.plural(eliminated, 'have', 'has')} been eliminated!` : ''} ${Chat.toListString(game.playerlist.map(p => `<em>${this.playerTable[p].name}</em>`))} have successfully completed the last hunt and have moved on to the next round!`);
// process end of game
if (game.playerlist.length === 1) {
const winningUser = Users.get(game.playerlist[0]);
const winner = winningUser ? winningUser.name : game.playerlist[0];
this.announce(`Congratulations to the winner - ${winner}!`);
game.destroy();
} else if (!game.playerlist.length) {
this.announce('Everyone has been eliminated! Better luck next time!');
game.destroy();
}
},
},
round: 0,
playerlist: null,
},
pr: 'pointrally',
pointrally: {
name: 'Point Rally',
id: 'pointrally',
pointDistribution: [50, 40, 32, 25, 20, 15, 10],
mod: {
name: 'Point Rally',
id: 'pointrally',
isGameMode: true,
onLoad() {
const game = this.room.scavgame!;
this.announce(`Round ${++game.round}`);
},
async onAfterEnd() {
const game = this.room.scavgame!;
for (const [i, completed] of this.completed.map(e => e.name).entries()) {
const points = (game.pointDistribution[i] ||
game.pointDistribution[game.pointDistribution.length - 1]);
game.leaderboard.addPoints(completed, 'points', points);
}
// post leaderboard
const room = this.room;
const html = await game.leaderboard.htmlLadder() as string;
room.add(`|raw|${html}`).update();
},
},
round: 0,
leaderboard: true,
},
js: 'jumpstart',
jump: 'jumpstart',
jumpstart: {
name: 'Jump Start',
id: 'jumpstart',
jumpstart: [60, 40, 30, 20, 10],
round: 0,
mod: {
name: 'Jump Start',
id: 'jumpstart',
isGameMode: true,
onLoad() {
const game = this.room.scavgame!;
if (game.round === 0) return;
const maxTime = Math.max(...game.jumpstart);
this.jumpstartTimers = [];
this.answerLock = true;
for (const [i, time] of game.jumpstart.entries()) {
if (!game.completed[i]) break;
this.jumpstartTimers[i] = setTimeout(() => {
const target = game.completed.shift();
if (!target) return;
const staffHost = Users.get(this.staffHostId);
const targetUser = Users.get(target);
if (targetUser) {
if (staffHost) staffHost.sendTo(this.room, `${targetUser.name} has received their first hint early.`);
targetUser.sendTo(
this.room,
`|raw|<strong>The first hint to the next hunt is:</strong> <div style="overflow:auto; max-height: 50vh"> ${this.formatOutput(this.questions[0].hint)}</div>`
);
targetUser.sendTo(
this.room,
`|notify|Early Hint|The first hint to the next hunt is: <div style="overflow:auto; max-height: 50vh"> ${this.formatOutput(this.questions[0].hint)}</div>`
);
}
}, (maxTime - time) * 1000 + 5000);
}
// when the jump starts are all given to eligible players
this.jumpstartTimers[this.jumpstartTimers.length] = setTimeout(() => {
this.answerLock = false;
const message = this.getCreationMessage(true);
this.room.add(message).update();
this.announce('You may start guessing!');
this.startTime = Date.now();
}, 1000 * (maxTime + 5));
},
onJoin(user) {
if (this.answerLock) {
user.sendTo(this.room, `The hunt is not open for guesses yet!`);
return true;
}
},
onViewHunt(user) {
if (this.answerLock && !(this.hosts.some(h => h.id === user.id) || user.id === this.staffHostId)) {
return true;
}
},
onCreateCallback() {
if (this.answerLock) {
return `|raw|<div class="broadcast-blue"><strong>${['official', 'unrated'].includes(this.gameType) ? 'An' : 'A'} ${this.gameType} ` +
`Scavenger Hunt by <em>${Utils.escapeHTML(Chat.toListString(this.hosts.map(h => h.name)))}</em> ` +
`has been started${(this.hosts.some(h => h.id === this.staffHostId) ? '' : ` by <em>${Utils.escapeHTML(this.staffHostName)}</em>`)}.` +
`<br />The first hint is currently being handed out to early finishers.`;
}
},
onEnd(reset) {
if (this.jumpstartTimers) {
for (const timer of this.jumpstartTimers) {
clearTimeout(timer);
}
}
const game = this.room.scavgame!;
if (!reset) {
if (game.round === 0) {
game.completed = this.completed.map(entry => toID(entry.name));
game.round++;
} else {
game.destroy();
}
}
},
},
},
ts: 'teamscavs',
tscav: 'teamscavs',
teamscavengers: 'teamscavs',
teamscavs: {
name: 'Team Scavs',
id: 'teamscavs',
/* {
[team
name: string]: {
name: string[],
players: UserID[],
answers: string[],
question: number,
completed: boolean
}
} */
teams: {},
teamAnnounce(player: ScavengerHuntPlayer | User, message: string) {
const team = this.getPlayerTeam(player);
for (const userid of team.players) {
const user = Users.getExact(userid);
if (!user?.connected) continue; // user is offline
user.sendTo(this.room, `|raw|<div class="infobox">${message}</div>`);
}
},
getPlayerTeam(player: ScavengerHuntPlayer | User) {
const game = this.room.scavgame!;
for (const teamID in game.teams) {
const team = game.teams[teamID];
if (team.players.includes(player.id)) {
return team;
}
}
return null;
},
advanceTeam(answerer: ScavengerHuntPlayer, isFinished?: boolean) {
const hunt = this.room.getGame(ScavengerHunt)!;
const team = this.getPlayerTeam(answerer);
team.question++;
const question = hunt.getQuestion(team.question);
for (const userid of team.players) {
const user = Users.getExact(userid);
if (!user) continue;
user.sendTo(this.room, question);
}
team.answers = [];
},
mod: {
name: 'Team Scavs',
id: 'teamscavs',
isGameMode: true,
onLoad() {
// don't let people change their name in the middle of the hunt.
this.allowRenames = false;
},
onViewHunt(user) {
const game = this.room.scavgame!;
const team = game.getPlayerTeam(user);
const player = this.playerTable[user.id];
if (!player || !team) return;
if (player.currentQuestion !== team.question - 1) player.currentQuestion = team.question - 1;
if (team.completed) player.completed = true;
},
onSendQuestion(player) {
const game = this.room.scavgame!;
const team = game.getPlayerTeam(player);
if (!team) return;
if (player.currentQuestion !== team.question - 1) player.currentQuestion = team.question - 1;
if (team.completed) {
player.completed = true;
player.sendRoom('Your team has already completed the hunt!');
return true;
}
},
onConnect(user) {
const player = this.playerTable[user.id];
if (!player) return;
const game = this.room.scavgame!;
const team = game.getPlayerTeam(player);
if (team) {
if (player.currentQuestion !== team.question - 1) player.currentQuestion = team.question - 1;
if (team.completed) player.completed = true;
}
},
onJoin(user) {
const game = this.room.scavgame!;
const team = game.getPlayerTeam(user);
if (!team) {
user.sendTo(this.room, 'You are not allowed to join this scavenger hunt as you are not on any of the teams.');
return true;
}
},
onAfterLoadPriority: -9999,
onAfterLoad() {
const game = this.room.scavgame!;
if (Object.keys(game.teams).length === 0) {
this.announce('Teams have not been set up yet. Please reset the hunt.');
}
},
// -1 so that blind incog takes precedence of this
onCorrectAnswerPriority: -1,
onCorrectAnswer(player, value) {
const game = this.room.scavgame!;
if (player.currentQuestion + 1 < this.questions.length) {
game.teamAnnounce(
player,
Utils.html`<strong>${player.name}</strong> has gotten the correct answer (${value}) for question #${player.currentQuestion + 1}.`
);
game.advanceTeam(player);
return false;
}
},
onAnySubmit(player, value) {
const game = this.room.scavgame!;
const team = game.getPlayerTeam(player);
if (!team) return true; // handle players who get kicked during the hunt.
if (player.currentQuestion !== team.question - 1) player.currentQuestion = team.question - 1;
if (team.completed) player.completed = true;
if (player.completed) return;
if (team.answers.includes(value)) return;
game.teamAnnounce(player, Utils.html`${player.name} has guessed "${value}".`);
team.answers.push(value);
},
onCompletePriority: 2,
onComplete(player, time, blitz) {
const game = this.room.scavgame!;
const team = game.getPlayerTeam(player);
return { name: team.name, time, blitz };
},
// workaround that gives the answer after verifying that completion should not be hidden
onConfirmCompletion(player, time, blitz) {
const game = this.room.scavgame!;
const team = game.getPlayerTeam(player);
team.completed = true;
team.question++;
game.teamAnnounce(
player,
Utils.html`<strong>${player.name}</strong> has gotten the correct answer for question #${player.currentQuestion}. Your team has completed the hunt!`
);
},
onEnd() {
const game = this.room.scavgame!;
for (const teamID in game.teams) {
const team = game.teams[teamID];
team.answers = [];
team.question = 1;
team.completed = false;
}
},
},
},
};
export class ScavengerGameTemplate {
room: Room;
playerlist: null | string[];
timer: NodeJS.Timeout | null;
[k: string]: any;
constructor(room: Room) {
this.room = room;
this.playerlist = null;
this.timer = null;
}
destroy(force?: boolean) {
if (this.timer) clearTimeout(this.timer);
const game = this.room.getGame(ScavengerHunt);
if (force && game) game.onEnd(false);
this.room.scavgame = null;
}
eliminate(userid: string) {
if (!this.playerlist?.includes(userid)) return false;
this.playerlist = this.playerlist.filter(pid => pid !== userid);
if (this.leaderboard) delete this.leaderboard.data[userid];
return true;
}
announce(msg: string) {
this.room.add(`|raw|<div class="broadcast-blue"><strong>${msg}</strong></div>`).update();
}
}
const LoadGame = function (room: Room, gameid: string) {
let game = MODES[gameid];
if (!game) return false; // invalid id
if (typeof game === 'string') game = MODES[game];
const base = new ScavengerGameTemplate(room);
const scavgame = Object.assign(base, Utils.deepClone(game));
// initialize leaderboard if required
if (scavgame.leaderboard) {
scavgame.leaderboard = new Leaderboard();
}
return scavgame;
};
export const ScavMods = {
LoadGame,
twists: TWISTS,
modes: MODES,
};
|