C语言斗地主小游戏源代码
时间: 2024-03-27 20:33:34 浏览: 97
C语言斗地主小游戏源代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NUM_OF_CARDS 54
#define NUM_OF_PLAYERS 3
#define NUM_OF_HAND_CARDS 17
typedef struct {
int num;
int suit;
} Card;
void shuffle(Card *deck) {
srand(time(NULL));
for (int i = NUM_OF_CARDS - 1; i > 0; i--) {
int j = rand() % (i + 1);
Card temp = deck[i];
deck[i] = deck[j];
deck[j] = temp;
}
}
void deal(Card *deck, Card **players) {
for (int i = 0; i < NUM_OF_PLAYERS; i++) {
players[i] = (Card *)malloc(NUM_OF_HAND_CARDS * sizeof(Card));
for (int j = 0; j < NUM_OF_HAND_CARDS; j++) {
players[i][j] = deck[i * NUM_OF_HAND_CARDS + j];
}
}
}
void printCard(Card card) {
char *numStr[] = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "小王", "大王"};
char *suitStr[] = {"♠️", "♥️", "♣️", "♦️"};
printf("%s%s ", numStr[card.num], suitStr[card.suit]);
}
void printHandCards(Card *handCards, int num) {
for (int i = 0; i < num; i++) {
printCard(handCards[i]);
}
printf("\n");
}
int main() {
Card deck[NUM_OF_CARDS];
for (int i = 0; i < NUM_OF_CARDS; i++) {
deck[i].num = i % 13;
deck[i].suit = i / 13;
}
shuffle(deck);
Card *players[NUM_OF_PLAYERS];
deal(deck, players);
printf("玩家1的手牌:");
printHandCards(players[0], NUM_OF_HAND_CARDS);
printf("玩家2的手牌:");
printHandCards(players[1], NUM_OF_HAND_CARDS);
printf("玩家3的手牌:");
printHandCards(players[2], NUM_OF_HAND_CARDS);
for (int i = 0; i < NUM_OF_PLAYERS; i++) {
free(players[i]);
}
return 0;
}
```
这段代码实现了一个简单的斗地主小游戏,包括洗牌、发牌和打印玩家手牌的功能。在代码中,使用了一个Card结构体表示一张扑克牌,其中num表示牌面大小,suit表示花色。首先,通过shuffle函数对一副54张的扑克牌进行洗牌。然后,通过deal函数将洗好的牌发给三个玩家。最后,通过printHandCards函数打印每个玩家的手牌。
阅读全文