用C语言模拟扑克自动发牌
时间: 2024-03-01 14:50:55 浏览: 143
好的,这是一个比较简单的扑克自动发牌的 C 语言程序示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define CARD_NUM 52
#define PLAYER_NUM 4
void shuffle(int* deck, int n) {
srand(time(NULL));
for (int i = n - 1; i > 0; i--) {
int j = rand() % (i + 1);
int temp = deck[i];
deck[i] = deck[j];
deck[j] = temp;
}
}
void print_card(int card) {
const char* suits[] = {"Spades", "Hearts", "Diamonds", "Clubs"};
const char* ranks[] = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
int suit = card / 13;
int rank = card % 13;
printf("%s of %s\n", ranks[rank], suits[suit]);
}
int main() {
int deck[CARD_NUM];
for (int i = 0; i < CARD_NUM; i++) {
deck[i] = i;
}
shuffle(deck, CARD_NUM);
int player_cards[PLAYER_NUM][CARD_NUM / PLAYER_NUM];
for (int i = 0; i < PLAYER_NUM; i++) {
printf("Player %d:\n", i + 1);
for (int j = 0; j < CARD_NUM / PLAYER_NUM; j++) {
player_cards[i][j] = deck[CARD_NUM / PLAYER_NUM * i + j];
print_card(player_cards[i][j]);
}
printf("\n");
}
return 0;
}
```
程序中定义了两个常量 `CARD_NUM` 和 `PLAYER_NUM`,分别表示一副扑克牌的数量和玩家数量。`shuffle` 函数用于洗牌,采用了随机交换的方法。`print_card` 函数用于打印一张扑克牌的花色和点数。在 `main` 函数中,先生成一副牌并洗牌,然后按照玩家数量将牌发到不同的玩家手中,并打印每个玩家的牌。
阅读全文