Skip to content

Commit

Permalink
engine: improved card drawing logic.
Browse files Browse the repository at this point in the history
this commit handles the drawing logic from an empty cardDeck.
- It reshuffles the thrown cards into the card deck when the card deck is empty and a player needs to draw a card.
- Also added relevant unit test, in engine.test.ts, to verify this function (drawCardFromDeck) works correctly.
  • Loading branch information
sethdivyansh committed Jun 1, 2024
1 parent f05595c commit be3882e
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
20 changes: 20 additions & 0 deletions backend/tests/engine.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { GameEngine } from '../uno-game-engine/engine';

describe('testing drawCardFromDeck()', () => {
test('draws a card when deck is empty but thrownCards is not', () => {
const game = new GameEngine();
game.addPlayer({ id: '1', cards: [] });
game.cardDeck = [];
game.thrownCards = [
{
type: 'number',
color: 'yellow',
value: '1',
id: 'card-number-yellow-1-1',
},
];
const player = game.players[0];
game.drawCardFromDeck(player);
expect(player.cards.length).toBe(1);
});
});
18 changes: 13 additions & 5 deletions backend/uno-game-engine/engine.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getShuffledCardDeck } from './deck';
import { getShuffledCardDeck, shuffle } from './deck';
import { handleEvent } from './gameEvents';

const NUM_CARDS_PER_PLAYER = 7;
Expand Down Expand Up @@ -48,10 +48,18 @@ 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) {
this.cardDeck = [...this.thrownCards];
this.thrownCards = [];
shuffle(this.cardDeck);
}
const currentPlayer = this.players.find(
(p: Player) => p.id === player.id
);
if (currentPlayer && this.cardDeck) {
const card = this.cardDeck.pop();
if (card) currentPlayer.cards.push(card);
}
}
dispatchEvent(event: GameEvent) {
// handle different types of events based on event.type
Expand Down

0 comments on commit be3882e

Please sign in to comment.