views:

309

answers:

2

I'm making a blackjack sim and I want to deal the cards how it would be in a casino,

i.e. all players get dealt a card, dealer gets one face down, players get another card, dealer gets one face up

BUT LOOK I VIOLATED DRY :( How to redo??

void BlackJack::newHand()
{
    resetHands();

    for (unsigned int i = 0; i < players.size(); i++)
        players[i]->addCard(deck->nextCard());

    Card* c = deck->nextCard();
    c->setVisible(false); // dealer gets a face down card
    dealer->addCard(c);

    for (unsigned int i = 0; i < players.size(); i++)
        players[i]->addCard(deck->nextCard());

    dealer->addCard(deck->nextCard());
}
+12  A: 

Move the repeated code into another function:

void BlackJack::addDealerCard(bool visible) {
    Card* c = deck->nextCard();
    c->setVisible(visible); 
    dealer->addCard(c);
}

void BlackJack::addCards() {
     for (unsigned int i = 0; i < players.size(); i++)
        players[i]->addCard(deck->nextCard());
}

void BlackJack::newHand() {
    resetHands();

    addCards();    
    addDealerCard(false);

    addCards();    
    addDealerCard(true);
}
Georg Fritzsche
+1  A: 
    void BlackJack::newHand()
    {
        resetHands();

        dealToPlayers();

        Card* c = deck->nextCard();
        c->setVisible(false); // dealer gets a face down card
        dealer->addCard(c);

        dealToPlayers();

        dealer->addCard(deck->nextCard());
    }

    void BlackJack::dealToPlayers()
    {
         for (unsigned int i = 0; i < players.size(); i++)
            players[i]->addCard(deck->nextCard());
    }
dkackman