我正在用C ++制作一个卡片游戏,它有一个Player
抽象类,可以被其他类扩展。我需要创建一个指向这些派生类的指针数组。这有效,但还有更好的方法吗?
class Player{
public:
Player();
Player(const Player&);
Player & operator=(const Player &);
virtual void sort() = 0;
virtual Card play(Pile*) = 0;
void confirmPlay();
void giveHand(Hand&);
void giveCard(Card);
bool hasCards();
void won();
void resetWins();
int getWins();
virtual ~Player();
protected:
int cardsLeft;
Hand hand;
int cardPlayed;
int wins;
private:
};
class DumbPlayer : public Player
{
public:
DumbPlayer();
Card play(Pile*);
void sort();
virtual ~DumbPlayer();
DumbPlayer & operator=(const DumbPlayer &);
DumbPlayer(const DumbPlayer&);
protected:
private:
};
class Game{
public:
Game(int, Player**&);
void playX(int);
void playOne();
virtual ~Game();
protected:
private:
bool done();
Game & operator=(const Game &);
Game(const Game&);
Pile * piles;
Deck deck;
int playerCount;
Player ** players;
};
//implementation not shown to save space, tell me if you would like to see anything.
//I think that all of the other class/function names should be good enough to not show.
Game::Game(const int pplayerCount, Player**& pplayers) :
piles(new Pile[4]),
playerCount(pplayerCount),
deck(),
players(new Player*[playerCount]){
for(int i = 0; i < 4; i++){
piles[i].setSuit(i);
}
for(int i = 0; i < playerCount; i++){
players[i] = pplayers[i];
}
}
void Game::playOne(){
deck.shuffle(); //shuffle deck
for(int i = 0; i < 4; i++){
piles[i].reset(); //reset piles
}
Hand hands[playerCount]; //create hands
Hand leftovers;
deck.dealAll(playerCount, hands, leftovers); //deal the deck
int cardsLeftover = leftovers.getSize(); //there are leftover cards,
//52/3 has a remainder
for(int playerIdx = 0; playerIdx < playerCount; playerIdx++){
(*players[playerIdx]).giveHand(hands[playerIdx]); //this is what
//i am unsure about.
(*players[playerIdx]).sort();
}
int winner = -1;
while(!done()){
for(int playerIdx = 0; playerIdx < playerCount; playerIdx++){
Card play = (*players[playerIdx]).play(piles);
if(piles[play.getSuit()].canPut(play)){
(*players[playerIdx]).confirmPlay();
piles[play.getSuit()].put(play);
if(!(*players[playerIdx]).hasCards()){
winner = playerIdx;
break;
}
} else {
if(cardsLeftover > 0){
(*players[playerIdx]).giveCard(leftovers.popCard(--cardsLeftover));
}
}
}
if(winner != -1){
(*players[winner]).won();
break;
}
}
}
我知道这是一大堆代码(对于这个网站)...我不确定游戏构造函数/类和包括(*players[i]).x()
答案 0 :(得分:4)
如今,拼写指针数组为:
std::vector<boost::shared_ptr<Player> > players;
这将充满Resource Acquisition Is Initialization (RAII) idiom以确保正确调用析构函数并在异常和无法预料的代码路径中回收内存。
答案 1 :(得分:1)
使用std :: vector,list,map等。