shoehive
Version:
WebSocket-based multiplayer game framework for real-time, event-driven gameplay
125 lines (124 loc) • 3.76 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Deck = void 0;
const types_1 = require("./types");
/**
* A deck of [Card](/core/card/types#card)s.
*
* Supports shuffling, drawing cards, and resetting from the discard pile.
*/
class Deck {
constructor(numberOfDecks = 1) {
this.cards = [];
this.discardPile = [];
this.initialize(numberOfDecks);
}
/**
* Initializes the deck.
*
* @param numberOfDecks The number of decks to initialize.
*/
initialize(numberOfDecks) {
this.cards = [];
for (let d = 0; d < numberOfDecks; d++) {
for (const suit of Object.values(types_1.CardSuit)) {
for (const rank of Object.values(types_1.CardRank)) {
let value;
// Assign default card values (can be customized by game-specific logic)
if (rank === types_1.CardRank.ACE) {
value = 11; // Default Ace value, games can handle it differently
}
else if (rank === types_1.CardRank.JACK || rank === types_1.CardRank.QUEEN || rank === types_1.CardRank.KING) {
value = 10;
}
else {
value = parseInt(rank, 10) || undefined;
}
this.cards.push({
suit,
rank,
value,
isVisible: true, // Cards in deck are visible by default
});
}
}
}
}
/**
* Shuffles the deck.
*/
shuffle() {
// Fisher-Yates shuffle algorithm
for (let i = this.cards.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[this.cards[i], this.cards[j]] = [this.cards[j], this.cards[i]];
}
}
/**
* Draws a card from the deck.
*
* @param isVisible Whether the card should be visible.
* @returns The drawn card or null if the deck is empty.
*/
drawCard({ isVisible = true } = {}) {
if (this.cards.length === 0) {
return null;
}
const card = this.cards.pop();
card.isVisible = isVisible;
return card;
}
/**
* Draws multiple cards from the deck.
*
* @param count The number of cards to draw.
* @param isVisible Whether the cards should be visible.
* @returns An array of drawn cards or an empty array if the deck is empty.
*/
drawCards({ count, isVisible = true }) {
const cards = [];
for (let i = 0; i < count; i++) {
const card = this.drawCard({ isVisible });
if (card) {
cards.push(card);
}
else {
break;
}
}
return cards;
}
/**
* Adds a card to the discard pile.
*
* @param card The card to add to the discard pile.
*/
addToDiscard({ card }) {
this.discardPile.push(card);
}
/**
* Resets the deck from the discard pile.
*/
resetFromDiscard() {
this.cards = [...this.cards, ...this.discardPile];
this.discardPile = [];
this.shuffle();
}
/**
* Gets the number of remaining cards in the deck.
*
* @returns The number of remaining cards in the deck.
*/
getRemainingCards() {
return this.cards.length;
}
/**
* Gets the number of discarded cards.
*
* @returns The number of discarded cards.
*/
getDiscardedCards() {
return this.discardPile.length;
}
}
exports.Deck = Deck;