jeudi 12 mars 2020

How I can return an instance of a class using the Builder pattern in C++?

I'm trying to create a simple card game. The aim is to have a firmer grasp with C++ (I have experience just with Java up to now). In particular I'm struggling fully understanding the pointers, despite I've read and watched countless materials all over the web.

#include "../header_files/Card.h"

class Card {
public:
    void setCardName(const string& name){
        card_name = name;
    }
    void setCardPower(const int& pow){
        card_power = pow;
    }
    void setLuck(const int& luck){
        card_luck = luck;
    }

    void printCardDetails() {
        std::cout << "\nCard: " << card_name
                << "Luck:  "<< card_luck <<
                "Power: " << card_power <<"\n" << std::endl;
    }

private:
    string card_name;
    int card_power;
    int card_luck;
};

class CardBuilder{
public: virtual ~CardBuilder() {};

    Card* getCard(){
        return card.release();
    }
    void createNewCard(){
        card = make_unique<Card>();
    }

    virtual void setCardName() = 0;
    virtual void setCardPower() = 0;
    virtual void setCardLuck() = 0;

protected:
    unique_ptr<Card> card;
};


class CardType1Builder : public CardBuilder {
public:
    virtual ~CardType1Builder() {};

    virtual void setCardName(){
        card->setCardName("Card Type 1");
    }
    virtual void setCardPower(){
        card->setCardPower(1+ (rand() %10));
    }
    virtual void setCardLuck(){
        card->setLuck(1+ (rand() %5));
    }
};

class CardType2Builder : public CardBuilder {
public:
    virtual ~CardType2Builder() {};

    virtual void setCardName(){
        card->setCardName("Card Type 2");  //36
    }
    virtual void setCardPower(){
        card->setCardPower(1+ (rand() %10));
    }
    virtual void setCardLuck(){
        card->setLuck(1+ (rand() %5));
    }
};

class CardGenerator {
public:
    void printCard() {
        cardBuilder->getCard()->printCardDetails();
    }
    void constructCard(CardBuilder* cb){
        cardBuilder = cb;
        cardBuilder->createNewCard();
        cardBuilder->setCardName();
        cardBuilder->setCardPower();
        cardBuilder->setCardLuck();
    }

private:
    CardBuilder* cardBuilder;
};

Now I'd like to create a Deck class with several instances of the classes built by the CardBuilder. In particular I tried the following:

class Deck{

private:
    CardGenerator cardGenerator;
    CardType1Builder cardType1Builder;
    CardType1Builder cardType2Builder;
    Card card1;
    Card card2;  

public:
void generateCards() {
    card1 = *cardGenerator.constructCard(&cardType1Builder); //trying to dereference the pointer
    cardGenerator.printCard();

    card1 cardGenerator.constructCard(&cardType2Builder);
    cardGenerator.printCard();


}
};

But unfortunately doesn't work, I probably misunderstood the aim of the * operator. Thank you.

Aucun commentaire:

Enregistrer un commentaire