所以我尝试用 C 语言编写一个 Blackjack 游戏只是为了好玩(这是我以前从未尝试过的)。我已经完成了最初的几个步骤,例如如何设置牌组以及如何将牌交给庄家和玩家。但是,显示的输出也没有显示我想要的(显示庄家只有 1 张牌,而应该显示 2 张牌)。这是一个屏幕截图:
我确实在我的手机上运行了这个(更容易获得截图),但我在我的计算机上使用 Code::Blocks 得到了相同的结果。无论如何,我有两个函数来处理设置套牌和显示当前卡片。我在 main() 函数中使用循环处理的牌。我知道 makeDeck() 函数工作正常,所以我假设我的错误在其他地方。看看我的代码,让我知道发生了什么(另外,任何改进建议将不胜感激):
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/*Function Prototypes*/
int* makeDeck();
/*Usage - returns an int* to be used for the deck */
void showHands(int[], int[]);
/*Usage - pass dealerHand[], then playerHand[] */
int main() {
srand(time(0)); //Make a new rand() seed value
int x, count = 0, choice = 1;
int* cards = makeDeck();
int dealerCards[12]; //cards in hand will never exceed 11
int playerCards[12]; //4 A's, 4 2's, 3 3's
/*Loop to run the game. One iteration per hand */
while(choice != 0) {
for(x = 0; x < 12; x++) {
dealerCards[x] = 0;
playerCards[x] = 0;
}
//Deal 2 cards to dealer and player
for(x = 0; x < 2; x++) {
dealerCards[x] = cards[count];
count++;
}
for(x = 0; x < 2; x++) {
playerCards[x] = cards[count];
count++;
}
showHands(dealerCards, playerCards);
/*DEBUGGING */
printf("\nEnter 0 to exit loop: ");
scanf("%i", &choice);
}
return 0;
}
//Declare placeholder variable "bunchOfCards" globally
int bunchOfCards[52];
int* makeDeck(){
int* deck = bunchOfCards;
int x = 0,
y = 0,
card = 0;
for(x = 0; x < 52; x++) { //set all cards to 0
deck[x] = 0;
}
for(x = 0; x < 4; x++) { //set up deck
for(y = 1; y < 14; y++) {
card = (rand() % 52);
//check if deck position is already used
while(deck[card] != 0) {
card = (rand() % 52);
}
deck[card] = y;
}
}
/* DEBUGGING
for(x = 0; x < 52; x++) {
printf("%i\t", deck[x]);
} */
return deck;
}
void showHands(int* dealer, int* player) {
int x; char card[3] = { '\0', '\0', '\0' };
puts("The hands are: \n\nDealer:");
//Display dealer cards
for(x = 0; x < 12; x++) {
if(dealer[x] != 0) {
if((dealer[x] < 10) && (dealer[x] != 1)) {
card[0] = (char)(((int)'0') + dealer[x]);
card[1] = '\0';
} else if(dealer[x] == 1) {
card[0] = 'A';
card[1] = '\0';
} else if(dealer[x] == 10) {
card[0] = '1';
card[1] = '0';
} else if(dealer[x] == 11) {
card[0] = 'J';
card[1] = '\0';
} else if(dealer[x] == 12) {
card[0] = 'Q';
card[1] = '\0';
} else if(dealer[x] == 13) {
card[0] = 'K';
card[1] = '\0';
}
printf("\t%s", card);
}
//Display player cards
puts("\nPlayer: ");
for(x = 0; x < 12; x++) {
if(player[x] != 0) {
if((player[x] < 10) && (player[x] != 1)) {
card[0] = (char)(((int)'0') + player[x]);
card[1] = '\0';
} else if(player[x] == 1) {
card[0] = 'A';
card[1] = '\0';
} else if(player[x] == 10) {
card[0] = '1';
card[1] = '0';
} else if(player[x] == 11) {
card[0] = 'J';
card[1] = '\0';
} else if(player[x] == 12) {
card[0] = 'Q';
card[1] = '\0';
} else if(player[x] == 13) {
card[0] = 'K';
card[1] = '\0';
}
printf("\t%s", card);
}
}
}
}