aboutsummaryrefslogtreecommitdiffstats
path: root/ee1301/wk6/lab5/strap012_lab5_w_1.cpp
blob: d3684fbedfeefe4477d460d34634410db5a674e2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream>
#include <string>
#include <time.h> //MinGW does not compile without this included when time is involved.

class DeckOfCards {
private:
  int index=0, deck[53];     //deck is size 53 as a hack designed to prevent segfaults.
public:
  DeckOfCards();
  void shuffle();
  int dealCard();
};

void showHand(int hand[], const int size);
int main() {
  srand(time(NULL));
  const int size=4;   //Size can be changed for larger hands
  DeckOfCards deck;
  int hand[size];
  for (int i=0; i<26; i++) {
    for (int j=0; j<size; j++) {
      hand[j]=deck.dealCard();
    }
    showHand(hand, size);
  }
}

//Prints out hand shuffled from before
void showHand(int hand[], const int size) {
  for (int i=0; i<size; i++) {
  //Switch case needed for showing face cards and aces
    switch(hand[i]%13) {
        case 0: std::cout << 'A';
        break;
        case 10: std::cout << 'J';
        break;
        case 11: std::cout << 'Q';
        break;
        case 12: std::cout << 'K';
        break;
        default: std::cout << hand[i]%13+1;
      }
    std::cout << " ";
  }
  std::cout << std::endl;
}

//Deck initialized with 1-52 and shuffled
DeckOfCards::DeckOfCards() {
  for(int i=0; i<52; i++) {
    deck[i]=i+1;
  }
  shuffle();
}

//Implementation of Knuth Shuffle
void DeckOfCards::shuffle() {
  int j=0, temp=0;
  for (int i=50; i>1; i--) {
    j = rand() % 50 + 1;
    if (j < i) {
      temp=deck[i]; deck[i]=deck[j]; deck[j]=temp;
    }
  }
}

//Function to deal the card when asked by grabbing from the deck and shuffling if such card does not exist.
int DeckOfCards::dealCard() {
  index++;
  if (index>=52) {
    index=0;
    shuffle();
  }
  return deck[index];
}