cocos2d-x 3.8 之Console模块

偶使用的环境是Mac Xcode, 在看cocos2dx cpp-test项目中,无意之下发现了这样的一段代码:

// Enable Remote Console
auto console = Director::getInstance()->getConsole();
console->listenOnTCP(5678);

有何用处?

  原来这是cocos2d-x 3.0 以后新增的模块,可实现远程调试。比如在PC中连接5678端口,即可连接应用程序,输入相关的命令就可以进行调试功能。 目前已实现"fps", "help", "version"等命令,为了让大家对Console有一个更直观的了解,我们运行ccp-test项目,然后打开终端命令,

输入: nc localhost 5678(Enter),

然后再输入: help(Enter),命令下,会出现以下的图示:

好像到目前为止,还没有发现如何调试应用程序吧,继续听我说下去,项目中,有着这样的代码

// 显示FPS
Director::getInstance()->setDisplayStats(true);

我想把它隐藏,那就在终端中输入命令: fps off(Enter) ,你会发现FPS消失了,再输入 fps on(enter),就又出现了。

这就是Console的好处,当然除了已经实现的命令外,开发者还可继承Console类来添加自己的调试命令。比如设置玩家的等级,金钱的增加或减少,钻石的增减等。

大家想了解Console类,可打开文件../cocos2d_libs.xcodeproj/base/CCConsole.h 文件进行查看,刚才的help命令而出现的帮助信息,大家可查看构造函数Console::Console()即可。

 

为了更深入的了解下Console, 我个人写了一个小Demo,同大家分享下,主要效果如下:

通过命令,可以改变玩家的等级,金钱,钻石等。因为原理相似,偶只贴上主要代码,其UI实现逻辑,不再赘述。

(1) 添加监听,及命令,可在HelloWorld::init()中

  // 添加Console监听
    m_pConsole = Director::getInstance()->getConsole();
    m_pConsole->listenOnTCP(5679);
    
    // 添加自定义命令,其格式为: 命令名称,命令说明,回调函数
    static struct Console::Command gms[] = {
        {"level", "make sure add UserLevel", std::bind(&HelloWorld::GmChangeUserLevel, this, std::placeholders::_1, std::placeholders::_2)},
        {"money", "Add or Reduce Money Num", std::bind(&HelloWorld::GmChangeMoney, this, std::placeholders::_1, std::placeholders::_2)},
        {"diamond", "Add or Reduce Diamond Num", std::bind(&HelloWorld::GmChangeDiamond, this, std::placeholders::_1, std::placeholders::_2)},
        {"item", "input itemId, itemNum, itemBelong", std::bind(&HelloWorld::GmItem, this, std::placeholders::_1, std::placeholders::_2)}
    };
    for (int i = 0; i < sizeof(gms)/sizeof(gms[0]); ++i)
    {
        m_pConsole->addCommand(gms[i]);
    }

(2) 回调函数

// 改变玩家等级,参数1:可理解为soket句柄, 参数2: 命令所带的参数值
void HelloWorld::GmChangeUserLevel(int fd, const std::string& args)
{
    int nLevel = utils::atof(args.c_str());
    if(nLevel <= 0)
    {
        const char msg[] = "input order Error, such as: level 10";
        // 向终端发送数据
        send(fd, msg, sizeof(msg),0);
        send(fd, "\n",1,0);
        return;
    }
    
    // 改变数据(偶的想法,可直接发送server,然后server处理后再做返回,不就是一个简单的GM嘛) 
    CCLOG("GmChangeUserLevel level = %d", nLevel);
    std::string str = StringUtils::format("%d",nLevel);
    m_pUserLev->setString(str);
}

 (3) 输入命令,如图所示:

 

参考资料:

http://www.cocoachina.com/cocos/20140704/9028.html

 

posted @ 2016-03-16 21:09  Code~  阅读(762)  评论(0编辑  收藏  举报