用指针,文件,结构体,函数,写一个c语言随机发牌
时间: 2023-05-29 14:07:51 浏览: 102
C语言实现随机发牌
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define CARD_NUM 52
#define PLAYER_NUM 4
typedef struct card {
char suit; // 花色
char rank; // 点数
} Card;
void shuffle(Card *deck, int size) {
srand(time(NULL));
for (int i = 0; i < size; i++) {
int j = rand() % size;
Card temp = deck[i];
deck[i] = deck[j];
deck[j] = temp;
}
}
void printCards(Card *cards, int size) {
for (int i = 0; i < size; i++) {
printf("%c%c ", cards[i].suit, cards[i].rank);
}
printf("\n");
}
void dealCards(Card *deck, Card **players, int player_num, int card_num) {
for (int i = 0; i < player_num; i++) {
for (int j = 0; j < card_num; j++) {
players[i][j] = deck[i * card_num + j];
}
}
}
int main() {
Card deck[CARD_NUM];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 13; j++) {
deck[i * 13 + j].suit = "CDHS"[i];
deck[i * 13 + j].rank = "A23456789TJQK"[j];
}
}
shuffle(deck, CARD_NUM);
Card *players[PLAYER_NUM];
for (int i = 0; i < PLAYER_NUM; i++) {
players[i] = (Card *)malloc(sizeof(Card) * 13);
}
dealCards(deck, players, PLAYER_NUM, 13);
for (int i = 0; i < PLAYER_NUM; i++) {
printf("Player %d: ", i + 1);
printCards(players[i], 13);
}
for (int i = 0; i < PLAYER_NUM; i++) {
free(players[i]);
}
return 0;
}
阅读全文