绘制一张卡片,并将其调用

时间:2017-12-02 19:42:24

标签: c++ arrays

我正在创造一个二十一点游戏。我已经设置了卡片组,我现在只需要实现游戏。

所以我有一个名为deck.cpp的文件,其中包含deck数组,以及一个存储该值的卡片文件。在deck.cpp文件中,我有以下可以绘制卡片的功能:

void Deck::draw(int v){
    cout << deck[v].toString();
}

然后,在我实际玩游戏的另一个档案中,我打电话给甲板课,并将其拖垮,这也正常。

#include "Deck.hpp"
#include "PlayingCard.hpp"
#include <string>
using namespace std;


class Blackjack{

    private:
        //Must contain a private member variable of type Deck to use for the game
        Deck a;
        int playerScore;
        int dealerScore;

        bool playersTurn();
        bool dealersTurn();

    public:
        //Must contain a public default constructor that shuffles the deck and initializes the player and dealer scores to 0
        Blackjack();

        void play();
};

现在我无法弄清楚如何将两张卡片打印出来并获得它们的总和:

#include "Blackjack.hpp"
#include "Deck.hpp"
#include <iostream>
#include <iomanip>

using namespace std;
//Defaults the program to run
Blackjack::Blackjack(){
    a.shuffle();
    playerScore = 0;
    dealerScore = 0;
}
void Blackjack::play(){

}

我意识到这可能存在问题,因为当用户决定点击时,我们可能不知道哪个牌在牌组中。我相信我认为绘制功能是错误的。

问题是我无法弄清楚如何从卡座上正确地绘制卡片(减少顶部卡片)。那么我该如何调整userscore。我有一个getValue()函数返回double。

1 个答案:

答案 0 :(得分:0)

甲板中所需的更改

在现实世界中,牌组知道剩下多少张牌以及下一张牌是什么。在你的课堂上它应该是相同的:

class Deck{       
   private:
        PlayingCard deck[52];
        int next_card;         //<=== just one approach 
   public:
        ...
};

当您在现实世界中绘制卡片时,您手中有卡片。因此绘图会返回一些内容:

class Deck{       
        ...
   public:
        Deck();
        void shuffle();
        void printDeck();
        PlayingCard draw();   // <=== return the card
};

该功能将如下所示:

PlayingCard Deck::draw(){
    int v=next_card++; 
    cout << deck[v].toString();
    return deck[v]; 
}

在此实现中,为简单起见,deck不会更改。构建甲板时,next_card应初始化为0.任何时候next_card下面的元素都已绘制,而甲板上剩余的元素是从next_card到51的元素。你应该处理这个案子,如果有人想要画一张牌,尽管牌组中没有牌。

如何继续游戏

绘图更容易,因为现在,游戏可以知道绘制的卡片。这允许您根据PlayCard值更新分数。而且你不再需要跟踪顶牌:

Blackjack::Blackjack(){
    // Deck a;   <====== this should be a protected member of Blackjack class           
    a.shuffle();
    playerScore = 0;
    dealerScore = 0;
}

我不确定玩家只能抽两张牌。所以我建议改变你的游戏玩法。

void Blackjack::play(){
    bool player_want_draw=true, dealer_want_draw=true;
    while (player_want_draw || dealer_want_draw) {
        if (player_want_draw) {
            cout<<"Player draws ";
            PlayCard p = a.draw(); 
            cout<<endl; 
            // then update the score and ask user if he wants to draw more
        }
        if (dealer_want_draw) {
            cout<<"Dealer draws ";
            PlayCard p = a.draw(); 
            cout<<endl; 
            // then update the score and decide if dealer should continue drawing
        }        
    }
    // here you should know who has won
}

你可以通过更新每一轮的得分和一些旗帜来实现二十一点游戏,而不必记住每个玩家的抽牌卡的价值。但是,如果您愿意,您可以像在现实世界中那样实施它,方法是为每个玩家/经销商保留他/她所画的卡片。Blackjack。使用数组,它可能但很麻烦。但是如果你已经了解了矢量,那就去吧。