Skip to content

Commit 1bf5e25

Browse files
committed
Add DH_cut_deck() (deck cutting function)
1 parent 5c63752 commit 1bf5e25

2 files changed

Lines changed: 38 additions & 0 deletions

File tree

deckhandler.c

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
#include <stdbool.h>
3333
#include <stdio.h>
3434
#include <stdlib.h>
35+
#include <string.h>
3536
#include <time.h>
3637

3738
#include "deckhandler.h"
@@ -123,6 +124,25 @@ void DH_shuffle_deck(DH_Deck *deck) {
123124
deck->top_card = 0;
124125
}
125126

127+
void DH_cut_deck(DH_Deck *deck, const int cut_point) {
128+
if (cut_point <= 0 || cut_point >= DH_CARDS_IN_DECK)
129+
return; // No cut if point is out of bounds
130+
131+
DH_Card temp[DH_CARDS_IN_DECK];
132+
int i, j = 0;
133+
134+
// Copy bottom half first
135+
for (i = cut_point; i < DH_CARDS_IN_DECK; ++i)
136+
temp[j++] = deck->card[i];
137+
138+
// Then copy top half
139+
for (i = 0; i < cut_point; ++i)
140+
temp[j++] = deck->card[i];
141+
142+
// Copy back to original deck
143+
memcpy(deck->card, temp, sizeof(temp));
144+
}
145+
126146
const char *DH_get_card_face(DH_Card card) { return faces[card.face_val - 1]; }
127147

128148
const char *DH_get_card_suit(DH_Card card) { return suits[card.suit]; }

deckhandler.h

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,24 @@ DH_Card DH_deal_top_card(DH_Deck *deck);
122122
*/
123123
void DH_shuffle_deck(DH_Deck *deck_dh);
124124

125+
/**
126+
* @brief Cuts the deck at the specified index, simulating a real-life card cut.
127+
*
128+
* This function rotates the deck so that the card at `cut_point` becomes the new top card.
129+
* The cards before the cut point are moved to the bottom of the deck. For example, if the
130+
* deck is cut at position 26, the new order will be cards 26 to 51 followed by cards 0 to 25.
131+
*
132+
* @param deck Pointer to the DH_Deck structure to be modified.
133+
* @param cut_point The index at which to cut the deck. Must be between 1 and DH_CARDS_IN_DECK - 1.
134+
* If out of bounds, the function does nothing.
135+
*
136+
* @note This function modifies the deck in-place. Use in conjunction with DH_shuffle_deck()
137+
* to simulate realistic shuffling behavior.
138+
*
139+
* @see DH_shuffle_deck
140+
*/
141+
void DH_cut_deck(DH_Deck *deck, int cut_point);
142+
125143
/**
126144
* @brief Get the string name of a card's face value (e.g., "Ace", "10", "King").
127145
*

0 commit comments

Comments
 (0)