Skip to content

Commit 12aacca

Browse files
committed
Ensure each player is listed at least once before repeats; add shuffle utility.
1 parent f53a2b0 commit 12aacca

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed

src/app/store/autopelago-store.ts

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
import type { AutopelagoClientAndData } from '../data/slot-data';
1313
import { targetLocationEvidenceFromJSONSerializable } from '../game/target-location-evidence';
1414
import { makePlayerToken } from '../utils/make-player-token';
15+
import { shuffle } from '../utils/shuffle';
1516
import { toWeighted } from '../utils/weighted-sampler';
1617
import { withCleverTimer } from './with-clever-timer';
1718
import { withGameState } from './with-game-state';
@@ -158,13 +159,17 @@ export const GameStore = signalStore(
158159
return message;
159160
}
160161

162+
// list each player at least once before repeating any.
163+
let currentRandomPlayerBag: Player[] = [];
161164
return message.replaceAll('{RANDOM_PLAYER}', () => {
162-
const idx = Math.floor(Math.random() * randomPlayers.size);
163-
const otherPlayer = randomPlayers.get(idx);
164-
if (!otherPlayer) {
165-
throw new Error('list.size is inconsistent with list.get(i). this is a bug in immutable.js');
165+
if (currentRandomPlayerBag.length === 0) {
166+
currentRandomPlayerBag = shuffle([...randomPlayers]);
166167
}
167-
return otherPlayer.alias;
168+
const player = currentRandomPlayerBag.pop();
169+
if (player === undefined) {
170+
throw new Error('pop should have returned something here. this is a programming error');
171+
}
172+
return player.alias;
168173
});
169174
}
170175
function _wrapMessageTemplate<T extends unknown[]>(f: ((...args: T) => string) | null) {

src/app/utils/shuffle.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// Fisher-Yates shuffle
2+
// https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#JavaScript_implementation
3+
export function shuffle<T>(array: T[]): T[] {
4+
for (let i = array.length - 1; i >= 1; i--) {
5+
const j = Math.floor(Math.random() * (i + 1));
6+
[array[i], array[j]] = [array[j], array[i]];
7+
}
8+
return array;
9+
}

0 commit comments

Comments
 (0)