diff --git a/backend/tests/deck.test.ts b/backend/tests/deck.test.ts index 98e629a..d54e7b3 100644 --- a/backend/tests/deck.test.ts +++ b/backend/tests/deck.test.ts @@ -1,7 +1,28 @@ -import { makeCard } from '../uno-game-engine/deck'; +import { shuffle, makeCard } from '../uno-game-engine/deck'; describe('testing deck.ts', () => { test('makeCard', () => { const card = makeCard('number', 'blue', '3'); expect(card.color).toBe('blue'); }); }); +describe('shuffle function', () => { + test('should change order of elements', () => { + // Create a mock deck + const deck = [ + makeCard('number', 'red', '1'), + makeCard('number', 'blue', '2'), + makeCard('number', 'red', '1'), + makeCard('number', 'yellow', '1'), + ]; + + // Create a copy of the deck for comparison + const originalDeck = [...deck]; + shuffle(deck); + + // Check that the order of elements has changed + const orderChanged = deck.some( + (card, index) => card !== originalDeck[index] + ); + expect(orderChanged).toBe(true); + }); +}); diff --git a/backend/uno-game-engine/deck.ts b/backend/uno-game-engine/deck.ts index a4aacce..8a6c19e 100644 --- a/backend/uno-game-engine/deck.ts +++ b/backend/uno-game-engine/deck.ts @@ -74,7 +74,10 @@ export function makeCard( * This function shuffles the elements of the given array *in place* . The function behaves in a type-agnostic way. * Time complexity: O(n) */ -export function shuffle(deck: Array) { - //todo: Implement a generic shuffling algorithm - [deck[0], deck[1]] = [deck[1], deck[0]]; +export function shuffle(deck: Array) { + // Fisher-Yates shuffle algorithm to shuffle card deck + for (let i = deck.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * i); + [deck[i], deck[j]] = [deck[j], deck[i]]; + } }