COCOS2DX C + + some practical methods __c++

Source: Internet
Author: User
Tags 04x generator rand response code stringbuffer

1. Get 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. Get the current time stamp

std::string getrawtime () {
    SYSTEMTIME systime;
    Getlocaltime (&systime);
    time_t Unixtime;
    Time (&unixtime);
    std::string rawtime = __string::createwithformat ("%ld%ld", Unixtime, Systime.wmilliseconds)->getCString (); Output UNIX timestamp string
    rawtime.erase (a);
    return rawtime;
}

3. Get file Timestamp

time_t tt;
struct TM *tst;
struct STAT st;
Stat ("D:\\simple.txt", &st);/must use two ' \ '
tt = st.st_ctime;
Log ("tt=%ld\n", TT);

4. Compressed Files

Zip library download link 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. Get Network status

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

6.COCOS2DX Fetch Local Data stream

ssize_t size = 0;
unsigned char* Titlech = fileutils::getinstance ()->getfiledata ("D:/test.png", "R", &size);          

7.COCOS2DX Load network picture data stream

Const char* PSRC = "Network picture data stream";
    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 Generate JSON

#include "json/document.h" #include "json/writer.h" #include "json/stringbuffer.h" #include <iostream> #include

Data/httpconstant.h "using namespace Rapidjson;
Generate JSON Rapidjson::D ocument m_writedoc; M_writedoc.
SetObject (); Rapidjson::D ocument::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 ();
Parse JSON Rapidjson::D ocument writedoc; Writedoc.
SetObject (); Rapidjson::value &value = Writedoc. Parse<kparsedefaultflags> (Str.c_str ()); BOOL result = value["result"]. Getbool ();

9.COCOS2DX HTTP requests

#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::P ost);
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 (!re
    Sponse) {return;
    Long StatusCode = Response->getresponsecode ();
    Log ("Response code:%LD", StatusCode);
        if (StatusCode!=) {log ("response failed");    

        Log ("Error buffer:%s", Response->geterrorbuffer ()); Auto Layer = Tiplayer::cReate ("Get the class two-dimensional code failed");
        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 list data

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 (NULL));////s random number seed
//using Myrandom:
random_shuffle (M_userinfovector.begin (), m_ Userinfovector.end (), p_myrandom);

11. Get Network Connection Status

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

DWORD  flags;//Internet way   
BOOL  m_ Whether the bonline=true;//is online    
m_bonline=isnetworkalive (&flags);    

if (m_bonline)//online    
{    
   if ((Flags & Network_alive_lan) ==network_alive_lan)  
   {  
    cout<< " Online: network_alive_lan\n ";  
   }
   if ((Flags & Network_alive_wan) ==network_alive_wan)   
   {  
    cout<< "online: network_alive_wan\n";  
   }  
   if ((Flags & Network_alive_aol) ==network_alive_aol)    
   {    
    cout<< "online: network_alive_aol\n";   
   }    
}  
else   
   cout<< "not on line \ n";    
}  

12. List Random Sort

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 (NULL));////s random number seed
        //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++ Split substring

std::string tag = "Save12";
std::string str = "Save";
if (Strstr (Tag.c_str (), Str.c_str ()))
{
    std::string s = tag.substr (4);
}

14. Read local data stream

 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 ()); 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.