#include <string.h> #include <time.h> #include <iostream> using namespace std;
#define POKER_MAX 54 //54张扑克 #define POKER_COLOR_MAX 4 //四种主花色 #define POKER_POINT_MAX 13 //每种花色13张牌,J=11,Q=12,K=13 #define POKER_COLOR_KING 4 //王的花色 #define POKER_COLOR_0 0 //黑桃花色 #define POKER_COLOR_1 1 //红桃花色 #define POKER_COLOR_2 2 //樱花花色 #define POKER_COLOR_3 3 //方块花色 #define POKER_KING_POINT_BIG 1 //大王的点数 #define POKER_KING_POINT_LITTLE 0 //小王的点数 typedef struct _POKER_CARD_ { short m_sID; //全序列排列时的ID(0~53) char m_cColor; //扑克花色 char m_cPoint; //扑克点数 }SCard; const unsigned long SCardSize=sizeof(SCard); class CPoker { public: CPoker() { //先整齐排列54张牌,按黑红樱方顺序,每种花色按0~12顺序 int i=0; int j=0; int nIndex=0; for(i=0;i<POKER_COLOR_MAX;i++) { for(j=0;j<POKER_POINT_MAX;j++) { SetPokerInfo(i,j,nIndex); nIndex++; } } //王放在最后两张 SetPokerInfo(POKER_COLOR_KING,POKER_KING_POINT_LITTLE,nIndex); //小王 nIndex++; SetPokerInfo(POKER_COLOR_KING,POKER_KING_POINT_BIG,nIndex); //大王 } ~CPoker(){} //一般说来,按牌总数决定洗牌次数,已经洗得很烂了 void Wash(int nTime=POKER_MAX) { int i=0; randIndex = 0; for(i=0;i<nTime;i++) Random(); } //实际的游戏,从此处取洗好的牌张数据 bool Get(unsigned int nIndex,SCard* pCard) { if(POKER_MAX<=nIndex) return false; memcpy((char*)pCard,(char*)&m_Poker[nIndex],SCardSize); return true; } void PrintInfo(void) { int i=0; SCard Card; for(i=0;i<POKER_MAX;i++) { if(Get(i,&Card)) { printf("%02d - ID=%02d, Color=%d, Point=%02d\n", i,Card.m_sID,Card.m_cColor,Card.m_cPoint); } } printf("===============\n"); } private: //给sID指定的牌张赋值 void SetPokerInfo(char cColor,char cPoint,short sID) { m_Poker[sID].m_cColor=cColor; m_Poker[sID].m_cPoint=cPoint; m_Poker[sID].m_sID=sID; } //交换两张牌 void Exchange(int a,int b) { char szTemp[SCardSize]; memcpy(szTemp,(char*)&m_Poker[a],SCardSize); memcpy((char*)&m_Poker[a],(char*)&m_Poker[b],SCardSize); memcpy((char*)&m_Poker[b],szTemp,SCardSize); } int GetRandomBetween() { int retVal = 0; time_t t; srand((unsigned) time(&t)); for(int i=0; i<54; i++) { randData[i] = rand() % 54; } ++randIndex; if(randIndex > 53) { randIndex = 0; } return randData[randIndex]; } //随机选取两张牌张交换洗牌 //如果随机数相等,发生碰撞,则b=a+1,总之不一样就可以了。 void Random(void) { int a=0; int b=0; a = GetRandomBetween(); b = GetRandomBetween(); //printf("%d---%d\n",a,b); if(a==b) { b=a+1; if(POKER_MAX<=b) b=0; } Exchange(a,b); } private: SCard m_Poker[POKER_MAX]; int randData[54]; int randIndex; };
执行主函数
#include "stdafx.h" #include "CPoker.h"
int main(int argc, char* argv[]) { CPoker Poker; srand((unsigned int)time(NULL)); Poker.PrintInfo(); Poker.Wash(); Poker.PrintInfo(); Poker.Wash(); Poker.PrintInfo();
return 0; }
|