我为我的C++课程做了一个二十一点游戏。我在检查谁赢得了比赛时遇到问题。在比赛期间,我会在每次抽奖后检查那个人是否被破坏(总共超过 21 次)。如果他们确实破坏了,我会将其存储在变量中。他们playerBust
和dealerBust
.它们被初始化为 0
。
win-check 是一个标准的 if/else-if 段。它说playerBust == 1
总是假的,dealerBust == 0
总是真的。
但是,游戏的最后一次测试我记录了这两个,并在最后dealerBust = 1
。
对我的代码的一些解释:
deck.newdeck
给了我一个新的、洗牌的套牌。
initializeGame();
将玩家和庄家的手牌总数设置为 0
。
.toString()
简单地返回一个命名卡片的字符串,例如"黑桃王牌"。
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;
你正在使用逻辑或(||
),而你实际上想使用逻辑和(&&
)代替。
考虑一下:
if (playerBust == 1 || dealerBust == 1){
cout << "Tie" << endl;
}
else if (playerBust == 1 || dealerBust == 0)
如果不采用第一个分支,那么我们知道playerBust
不是真的,dealerBust
也不是。因此,在else if
中,测试playerBust
是否为真(不可能)或dealerBust
是否为假(一定是)是没有意义的。