用函数,指针,写c语言随机发牌
时间: 2023-05-29 08:07:43 浏览: 178
这里提供一个简单的随机发牌程序,使用指针和函数来实现:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define DECK_SIZE 52
#define SUIT_SIZE 13
void shuffle(int deck[], int size);
void deal(int deck[], int size, int num_players);
int main() {
int deck[DECK_SIZE];
int num_players;
// Initialize deck
for (int i = 0; i < DECK_SIZE; i++) {
deck[i] = i;
}
// Prompt for number of players
printf("Enter number of players: ");
scanf("%d", &num_players);
// Shuffle deck
srand(time(NULL));
shuffle(deck, DECK_SIZE);
// Deal cards
deal(deck, DECK_SIZE, num_players);
return 0;
}
void shuffle(int deck[], int size) {
for (int i = size - 1; i >= 0; i--) {
int j = rand() % (i + 1);
int temp = deck[i];
deck[i] = deck[j];
deck[j] = temp;
}
}
void deal(int deck[], int size, int num_players) {
int *cards[num_players];
int num_cards = size / num_players;
for (int i = 0; i < num_players; i++) {
cards[i] = &deck[i * num_cards];
}
printf("\nCards Dealt:\n");
for (int i = 0; i < num_players; i++) {
printf("Player %d:", i + 1);
for (int j = 0; j < num_cards; j++) {
int card = *(cards[i] + j);
int suit = card / SUIT_SIZE;
int rank = card % SUIT_SIZE;
printf(" %c%c", rank + 'A', suit + 'S');
}
printf("\n");
}
}
```
首先,我们定义了常量 `DECK_SIZE` 和 `SUIT_SIZE` 分别代表扑克牌的数量和花色的数量。
然后,我们定义了两个函数 `shuffle` 和 `deal`,分别用于洗牌和发牌。
`shuffle` 函数使用 Fisher-Yates 洗牌算法,随机交换每个牌的位置,从而达到洗牌的目的。
`deal` 函数将洗好的牌分配给每个玩家。它首先将指向每个玩家的牌的指针存储在 `cards` 数组中,然后使用指针算术运算来访问每个玩家的牌。
最后,在 `main` 函数中,我们创建一个 `deck` 数组,用于存储扑克牌的编号。我们使用 `scanf` 函数从用户那里读取玩家数量,并调用 `shuffle` 和 `deal` 函数来随机洗牌和发牌。
注意,这个程序没有考虑到特殊牌(如鬼牌),并且可能需要进行更多的错误检查来确保输入的正确性。
阅读全文
相关推荐



















