2017-10-15 148 views
-1

我必須編程一個簡單的二十一點遊戲爲我的介紹C++類和老師希望我們建立甲板的方式讓我感到困惑與我如何編程的Ace自動選擇不管是否爲11或1的值。C++ BlackJack Stuck試圖編程王牌

從閱讀其他可能的解決方案,出現了相互衝突的想法,首先將ace的值設置爲11,如果你破產,則減去10(教授如何選擇),但大多數我看到說,將值設置爲1,如果需要添加10。

下面

是他如何希望我們建立我們的卡和甲板類:

#include <iostream> 
#include <string> 
#include <vector> 
#include <ctime> 

using namespace std; 

class card 
{ 
string rank; 
string suit; 
int value; 

public: 
string get_rank() 
{ 
    return rank; 
} 
string get_suit() 
{ 
    return suit; 
} 
int get_value() 
{ 
    return value; 
} 

//Contstructor 
card(string rk = " ", string st = " ", int val = 0) 
{ 
    rank = rk; 
    suit = st; 
    value = val; 
} 


//print function 
void print() 
{ 
    cout << rank << " of " << suit << endl; 
} 
}; 

class deck 
{ 
card a_deck[52]; 
int top; 

public: 
card deal_card() 
{ 
    return a_deck[top++]; 
} 

//Deck constructor 
deck() 
{ 
    top = 0; 
    string ranks[13] = { "Ace", "King", "Queen", "Jack", "Ten", "Nine", 
"Eight", "Seven", "Six", "Five", "Four", "Three", "Two" }; 
    string suits[4] = { "Spades", "Diamonds", "Hearts", "Clubs" }; 
    int values[13] = { 11,10,10,10,10,9,8,7,6,5,4,3,2 }; 

    for (int i = 0; i < 52; i++) 
     a_deck[i] = card(ranks[i % 13], suits[i % 4], values[i % 13]); 

    srand(static_cast<size_t> (time(nullptr))); 
} 

void shuffle() 
{ 
    for (int i = 0; i < 52; i++) 
    { 
     int j = rand() % 52; 
     card temp = a_deck[i]; 
     a_deck[i] = a_deck[j]; 
     a_deck[j] = temp; 

    } 
} 
}; 

然後,他把我們創造一個我們所建立的手放進載體的播放器類

class player 
{ 
string name; 
vector<card>hand; 
double cash; 
double bet; 

public: 

//Constructor 
player(double the_cash) 
{ 
    cash = the_cash; 
    bet = 0; 
} 

void hit(card c) 
{ 
    hand.push_back(c); 
} 


int total_hand() 
{ 
    int count = 0; 
    for (int i = 0; i < hand.size(); i++) 
    { 
     card c = hand[i]; 
     count = count + c.get_value(); 
    } 
    return count; 

} 
}; 

如何我會去編碼Ace嗎?他幾乎沒有去創造一個「朋友」最後一堂課。我應該在甲板內創建一個將數組中的Ace值改爲1的朋友函數嗎?如果我沒有道理,我的大腦會受到傷害,道歉。

+0

*我如何去編碼Ace?* - 聽說過if-else語句?您發佈的所有代碼都無法在任何地方使用,這可能是您如何根據特定場景編碼具有兩個值之一的特殊卡的方式。 – PaulMcKenzie

回答

0

您可以通過兩種方式實施。

要添加10後,你可以改變你的total_hand()函數成爲:

int total_hand 
{ 
    int count = 0; 
    int num_of_aces = 0; 
    for (int i = 0; i < hand.size(); i++) 
    { 
     card c = hand[i]; 
     if (c.get_value() == 11){ 
      num_of_aces += 1; 
      count += 1; 
     } 
     else 
      count = count + c.get_value(); 
    } 
    for (int i = 0; i < num_of_aces; i++){ 
     if (count + 10 <= 21) 
      count += 10; 
    return count; 
} 

要減去10後(如你的直覺建議),你可以做到以下幾點:

int total_hand 
{ 
    int count = 0; 
    int num_of_aces = 0; 
    for (int i = 0; i < hand.size(); i++) 
    { 
     card c = hand[i]; 
     if (c.get_value() == 11) 
      num_of_aces += 1; 

     count = count + c.get_value(); 
    } 

    while(count > 21 && num_of_aces--) 
     count -=10; 

    return count; 
} 
+0

「添加10」的情況可以變得更簡單和更快,因爲沒有必要數一數。只要保持一個標誌,不管是否已經看到任何王牌,並且如果總數小於12,則只添加10次,而不是循環。 –