C语言实现模拟扑克牌发牌,只考虑四种花色的共52张牌,不考虑大鬼和小鬼,每人发十三张牌
时间: 2024-02-07 20:04:07 浏览: 202
扑克牌发牌C语言程序
好的,以下是实现模拟扑克牌发牌的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define CARD_NUM 52
#define PLAYER_NUM 4
#define CARD_TYPE_NUM 4
#define CARD_NUM_PER_TYPE 13
// 牌的结构体
typedef struct {
int type; // 花色,0-3表示黑桃、红心、梅花、方块
int num; // 点数,1-13表示A到K
} Card;
// 初始化牌组
void init_cards(Card *cards) {
for (int i = 0; i < CARD_TYPE_NUM; i++) {
for (int j = 0; j < CARD_NUM_PER_TYPE; j++) {
cards[i * CARD_NUM_PER_TYPE + j].type = i;
cards[i * CARD_NUM_PER_TYPE + j].num = j + 1;
}
}
}
// 洗牌
void shuffle_cards(Card *cards) {
srand(time(NULL)); // 设置随机种子
for (int i = CARD_NUM - 1; i >= 1; i--) {
int j = rand() % (i + 1); // 生成0到i之间的随机数
Card temp = cards[i];
cards[i] = cards[j];
cards[j] = temp;
}
}
// 输出牌的信息
void print_card(Card card) {
const char *type_strs[] = {"黑桃", "红心", "梅花", "方块"};
const char *num_strs[] = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
printf("%s%s ", type_strs[card.type], num_strs[card.num - 1]);
}
// 输出玩家的牌
void print_player_cards(int player_id, Card *cards) {
printf("玩家%d的牌:", player_id);
for (int i = 0; i < CARD_NUM_PER_TYPE; i++) {
print_card(cards[player_id * CARD_NUM_PER_TYPE + i]);
}
printf("\n");
}
int main() {
Card cards[CARD_NUM];
init_cards(cards); // 初始化牌组
shuffle_cards(cards); // 洗牌
// 发牌
Card player_cards[PLAYER_NUM][CARD_NUM_PER_TYPE];
for (int i = 0; i < CARD_NUM_PER_TYPE; i++) {
for (int j = 0; j < PLAYER_NUM; j++) {
player_cards[j][i] = cards[i * PLAYER_NUM + j];
}
}
// 输出每个玩家的牌
for (int i = 0; i < PLAYER_NUM; i++) {
print_player_cards(i, player_cards[i]);
}
return 0;
}
```
你可以直接将上述代码复制粘贴到C语言的开发环境中进行编译运行。希望能够帮到你。
阅读全文