上一节,我们把游戏界面已经编译好了,那么这一节,我们要实现我们的游戏方法。
//添加石头菜单 auto shitouMenu= MenuItemImage::create( "shitou.png","shitou.png",CC_CALLBACK_1(SettingScene::shitou,this)); shitouMenu->setPosition(Point(300,100)); auto menu = Menu::create(shitouMenu,NULL); menu->setPosition(Vec2::ZERO); this->addChild(menu,1); //添加剪刀菜单 auto jiandaoMenu= MenuItemImage::create( "jiandao.png","jiandao.png",CC_CALLBACK_1(SettingScene::jiandao,this)); jiandaoMenu->setPosition(Point(500,100)); auto menu1= Menu::create(jiandaoMenu,NULL); menu1->setPosition(Vec2::ZERO); this->addChild(menu1,1); //添加布菜单 auto buMenu= MenuItemImage::create( "bu.png","bu.png",CC_CALLBACK_1(SettingScene::bu,this)); buMenu->setPosition(Point(700,100)); auto menu2= Menu::create(buMenu,NULL); menu2->setPosition(Vec2::ZERO); this->addChild(menu2,1); return true;
通过MenuItemImage这个类,我们在Init()中添加了菜单,两张图片分别代表的是点击菜单前后的样子.SetPosition不必多说。
//定义的石头回调函数 void SettingScene::shitou(Ref* pSender) { ChuquanCount(); auto sprite01=Sprite::create("shitou.png"); sprite01->setPosition(Point(350,350)); this->addChild(sprite01); sprite01->setTag(100); int x=rand()%3+1; switch (x) { case 1: { auto spriteComputer1=Sprite::create("shitou.png"); spriteComputer1->setPosition(Point(650,350)); this->addChild(spriteComputer1); spriteComputer1->setTag(100); if(sprite01->getTag()==spriteComputer1->getTag()) { CCLOG("Draw"); DrawCount(); } CCLOG("shitou"); break; } case 2: { auto spriteComputer2=Sprite::create("jiandao.png"); spriteComputer2->setPosition(Point(650,350)); this->addChild(spriteComputer2); spriteComputer2->setTag(200); if(sprite01->getTag()<spriteComputer2->getTag()) { CCLOG("Win"); WinCount(); } CCLOG("jiandao"); break; } case 3: { auto spriteComputer3=Sprite::create("bu.png"); spriteComputer3->setPosition(Point(650,350)); this->addChild(spriteComputer3); spriteComputer3->setTag(300); if(sprite01->getTag()<spriteComputer3->getTag()) { CCLOG("Lose"); LoseCount(); } CCLOG("bu"); break; } default: { break; } } }
//出拳次数 void SettingScene::ChuquanCount() { count++; LabelTTFCountscore->setString(String::createWithFormat("%i",count)->getCString()); } //胜利次数 void SettingScene::WinCount() { wincount++; LabelTTFWinscore->setString(String::createWithFormat("%i",wincount)->getCString()); } //失败次数 void SettingScene::LoseCount() { losecount++; LabelTTFLosescore->setString(String::createWithFormat("%i",losecount)->getCString()); } //平局次数 void SettingScene::DrawCount() { drawcount++; LabelTTFDrawscore->setString(String::createWithFormat("%i",drawcount)->getCString()); }上边定义了石头的回调函数,以及计算分数方法。通过阅读代码不难理解其意思。要注意一点的是因为用到了随机数,要置随机数种子。就在我们的AppDelegate.cpp中的bool AppDelegate::applicationDidFinishLaunching()方法中,填入srand((int)time(0));在SettingScene中包含一个time.h和stdlib.h头文件,在来一个宏定义#define (rand()%x)就齐活了,这样一个完整的游戏就制作好了。PS:中间可能有一些没有定义的,我没有截,希望读者多动手动脑。小编也会继续努力,做出更好的作品与读者们分享。 原文链接:https://www.f2er.com/cocos2dx/343797.html