2023-07-27 05:12:30 -06:00

48 lines
1.0 KiB
TypeScript

export type Card<T> = {
id: string;
} & T
export class Deck<T> {
private cards: Card<T>[];
private discard: Card<T>[];
public hands: Card<T>[][] = []
constructor(cards?: Card<T>[]) {
this.cards = cards || [];
this.discard = [];
}
public shuffle() {
this.cards.sort(Math.random);
}
public reshuffle() {
this.cards = this.cards.concat(this.discard).sort(Math.random);
this.discard = [];
}
public createHand() {
return this.hands.push([]) - 1;
}
public drawToHand(handIndex: number, count = 1, reshuffle = true) {
const hand = this.hands.at(handIndex);
if (!hand) throw 'No hand at index ' + handIndex;
for (let i = 0; i < count; i++) {
if (!this.cards.length && reshuffle) this.reshuffle();
const card = this.cards.pop();
if (!card) break;
hand.push(card);
}
}
public addCard(...cards: Card<T>[]) {
this.cards.push(...cards);
}
public getDeck() {
return [...this.cards];
}
public getDiscard() {
return [...this.discard];
}
}