Skip to content

Commit

Permalink
fixed DrawCardFromDeck
Browse files Browse the repository at this point in the history
  • Loading branch information
Abhishek committed Jun 1, 2024
1 parent f05595c commit a013b40
Showing 1 changed file with 26 additions and 5 deletions.
31 changes: 26 additions & 5 deletions backend/uno-game-engine/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ export class GameEngine {
this.lastThrownCard = null;
this.currentColor = 0;
this.direction = 1;

this.status = 'READY';
}
allotCards() {
Expand All @@ -48,10 +47,32 @@ export class GameEngine {
(this.currentPlayerIndex + this.direction) % this.players.length;
}
drawCardFromDeck(player: Player) {
//todo: Handle the case when the deck is empty and we have to move the thrown cards back to the deck
this.players
.find((p: Player) => p.id === player.id)
.cards.push(this.cardDeck.pop());
if (this.cardDeck.length === 0) {
if (this.thrownCards.length === 0) {
throw new Error('No cards left to draw');
}
// Move thrown cards back to the deck
this.cardDeck = this.thrownCards;
this.thrownCards = [];
// Shuffle the deck
this.shuffleDeck(this.cardDeck);
}

// Draw a card for the player
const drawnCard = this.cardDeck.pop();
if (drawnCard) {
this.players.find((p) => p.id === player.id)?.cards.push(drawnCard);
} else {
throw new Error('Failed to draw a card');
}
}

shuffleDeck(deck) {
// Fisher-Yates shuffle
for (let i = deck.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[deck[i], deck[j]] = [deck[j], deck[i]];
}
}
dispatchEvent(event: GameEvent) {
// handle different types of events based on event.type
Expand Down

0 comments on commit a013b40

Please sign in to comment.