结构体数组实现洗牌和发牌的代码
时间: 2024-06-17 18:05:45 浏览: 10
洗牌和发牌是扑克游戏中常见的操作。结构体数组可以用来存储一副扑克牌,并且通过洗牌和发牌操作来实现游戏。
下面是一个简单的结构体数组实现洗牌和发牌的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 定义扑克牌结构体
struct Poker {
char *suit; // 花色
char *rank; // 点数
};
// 初始化一副扑克牌
void initPoker(struct Poker *poker) {
char *suits[] = {"Hearts", "Diamonds", "Clubs", "Spades"};
char *ranks[] = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
for (int i = 0; i < 52; i++) {
poker[i].suit = suits[i / 13];
poker[i].rank = ranks[i % 13];
}
}
// 洗牌函数
void shuffle(struct Poker *poker) {
srand(time(NULL)); // 使用当前时间作为随机种子
for (int i = 51; i > 0; i--) {
int j = rand() % (i + 1); // 随机生成一个0到i的整数
// 交换i和j位置上的扑克牌
struct Poker temp = poker[i];
poker[i] = poker[j];
poker[j] = temp;
}
}
// 发牌函数
void deal(struct Poker *poker, int numPlayers, int numCards) {
for (int i = 0; i < numPlayers; i++) {
printf("Player %d: ", i+1);
for (int j = 0; j < numCards; j++) {
printf("%s of %s\t", poker[i*numCards+j].rank, poker[i*numCards+j].suit);
}
printf("\n");
}
}
int main() {
struct Poker poker[52]; // 定义一副扑克牌
initPoker(poker); // 初始化扑克牌
shuffle(poker); // 洗牌
deal(poker, 4, 13); // 发牌,每个玩家发13张牌
return 0;
}
```
这个代码会输出四个玩家的手牌,每个玩家有13张牌。你可以根据需要修改`numPlayers`和`numCards`参数来改变玩家数和每个玩家的牌数。如果你需要了解更多关于结构体数组的知识,可以参考C语言基础教程。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)