“条件永远是真实的”,当我知道它不是

时间:2016-02-22 22:27:00

标签: c++

我为我的C ++课程制作了一个二十一点游戏。我在查看谁赢了比赛时遇到了问题。在比赛期间,我在每次抽奖后检查该人是否被击败(总共超过21人)。如果他们确实破产我将它存储在一个变量中。它们是playerBustdealerBust。它们被初始化为0

win-check是标准if / else-if段。它说playerBust == 1总是假的,dealerBust == 0总是如此。

但是,游戏的最后一次测试我记录了这两个,并且dealerBust = 1到最后。

我的代码的一些解释:

deck.newdeck给了我一个新的,洗牌的牌组。

initializeGame();将玩家和经销商的总牌设置为0

.toString()只需返回一个命名卡片的字符串,例如“Ace of Spades”。

getPlayerCardValue(...)getDealerCardValue(...)只是评估刚刚绘制的卡片的数值。

void Blackjack::playGame(){
deck.newDeck();
initializeGame();
drawInitialCards();
bool playerBust = 0;
bool dealerBust = 0;
Card newCard;

// PLAYERS TURN
if (playerHand > 21){
    playerBust = 1;
}
else if (playerHand < 21){
    bool stopDraw = 0;
    while (stopDraw == 0){
        bool playerDraw = askPlayerDrawCard();
        if (playerDraw == 1){
            newCard = deck.drawCard();
            cout << endl << "You drew: " << newCard.toString() << endl;
            playerHand += getPlayerCardValue(newCard);
            cout << "Player's total: " << playerHand << endl;
            if (playerHand > 21){
                playerBust = 1;
                stopDraw = 1;
            }
        }
        else if (playerDraw == 0){
            stopDraw = 1;
        }
    }
}

// DEALERS TURN
dealerHand += getDealerCardValue(dealerFaceDown, dealerHand);
cout << "Dealer's face down card is: " << dealerFaceDown.toString() << endl
<< "Dealer's total: " << dealerHand << endl;

if (dealerHand > 21){
    dealerBust = 1;
}
else if (dealerHand < 21){
    while (dealerHand < 17){
        newCard = deck.drawCard();
        cout << endl << newCard.toString() << endl;
        dealerHand += getDealerCardValue(newCard, dealerHand);
        cout << "Dealer's hand totals: " << dealerHand << endl;
        if (dealerHand > 21){
            dealerBust = 1;
        }
    }
}

// WINNING CONDITIONS
if (playerBust == 1 || dealerBust == 1){
    cout << "Tie" << endl;
}
else if (playerBust == 1 || dealerBust == 0){
    cout << "Dealer wins" << endl;
}
else if (playerBust == 0 || dealerBust == 1){
    cout << "Player wins" << endl;
}
else if (playerBust == 0 || dealerBust == 0){
    if (playerHand > dealerHand){
        cout << "Player wins" << endl;
    }
}
cout << endl << "Player's bust: " << playerBust << endl << "Dealer's bust: " << dealerBust << endl;

2 个答案:

答案 0 :(得分:11)

您正在使用逻辑或||),而您实际上想要使用逻辑和&&)。

答案 1 :(得分:1)

考虑一下:

if (playerBust == 1 || dealerBust == 1){
    cout << "Tie" << endl;
}
else if (playerBust == 1 || dealerBust == 0)

如果没有采用第一个分支,那么我们知道playerBust不是真的,dealerBust也不是。{1}}。所以在else if中没有必要测试playerBust是否为真(它不可能)或dealerBust是否为假(必须是)。