diff --git a/backend/tests/engine.test.ts b/backend/tests/engine.test.ts new file mode 100644 index 0000000..c706e3b --- /dev/null +++ b/backend/tests/engine.test.ts @@ -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); + }); +}); diff --git a/backend/uno-game-engine/engine.ts b/backend/uno-game-engine/engine.ts index 17bf2fe..12f19d9 100644 --- a/backend/uno-game-engine/engine.ts +++ b/backend/uno-game-engine/engine.ts @@ -1,4 +1,4 @@ -import { getShuffledCardDeck } from './deck'; +import { getShuffledCardDeck, shuffle } from './deck'; import { handleEvent } from './gameEvents'; const NUM_CARDS_PER_PLAYER = 7; @@ -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