cocos2dx C++一些实用方法

1.获取GUID

const char* newGUID()
{
     static char buf[64] = { 0 };
     GUID guid;
     if (S_OK == ::CoCreateGuid(&guid))
         {
          _snprintf(buf, sizeof(buf)
            , "%08X-%04X-%04x-%02X%02X-%02X%02X%02X%02X%02X%02X"
            , guid.Data1
            , guid.Data2
            , guid.Data3
            , guid.Data4[0], guid.Data4[1]
            , guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5]
            , guid.Data4[6], guid.Data4[7]
            );
         }
     return (const char*)buf;
}

2.获取当前时间戳

std::string getRawTime() {
    SYSTEMTIME sysTime;
    GetLocalTime(&sysTime);
    time_t unixTime;
    time(&unixTime);
    std::string rawTime = __String::createWithFormat("%ld%ld", unixTime, sysTime.wMilliseconds)->getCString();//输出UNIX时间戳字符串
    rawTime.erase(10);
    return rawTime;
}

3.获取文件时间戳

time_t tt;
struct tm *tst;
struct stat st;
stat("D:\\simple.txt", &st);//必须使用两个'\\'
tt = st.st_ctime;
log("tt=%ld\n", tt);

4.压缩文件

zip库下载链接 http://download.csdn.net/detail/chinawallace/9584122
HZIP hz = CreateZip(L"C:\\simple1.zip",0);
ZipAdd(hz, L"simple.txt", L"C:\\simple.txt");
CloseZip(hz);

5.获取网络状态

#include <Sensapi.h> 
#pragma comment(lib, "Sensapi.lib")
DWORD flags;
IsNetworkAlive(&flags);

6.cocos2dx获取本地数据流

ssize_t size = 0;
unsigned char* titlech = FileUtils::getInstance()->getFileData("D:/test.png", "r", &size);          

7.cocos2dx加载网络图片数据流

const char* pSrc = "网络图片数据流";
    unsigned char *pData = (unsigned char*)(const_cast<char*>(pSrc));
    auto pDataLen = strlen((const char*)pData);

    std::string load_str;
    load_str = std::string((const char*)pData, pDataLen);

    int len = 0;
    unsigned char *buffer1;
    len = base64Decode((unsigned char*)load_str.c_str(), (unsigned int)load_str.length(), &buffer1);

    Image* img = new Image();
    bool ok = img->initWithImageData(buffer1, len);

    unsigned char *pngData = img->getData();

    CCTexture2D *texture = new CCTexture2D();
    texture->initWithData(pngData, img->getDataLen(), kCCTexture2DPixelFormat_RGB888,
        img->getWidth(), img->getHeight(), CCSizeMake((float)img->getWidth(), (float)img->getHeight()));
    sprite->initWithTexture(texture);

8.cocos2dx生成json

#include "json/document.h"
#include "json/writer.h"
#include "json/stringbuffer.h"
#include <iostream>
#include "data/HttpConstant.h"
using namespace rapidjson;

//生成json
rapidjson::Document m_writedoc;
m_writedoc.SetObject();
rapidjson::Document::AllocatorType& allocator = m_writedoc.GetAllocator();
rapidjson::Value object(rapidjson::kObjectType);
m_writedoc.RemoveAllMembers();

rapidjson::Value gradeId(rapidjson::kStringType);
gradeId.SetString("45014d74cce3469b86ace39cf2025de6", allocator);
object.AddMember("gradeId", gradeId, allocator);

rapidjson::Value validation(rapidjson::kStringType);
validation.SetString("123", allocator);
object.AddMember("validation", validation, allocator);

StringBuffer buffer;
rapidjson::Writer<StringBuffer> writer(buffer);
object.Accept(writer);
std::string strSendMessage = buffer.GetString();

//解析json
rapidjson::Document writedoc;
writedoc.SetObject();
rapidjson::Value &value = writedoc.Parse<kParseDefaultFlags>(str.c_str());
bool result = value["result"].GetBool();

9.cocos2dx的Http请求

#include "network/HttpClient.h"
using namespace network;

HttpRequest* request = new (std::nothrow) HttpRequest();
request->setUrl("http://192.168.1.7:8080/lesiea/game/drumsData");
request->setRequestType(HttpRequest::Type::POST);
request->setResponseCallback(CC_CALLBACK_2(CourseSelectClassA1Layer::onHttpRequestCompleted, this));
std::vector<std::string> headers;
headers.push_back("Content-Type: application/json; charset=utf-8");
request->setHeaders(headers);

request->setTag("test");
HttpClient::getInstance()->send(request);
request->release();

void onHttpRequestCompleted(cocos2d::network::HttpClient *sender, cocos2d::network::HttpResponse *response)
{
    if (!response)
    {
        return;
    }
    long statusCode = response->getResponseCode();
    log("response code: %ld", statusCode);
    if (statusCode != 200)
    {
        log("response failed");
        log("error buffer: %s", response->getErrorBuffer());    

        auto layer = TipLayer::create("获取班级二维码失败");
        this->addChild(layer, 100, 100);
        return;
    }
    else
    {
        std::string tag = response->getHttpRequest()->getTag();
        std::vector<char> *buffer = response->getResponseData();
        std::string str;
        for (unsigned int i = 0; i < buffer->size(); i++)
        {
            str += (*buffer)[i];
        }
        log("%s", str);
    }
}

