用结构体,函数,指针,文件,写一个模拟发牌的c语言代码
时间: 2023-06-01 22:02:18 浏览: 114
下面是一个简单的模拟发牌的C语言代码,使用了结构体,函数,指针和文件:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define NUM_RANKS 13
#define NUM_SUITS 4
#define NUM_CARDS 52
typedef struct {
int rank;
int suit;
} Card;
void shuffle(Card *deck);
void swap(Card *card1, Card *card2);
void print_card(Card *card);
void print_deck(Card *deck, int num_cards);
void deal(Card *deck, Card *hand, int num_cards);
int main(void) {
Card deck[NUM_CARDS];
Card hand[5];
FILE *fp;
// Initialize the deck
int i, j, card_count = 0;
for (i = 0; i < NUM_RANKS; i++) {
for (j = 0; j < NUM_SUITS; j++) {
deck[card_count].rank = i;
deck[card_count].suit = j;
card_count++;
}
}
// Shuffle the deck
srand((unsigned) time(NULL));
shuffle(deck);
// Print the shuffled deck
printf("Shuffled deck:\n");
print_deck(deck, NUM_CARDS);
// Deal a hand of five cards
deal(deck, hand, 5);
// Print the hand
printf("Hand:\n");
print_deck(hand, 5);
// Write the hand to a file
fp = fopen("hand.txt", "w");
for (i = 0; i < 5; i++) {
fprintf(fp, "%d %d\n", hand[i].rank, hand[i].suit);
}
fclose(fp);
return 0;
}
void shuffle(Card *deck) {
int i;
for (i = 0; i < NUM_CARDS; i++) {
int j = rand() % NUM_CARDS;
swap(&deck[i], &deck[j]);
}
}
void swap(Card *card1, Card *card2) {
Card temp = *card1;
*card1 = *card2;
*card2 = temp;
}
void print_card(Card *card) {
char *ranks[] = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
char *suits[] = {"Clubs", "Diamonds", "Hearts", "Spades"};
printf("%s of %s\n", ranks[card->rank], suits[card->suit]);
}
void print_deck(Card *deck, int num_cards) {
int i;
for (i = 0; i < num_cards; i++) {
print_card(&deck[i]);
}
}
void deal(Card *deck, Card *hand, int num_cards) {
int i;
for (i = 0; i < num_cards; i++) {
hand[i] = deck[i];
}
}
```
这个程序使用了一个 `Card` 结构体来表示一张扑克牌,其中包括牌的等级和花色。在 `main` 函数中,先初始化一副牌,然后洗牌并打印出来。接着用 `deal` 函数从牌堆中发出5张牌,并打印出手牌。最后将手牌写入文件 `hand.txt` 中。 `shuffle` 函数用于洗牌, `swap` 函数用于交换两张牌的位置, `print_card` 函数用于打印一张牌, `print_deck` 函数用于打印整副牌。
阅读全文