扑克发牌算法 |
---|
扑克中的元素由两种内容组成:花色和面值。 花色:黑桃、红桃、方块、草花; 面值:A、2、3、4、5、6、7、8、9、10、J、Q、K。 一副不含Joker的牌共52张(13*4)张。 现在要实现给四个人(Player)发牌。 |
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define POKERS_COUNT 52
#define POKER_TYPE_COUNT 13
const char *pokerType[] = {"黑桃", "红桃", "方块", "草花"}; //const 常量,只读 指针数组
const char *pokerValue[] = {" A", " 2", " 3", " 4", " 5", " 6", " 7", " 8", " 9", "10", " J", " Q", " K"};
//[]和pokerType优先结合 const char* pokerType[] = {"黑桃", "红桃", "方块", "草花"}; 不加个数是为了方便以后进行修改
//数组,有四个元素,每个元素是char*,是四个字节,和里面的内容没有任何关系
//关于数组指针和指针数组详细参见 https://blog.csdn.net/weixin_42072280/article/details/83210655
void resetPoker(char *poker); //整牌
void dealPoker(char (*playerPokerSet)[POKER_TYPE_COUNT]); //deal 发牌
void showPlayerPokerSet(char (*playerPokerSet)[POKER_TYPE_COUNT], int whichOne);
void sortPlayerPokerSet(char *playerPoker);
void sortPlayerPokerSet(char *playerPoker){ //先把牌进行排序,把同一花色的牌连续输出,为了输出好看
int i;
int j;
int tmp;
for(i = 0; i < POKER_TYPE_COUNT; i++){
for(j = i + 1; j < POKER_TYPE_COUNT; j++){
if(playerPoker[i] > playerPoker[j]){
tmp = playerPoker[i];
playerPoker[i] = playerPoker[j];
playerPoker[j] = tmp;
}
}
}
}
void showPlayerPokerSet(char (*playerPokerSet)[POKER_TYPE_COUNT], int whichOne){
int i;
int oneCard[POKER_TYPE_COUNT];
if(whichOne < 0 || whichOne > 3){
return;
}
printf("第%d个玩家的牌:\n", whichOne+1);
for(i = 0; i < 4; i++){
sortPlayerPokerSet(playerPokerSet[i]);
}
for(i = 0; i < POKER_TYPE_COUNT; i++){
oneCard[i] = playerPokerSet[whichOne][i];
}
for(i = 0; i < POKER_TYPE_COUNT; i++){
printf("%s:%s ", pokerType[oneCard[i] / POKER_TYPE_COUNT], pokerValue[oneCard[i] % POKER_TYPE_COUNT]);
if((oneCard[i+1] / POKER_TYPE_COUNT) != (oneCard[i] / POKER_TYPE_COUNT)){
printf("\n");
}
}
printf("\n\n");
}
void dealPoker(char (*playerPokerSet)[POKER_TYPE_COUNT]){ //指向数组的指针,数组指针
char pokerSet[POKERS_COUNT];
int index = 0;
int i; //牌的数量
resetPoker(pokerSet); //0-51的值 这一步执行之后的值 pokerSet[i] = i
srand(time(NULL));
for(i = POKERS_COUNT; i > 0; i--){ //29变量生命域 变量存储类型 关于隐藏变量
int num = rand() % i; //用来接收产生的随机数,产生的是下标
int tmp; //用来交换的中间变量
playerPokerSet[0][index++] = pokerSet[num]; //二维数组的一维本质
//详细参见 https://blog.csdn.net/weixin_42072280/article/details/83210941
tmp = pokerSet[num];
pokerSet[num] = pokerSet[i-1];
pokerSet[i-1] = tmp;
}
}
void resetPoker(char *poker){
int i;
for(i = 0; i < POKERS_COUNT; i++){
poker[i] = i;
}
//18 18/13=>1 18%13=>5 1代表红桃 5代表6 红桃6
//51 51/13=>3 53%13=>12 3代表草花 12代表K
}
void main(void){
char playerPokerSet[4][POKER_TYPE_COUNT] = {0}; //int m[3][4]; 构造一个3行4列的二维数组
int i;
dealPoker(playerPokerSet);
for(i = 0; i < 4; i++){
showPlayerPokerSet(playerPokerSet, i);
}
}