I had to program a game of blacjack for class. Everything seems to be working fine, except shuffling the card deck when initializing the game (drawing the first two cards). Everything from then on out seems random.
I'll provide all necessary code. The randomWithLimits-function I am using:
int randomWithLimits(int upperLimit, int lowerLimit)
{
return (std::rand() % (upperLimit - lowerLimit + 1) + lowerLimit);
}
Simple enough, it is seeded in the main, like this:
int main()
{
srand(time(nullptr));
Blackjack bj;
bool play = true;
while (play == true) play = bj.playGame();
return 0;
}
The blackjack function itself is quite long, but here's the part that doesn't work properly (the first round):
bool Blackjack::playGame() {
CardDeck deck = CardDeck();
std::cout << "The dealer shuffles the deck\n";
deck.shuffle();
drawInitialCards();
std::cout << "\nYour hand is currently " << playerHand << ".";
{...}
std::string cont;
std::cout << "\n\n\nDo you wish to play another round? (y/n) ";
std::cin >> cont;
while (cont != "y" && cont != "n") {
std::cout << "\nNot a valid choice, choose again: (y/n) ";
std::cin >> cont;
}
if (cont == "y") return true;
else return false;
}
CardDeck is a class with this function
CardDeck::CardDeck() {
int count = 0;
for (int s = CLUBS; s <= SPADES; s++) {
for (int r = TWO; r <= ACE; r++) {
Card card(static_cast<Suit>(s), static_cast<Rank>(r));
cards.push_back(card);
}
}
currentCardIndex = 0;
}
which creates the deck. currentCardIndex keeps track of how many cards have been drawn, s is an enum-type called Suit and r is an enum-type called Rank. This seems to work fine.
It uses this shuffle function,
void CardDeck::shuffle() {
int count = 0;
while (count < 100) {
int a = randomWithLimits(51, 0);
int b = randomWithLimits(51, 0);
swap(a, b);
count++;
}
}
which uses the randomWithLimits-function from earlier and this swap-function
void CardDeck::swap(int a, int b) {
Card temp = cards[a];
cards[a] = cards[b];
cards[b] = temp;
}
It's not a big issue, but it still bothers me. Whenever I compile and run the function for the first time, the first output is always:
The dealer shuffles the deck
You drew a Two of Clubs.
The dealer drew a card.
You drew a Four of Clubs.
The dealer drew a card.
Your hand is currently 6.
From then every card seems to be random. I've tried messing around with how many times the shuffle-function swaps cards, whether I place the seed in main or the playGame-function etc. but I always get this result. Any help?
Aucun commentaire:
Enregistrer un commentaire