本系列讲解如何基于Cocos2d-x制作《单机斗地主》游戏,并对游戏源码进行剖析,以帮助大家理解游戏逻辑以及开发关键技术。
1.创建一副扑克牌,写代码首先创建一张牌的类。如下所示:
class Poker : public Sprite { public: Poker(); ~Poker(); static Poker* create(const char *pszFileName, const CCRect& rect); virtual void onEnter(); virtual void onExit(); virtual bool onTouchBegan(CCTouch *pTouch, CCEvent *pEvent); virtual void onTouchMoved(CCTouch *pTouch, CCEvent *pEvent); virtual void onTouchEnded(CCTouch *pTouch, CCEvent *pEvent); virtual void onTouchCancelled(CCTouch *pTouch, CCEvent *pEvent); void showFront();//显示正面 void showLast();//显示背面 Poker* copy();//拷贝 void setTouchPriority(int num); void SelectPkLuTou();//如果选择了牌就露出头 void SelectPkSuoTou();//如果选择了牌就缩头 private: CC_SYNTHESIZE(bool,m_isSelect,Select);//是否已选 CC_SYNTHESIZE(GameScene*,m_gameMain,GameMain); CC_SYNTHESIZE(bool,m_isDianJi,DianJi);//是否能被点击 CC_SYNTHESIZE(int,m_huaSe,HuaSe);//花色 CC_SYNTHESIZE(int,m_num,Num);//牌值 EventListenerTouchOneByOne* touchListener; };
然后我们用这个类写了一个函数来生成一张牌,该函数如下(位于源码GameScene中):
Poker* GameScene::selectPoker(int huaSe,int num){ Poker* pk; if(huaSe != Gui) pk = Poker::create("poker.png",CCRect(num*pkWidth,huaSe*pkHeight,pkWidth,pkHeight)); else pk = Poker::create("poker.png",CCRect((num-XiaoGui)*pkWidth,huaSe*pkHeight,pkWidth,pkHeight)); pk->setHuaSe(huaSe); pk->setNum(num); pk->setGameMain(this); return pk; }
poker.png图片如下:
2.接下来我们就用来创建一副扑克牌了,请看代码(在GameScene文件中)GameScene
bool GameScene::createPokers(){ bool isRet = false; do { Size size = Director::sharedDirector()->getVisibleSize(); Poker* pk; //创建52个除大鬼小鬼外的牌 for (int i=0; i<4; ++i) { for (int j=0; j<13; ++j) { pk = selectPoker(i,j); pk->setPosition(ccp(size.width/2/*+j*20*/,size.height/2/*-i*20*/)); pk->showLast(); this->addChild(pk); this->m_arrPokers->addObject(pk); } } //创建小鬼 pk = selectPoker(Gui,XiaoGui); pk->setPosition(ccp(size.width/2,size.height/2/*-4*20*/)); pk->showLast(); this->addChild(pk); this->m_arrPokers->addObject(pk); //创建大鬼 pk = selectPoker(Gui,DaGui); pk->setPosition(ccp(size.width/2/*+20*/,size.height/2/*-4*20*/)); pk->showLast(); this->addChild(pk); this->m_arrPokers->addObject(pk); isRet = true; } while (0); return isRet; }