Skip to content

Commit e538bf7

Browse files
author
Picoseconds
committed
fix: use stable sorting algorithm for leaderboard
1 parent a4679e4 commit e538bf7

File tree

2 files changed

+37
-3
lines changed

2 files changed

+37
-3
lines changed

src/moomoo/Game.ts

+6-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import WebSocket from "ws";
33
import Client from "./Client";
44
import Player from "./Player";
55
import * as lowDb from 'lowdb';
6-
import { randomPos, chunk } from "./util";
6+
import { randomPos, chunk, stableSort } from "./util";
77
import msgpack from "msgpack-lite";
88
import GameState from "./GameState";
99
import * as Physics from "./Physics";
@@ -313,7 +313,11 @@ export default class Game {
313313

314314
let leaderboardUpdate: (string | number)[] = [];
315315

316-
for (let player of this.state.players.sort((a, b) => a.points - b.points).reverse().slice(0, 10)) {
316+
for (let player of stableSort(this.state.players, (a, b) => {
317+
if (a.points > b.points) return -1;
318+
if (a.points < b.points) return 1;
319+
return 0;
320+
}).reverse().slice(0, 10)) {
317321
leaderboardUpdate = leaderboardUpdate.concat([player.id, player.name, player.points]);
318322
}
319323

src/moomoo/util.ts

+31-1
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,34 @@ function chunk<T>(arr: T[], len: number) {
3333
return chunks;
3434
}
3535

36-
export { SkinColor, eucDistance, randomPos, chunk };
36+
interface Comparator<T> {
37+
(a: T, b: T): number
38+
}
39+
40+
interface Array<T> {
41+
stableSort(cmp?: Comparator<T>): Array<T>;
42+
}
43+
44+
let defaultCmp: Comparator<any> = (a, b) => {
45+
if (a < b) return -1;
46+
if (a > b) return 1;
47+
return 0;
48+
}
49+
50+
function stableSort<T>(array: T[], cmp: Comparator<T> = defaultCmp): T[] {
51+
let stabilized = array.map((el, index) => <[T, number]>[el, index]);
52+
let stableCmp: Comparator<[T, number]> = (a, b) => {
53+
let order = cmp(a[0], b[0]);
54+
if (order != 0) return order;
55+
return a[1] - b[1];
56+
}
57+
58+
stabilized.sort(stableCmp);
59+
for (let i = 0; i < array.length; i++) {
60+
array[i] = stabilized[i][0];
61+
}
62+
63+
return array;
64+
}
65+
66+
export { SkinColor, eucDistance, randomPos, chunk, stableSort };

0 commit comments

Comments
 (0)