Spaces:
Running
Running
File size: 13,259 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 |
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var generator_elimination_exports = {};
__export(generator_elimination_exports, {
Elimination: () => Elimination
});
module.exports = __toCommonJS(generator_elimination_exports);
var import_lib = require("../../lib");
class ElimNode {
constructor(options) {
this.children = null;
this.user = options.user || null;
this.state = options.state || "";
this.result = options.result || "";
this.score = options.score || null;
this.losersBracketNode = options.losersBracketNode || null;
this.losersBracketIndex = options.losersBracketIndex || 0;
this.parent = options.parent || null;
this.fromNode = options.fromNode || null;
}
setChildren(children) {
if (this.children) {
for (const child of this.children)
child.parent = null;
}
if (children) {
for (const child of children)
child.parent = this;
}
this.children = children;
}
traverse(multiCallback) {
const queue = [this];
let node;
while (node = queue.shift()) {
multiCallback(node);
if (node.children)
queue.push(...node.children);
}
}
find(multiCallback) {
const queue = [this];
let node;
while (node = queue.shift()) {
const value = multiCallback(node);
if (value) {
return value;
}
if (node.children)
queue.push(...node.children);
}
return void 0;
}
[Symbol.iterator]() {
const results = [this];
for (const result of results) {
if (result.children)
results.push(...result.children);
}
return results[Symbol.iterator]();
}
toJSON() {
const node = {};
if (!this.children) {
node.team = this.user || (this.losersBracketIndex <= 1 ? `(loser's bracket)` : `(loser's bracket ${this.losersBracketIndex})`);
} else {
node.children = this.children.map((child) => child.toJSON());
node.state = this.state || "unavailable";
if (node.state === "finished") {
node.team = this.user;
node.result = this.result;
node.score = this.score;
}
}
return node;
}
}
const nameMap = [
"",
"Single",
"Double",
"Triple",
"Quadruple",
"Quintuple",
"Sextuple"
// Feel free to add more
];
class Elimination {
constructor(maxSubtrees) {
this.name = "Elimination";
this.isDrawingSupported = false;
this.isBracketFrozen = false;
this.players = [];
maxSubtrees = maxSubtrees || 1;
if (typeof maxSubtrees === "string" && maxSubtrees.toLowerCase() === "infinity") {
maxSubtrees = Infinity;
} else if (typeof maxSubtrees !== "number") {
maxSubtrees = parseInt(maxSubtrees);
}
if (!maxSubtrees || maxSubtrees < 1)
maxSubtrees = 1;
this.maxSubtrees = maxSubtrees;
this.treeRoot = null;
if (nameMap[maxSubtrees]) {
this.name = `${nameMap[maxSubtrees]} ${this.name}`;
} else if (maxSubtrees === Infinity) {
this.name = `N-${this.name}`;
} else {
this.name = `${maxSubtrees}-tuple ${this.name}`;
}
}
getPendingBracketData(players) {
return {
type: "tree",
rootNode: null
};
}
getBracketData() {
return {
type: "tree",
rootNode: this.treeRoot.toJSON()
};
}
freezeBracket(players) {
if (!players.length)
throw new Error(`No players in tournament`);
this.players = players;
this.isBracketFrozen = true;
let tree = null;
for (const user of import_lib.Utils.shuffle(players)) {
if (!tree) {
tree = {
root: new ElimNode({ user }),
currentLayerLeafNodes: [],
nextLayerLeafNodes: []
};
tree.currentLayerLeafNodes.push(tree.root);
continue;
}
const targetNode = tree.currentLayerLeafNodes.shift();
if (!targetNode)
throw new Error(`TypeScript bug: no ! in checkJs`);
const newLeftChild = new ElimNode({ user: targetNode.user });
tree.nextLayerLeafNodes.push(newLeftChild);
const newRightChild = new ElimNode({ user });
tree.nextLayerLeafNodes.push(newRightChild);
targetNode.setChildren([newLeftChild, newRightChild]);
targetNode.user = null;
if (tree.currentLayerLeafNodes.length === 0) {
tree.currentLayerLeafNodes = tree.nextLayerLeafNodes;
tree.nextLayerLeafNodes = [];
}
}
this.maxSubtrees = Math.min(this.maxSubtrees, players.length - 1);
for (let losersBracketIndex = 1; losersBracketIndex < this.maxSubtrees; losersBracketIndex++) {
const matchesByDepth = {};
const queue = [{ node: tree.root, depth: 0 }];
let frame;
while (frame = queue.shift()) {
if (!frame.node.children || frame.node.losersBracketNode)
continue;
if (!matchesByDepth[frame.depth])
matchesByDepth[frame.depth] = [];
matchesByDepth[frame.depth].push(frame.node);
queue.push({ node: frame.node.children[0], depth: frame.depth + 1 });
queue.push({ node: frame.node.children[1], depth: frame.depth + 1 });
}
const newTree = {
root: new ElimNode({ losersBracketIndex, fromNode: matchesByDepth[0][0] }),
currentLayerLeafNodes: [],
nextLayerLeafNodes: []
};
newTree.currentLayerLeafNodes.push(newTree.root);
for (const depth in matchesByDepth) {
if (depth === "0")
continue;
const matchesThisDepth = matchesByDepth[depth];
let n = 0;
for (; n < matchesThisDepth.length - 1; n += 2) {
const oldLeaf = newTree.currentLayerLeafNodes.shift();
if (!oldLeaf)
throw new Error(`TypeScript bug: no ! in checkJs`);
const oldLeafFromNode = oldLeaf.fromNode;
oldLeaf.fromNode = null;
const newBranch = new ElimNode({ losersBracketIndex });
oldLeaf.setChildren([new ElimNode({ losersBracketIndex, fromNode: oldLeafFromNode }), newBranch]);
const newLeftChild = new ElimNode({ losersBracketIndex, fromNode: matchesThisDepth[n] });
newTree.nextLayerLeafNodes.push(newLeftChild);
const newRightChild = new ElimNode({ losersBracketIndex, fromNode: matchesThisDepth[n + 1] });
newTree.nextLayerLeafNodes.push(newRightChild);
newBranch.setChildren([newLeftChild, newRightChild]);
}
if (n < matchesThisDepth.length) {
const oldLeaf = newTree.currentLayerLeafNodes.shift();
const oldLeafFromNode = oldLeaf.fromNode;
oldLeaf.fromNode = null;
const newLeaf = new ElimNode({ fromNode: matchesThisDepth[n] });
newTree.nextLayerLeafNodes.push(newLeaf);
oldLeaf.setChildren([new ElimNode({ fromNode: oldLeafFromNode }), newLeaf]);
}
newTree.currentLayerLeafNodes = newTree.nextLayerLeafNodes;
newTree.nextLayerLeafNodes = [];
}
newTree.root.traverse((node) => {
if (node.fromNode) {
node.fromNode.losersBracketNode = node;
node.fromNode = null;
}
});
const newRoot = new ElimNode({});
newRoot.setChildren([tree.root, newTree.root]);
tree.root = newRoot;
}
tree.root.traverse((node) => {
if (node.children?.[0].user && node.children[1].user) {
node.state = "available";
}
});
this.treeRoot = tree.root;
}
disqualifyUser(user) {
if (!this.isBracketFrozen)
return "BracketNotFrozen";
const found = this.treeRoot.find((node) => {
if (node.state === "available") {
if (!node.children)
throw new Error(`no children`);
if (node.children[0].user === user) {
return {
match: [user, node.children[1].user],
result: "loss",
score: [0, 1]
};
} else if (node.children[1].user === user) {
return {
match: [node.children[0].user, user],
result: "win",
score: [1, 0]
};
}
}
return void 0;
});
if (found) {
const error = this.setMatchResult(found.match, found.result, found.score);
if (error) {
throw new Error(`Unexpected ${error} from setMatchResult([${found.match.join(", ")}], ${found.result})`);
}
}
user.game.setPlayerUser(user, null);
}
getAvailableMatches() {
if (!this.isBracketFrozen)
return "BracketNotFrozen";
const matches = [];
this.treeRoot.traverse((node) => {
if (node.state !== "available")
return;
const p1 = node.children[0].user;
const p2 = node.children[1].user;
if (!p1.isBusy && !p2.isBusy) {
matches.push([p1, p2]);
}
});
return matches;
}
setMatchResult([p1, p2], result, score) {
if (!this.isBracketFrozen)
return "BracketNotFrozen";
if (!["win", "loss"].includes(result))
return "InvalidMatchResult";
if (!this.players.includes(p1) || !this.players.includes(p2))
return "UserNotAdded";
const targetNode = this.treeRoot.find((node) => {
if (node.state === "available" && (node.children[0].user === p1 && node.children[1].user === p2)) {
return node;
}
return void 0;
});
if (!targetNode)
return "InvalidMatch";
if (!targetNode.children)
throw new Error(`invalid available state`);
targetNode.state = "finished";
targetNode.result = result;
targetNode.score = score.slice();
const winner = targetNode.children[result === "win" ? 0 : 1].user;
const loser = targetNode.children[result === "loss" ? 0 : 1].user;
targetNode.user = winner;
if (!winner || !loser)
throw new Error(`invalid available state`);
if (loser.losses === this.maxSubtrees) {
loser.isEliminated = true;
loser.sendRoom(`|tournament|update|{"isJoined":false}`);
loser.game.setPlayerUser(loser, null);
}
if (targetNode.parent) {
const parent = targetNode.parent;
if (loser.losses <= winner.losses && !loser.isDisqualified) {
const newNode = new ElimNode({ state: "available", losersBracketNode: targetNode.losersBracketNode });
newNode.setChildren([targetNode, new ElimNode({ user: loser })]);
parent.setChildren([newNode, parent.children[1]]);
return;
}
const userA = parent.children[0].user;
const userB = parent.children[1].user;
if (userA && userB) {
parent.state = "available";
let error = "";
if (userA.isDisqualified) {
error = this.setMatchResult([userA, userB], "loss", [0, 1]);
} else if (userB.isDisqualified) {
error = this.setMatchResult([userA, userB], "win", [1, 0]);
}
if (error) {
throw new Error(`Unexpected ${error} from setMatchResult([${userA},${userB}], ...)`);
}
}
} else if (loser.losses < this.maxSubtrees && !loser.isDisqualified) {
const newRoot = new ElimNode({ state: "available" });
newRoot.setChildren([targetNode, new ElimNode({ user: loser })]);
this.treeRoot = newRoot;
}
if (targetNode.losersBracketNode) {
targetNode.losersBracketNode.user = loser;
const userA = targetNode.losersBracketNode.parent.children[0].user;
const userB = targetNode.losersBracketNode.parent.children[1].user;
if (userA && userB) {
targetNode.losersBracketNode.parent.state = "available";
let error = "";
if (userA.isDisqualified) {
error = this.setMatchResult([userA, userB], "loss", [0, 1]);
} else if (userB.isDisqualified) {
error = this.setMatchResult([userA, userB], "win", [1, 0]);
}
if (error) {
throw new Error(`Unexpected ${error} from setMatchResult([${userA}, ${userB}], ...)`);
}
}
}
}
isTournamentEnded() {
return this.treeRoot.state === "finished";
}
getResults() {
if (!this.isTournamentEnded())
return "TournamentNotEnded";
const results = [];
let currentNode = this.treeRoot;
for (let n = 0; n < this.maxSubtrees; ++n) {
results.push([currentNode.user]);
if (!currentNode.children)
break;
currentNode = currentNode.children[currentNode.result === "loss" ? 0 : 1];
if (!currentNode)
break;
}
if (this.players.length - 1 === this.maxSubtrees && currentNode) {
results.push([currentNode.user]);
}
return results;
}
}
//# sourceMappingURL=generator-elimination.js.map
|