10.随机列表数据

// random generator function:
ptrdiff_t myrandom(ptrdiff_t i) { return rand() % i; }
// pointer object to it:
ptrdiff_t(*p_myrandom)(ptrdiff_t) = myrandom;
srand(unsigned(time(NULL)));s随机数种子
// using myrandom:
random_shuffle(m_userInfoVector.begin(), m_userInfoVector.end(), p_myrandom);

11.获取网络连接状态

#include <Sensapi.h> 
#pragma comment(lib, "Sensapi.lib")

DWORD  flags;//上网方式   
BOOL  m_bOnline=TRUE;//是否在线    
m_bOnline=IsNetworkAlive(&flags);    

if(m_bOnline)//在线    
{    
   if ((flags & NETWORK_ALIVE_LAN) ==NETWORK_ALIVE_LAN)  
   {  
    cout<<"在线:NETWORK_ALIVE_LAN\n";  
   }
   if ((flags & NETWORK_ALIVE_WAN) ==NETWORK_ALIVE_WAN)   
   {  
    cout<<"在线:NETWORK_ALIVE_WAN\n";  
   }  
   if ((flags & NETWORK_ALIVE_AOL) ==NETWORK_ALIVE_AOL)    
   {    
    cout<<"在线:NETWORK_ALIVE_AOL\n";   
   }    
}  
else   
   cout<<"不在线\n";    
}  

12.列表随机排序

// random generator function:
ptrdiff_t myrandom(ptrdiff_t i) { return rand() % i; }

// pointer object to it:
ptrdiff_t(*p_myrandom)(ptrdiff_t) = myrandom;

srand(unsigned(time(NULL)));s随机数种子
        // using myrandom:
        random_shuffle(m_userInfoVector.begin(), m_userInfoVector.end(), p_myrandom);
        for (int i = 0; i < m_userInfoVector.size(); i++)
        {
            m_userInfoVector.at(i)->setIndex(i+1);
            m_pHeadVector.at(i)->initWithFile(m_userInfoVector.at(i)->getUserIcon());
        }   

13.c++分割子串

std::string tag = "save12";
std::string str = "save";
if (strstr(tag.c_str(), str.c_str()))
{
    std::string s = tag.substr(4);
}

14.读取本地数据流

    ssize_t size = 0;
    unsigned char* titlech = FileUtils::getInstance()->getFileData(path, "rb+", &size);

    auto pDataLen = strlen((const char*)titlech);

    std::string load_str;
    load_str = std::string((const char*)titlech, pDataLen);
    log("data=%s", load_str.c_str());

    std::string load_str;

    auto data = FileUtils::getInstance()->getDataFromFile(path);
    unsigned char* titlech = data.getBytes();
    auto pDataLen = strlen((const char*)titlech);

    load_str = std::string((const char*)titlech, pDataLen);
    log("data=%s", load_str.c_str());

    fstream fsIn;

    char s[65535];
    fsIn.open(path.c_str(), ios::in | ios::binary);

    fsIn.read(s, 65535);
    fsIn.close();

    char* c = s;
    std::string str = c;
    log("%s", str.c_str());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Cocos2d-x实战:C++卷》[1] 系统论述了Cocos2d-x游戏开发理论与实践。全书内容涵盖了Cocos2d-x的核心类、瓦片地图、物理引擎、音乐音效、数据持久化、网络通信、数据交换格式、内存管理、性能优化、平台移植、程序代码管理、三大应用商店发布产品等。本书共29章,按内容结构可分为六篇: 第一篇开发基础,即第2章~第8章,内容包括Cocos2d-x简介、环境搭建、字符串、标签、菜单、精灵、场景、层、动作、特效、动画和Cocos2d-x用户事件。 第二篇开发进阶,即第9章~第12章,内容包括游戏音乐与音效、粒子系统、瓦片地图和物理引擎。 第三篇数据与网络,即第13章~第17章,内容包括Cocos2d-x中使用的数据容器类、数据持久化、数据交换格式、基于HTTP网络通信和基于Node.js的Socket.IO网络通信。 第四篇设计与优化,即第18章~第20章,内容包括Cocos2d-x中的常用设计模式、Cocos2d-x中的内存管理和性能优化。 第五篇平台移植,即第21章~第23章,内容包括从Win32到Android平台的移植、从Win32到WindowsPhone8平台的移植和从Win32到iOS平台的移植。 第六篇开发实战,即第24章~第29章,内容包括使用Git管理程序代码和多个项目实战——迷失航线手机游戏项目开发、为迷失航线游戏添加广告、发布放到Googleplay应用商店、发布放到WindowsPhone应用商店和发布放到苹果AppStore。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值