前言

這篇follow"如何設計遊戲存檔功能",請先看完該篇並成功的實作之後再看這一篇。遊戲需要存檔,如果是單機遊戲就更需要存檔。當我們使用CCUserDefault這個類別時,卻發現有個致命的錯誤。利用這個功能會將資料寫入至UserDefault.xml這個檔案內。當我們將該檔案開啟,就可以看到赤裸裸的資料擺在眼前。

呈前一篇的範例,我們將UserDefault.xml檔案開啟,顯示的資料如下:

<?xml version="1.0" encoding="utf-8"?>
<userDefaultRoot><count>7</count></userDefaultRoot>

就只要看第二行就好,<count>內的count就是我們之前程式碼設定的key。而<count>後面的7則是m_iCount的變數值。

 

若,今天存的資料是遊戲玩家的生命值,或是金錢,這樣隨便一改不就變成作弊啦!請注意,該Android手機有root的話,該檔案是看得到的,不要以為包成apk就沒事情了喔。所以要怎麼解決這個問題呢?雖然COCOS2DX有給了一個好用的加密工具放在你[安裝cocos2dx根目錄]>[cocos]>[2d]內,名稱為base64.h及base64.cpp。有包含Encoder與Decoder的函式。不過目前Encoder只有cocos2dx 3.0以上才支援。本篇文章要介紹的是解決2.1.0或是2.2.0版的狀況,3.0的之後會另外介紹。

 

base64演算法介紹

正在寫..(懶)

 

實作環境

Win32,作業系統Windows7的主機。

Visual C++ 2010 Express。

cocos2dx 版本 2.1.0 beta3

 

 

base64在cocos2dx中的實作 Part1

開始著手進行實作嚕,請開啟之前的專案,我們繼續往下做。

 

step1. 開啟已經編輯過的HelloCpp專案,現在要新增兩個檔案CBase64.cpp與CBase64.h。注意檔案必須放在HelloCpp專案的Class資料夾。

002-01
VC專案樹狀圖

002-02
HelloCpp>Class資料夾

 

step2. 打開瀏覽器(FireFox、Chrome等),搜尋一下"base64 c"關鍵字。就可以找到有人分享的base64演算法實作。

連結 http://jashliao.pixnet.net/blog/post/15379581

 

 

step3. 複製一下程式碼至CBase64.cpp檔案內。整理一下程式,把int main()整段給先給mark起來。

 

step4. 剪下CBase64.cpp上端有兩行宣告,並貼入CBase64.h檔案內。

std::string base64_encode(unsigned char const* , unsigned int len);

std::string base64_decode(std::string const& s);

 

step5. 我們再key一些基本要key的東西,整個CBase64.h最後會變成這樣

#ifndef _CBASE64_
#define _CBASE64_

std::string base64_encode(unsigned char const* , unsigned int len);

std::string base64_decode(std::string const& s);

#endif //_CBASE64_

 

step6. 回到CBase64.cpp,這段程式碼仍有部分錯誤,有些字因為網頁格式關係黏起來了。所以可以透過VC編輯器偵測到哪邊有紅色底線,或是編譯一下把錯的地方修正一下就可以了。

例如 unsignedchar 改成 unsigned char 等...類似錯誤修正。

編譯無誤之後CBase.cpp程式碼大概變成如下:

#include <iostream>
#include <string>

static const std::string base64_chars = 

             "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

             "abcdefghijklmnopqrstuvwxyz"

             "0123456789+/";


//int main() {
//
//  const std::string s = "ADP GmbH\nAnalyse Design & Programmierung\nGesellschaft mit beschrankter Haftung" ;
//
// 
//
//  std::string encoded = base64_encode(reinterpret_cast<constunsignedchar*>(s.c_str()), s.length());
//
//  std::string decoded = base64_decode(encoded);
//
// 
//
//  std::cout << "encoded: " << encoded << std::endl;
//
//  std::cout << "decoded: " << decoded << std::endl;
//
// 
//
//  return 0;
//
//}

 

static inline bool is_base64(unsigned char c) {

  return (isalnum(c) || (c == '+') || (c == '/'));

}

 

std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {

  std::string ret;
  int i = 0;
  int j = 0;
  unsigned char char_array_3[3];
  unsigned char char_array_4[4];


  while (in_len--) {
    char_array_3[i++] = *(bytes_to_encode++);
    if (i == 3) {

      char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;

      char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);

      char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);

      char_array_4[3] = char_array_3[2] & 0x3f;

      for(i = 0; (i <4) ; i++)
        ret += base64_chars[char_array_4[i]];

      i = 0;
    }
  }

 

  if (i)
  {

    for(j = i; j < 3; j++)
      char_array_3[j] = '\0';

    char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;

    char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);

    char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);

    char_array_4[3] = char_array_3[2] & 0x3f;

    for (j = 0; (j < i + 1); j++)
        ret += base64_chars[char_array_4[j]]; 

    while((i++ < 3))
        ret += '=';
    }

    return ret;
}

 

std::string base64_decode(std::string const& encoded_string) {

  int in_len = encoded_string.size();
  int i = 0;
  int j = 0;
  int in_ = 0;

  unsigned char char_array_4[4], char_array_3[3];
  std::string ret;

  while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {

    char_array_4[i++] = encoded_string[in_]; in_++;

    if (i ==4) {

      for (i = 0; i <4; i++)
        char_array_4[i] = base64_chars.find(char_array_4[i]);

      char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
      char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
      char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

      for (i = 0; (i < 3); i++)
        ret += char_array_3[i];

      i = 0;
    }
  }


  if (i) {
    for (j = i; j <4; j++)
      char_array_4[j] = 0;

    for (j = 0; j <4; j++)
      char_array_4[j] = base64_chars.find(char_array_4[j]);

    char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
    char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
    char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

    for (j = 0; (j < i - 1); j++)
        ret += char_array_3[j];
  }

  return ret;
}

如果你編譯通過,表示你已經成功八成了,這時候可以去喝口水休息一下,等一下將會繼續實作。

 

 

base64在cocos2dx中的實作 Part2

開啟HelloWorldScene.cpp,回到我們上次講解的程式,繼續從init()這邊繼續下手。來回顧一下上次的程式碼,紫色部分是我們上次新增的程式碼:

bool HelloWorldB::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !CCLayer::init() )
    {
        return false;
    }
    
    CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
    CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();

    /////////////////////////////
    // 2. add a menu item with "X" image, which is clicked to quit the program
    //    you may modify it.

    // add a "close" icon to exit the progress. it's an autorelease object
    CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
                                        "CloseNormal.png",
                                        "CloseSelected.png",
                                        this,
                                        menu_selector(HelloWorldB::menuCloseCallback));
    
    pCloseItem->setPosition(ccp(origin.x + visibleSize.width - pCloseItem->getContentSize().width/2 ,
                                origin.y + pCloseItem->getContentSize().height/2));

    // create menu, it's an autorelease object
    CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
    pMenu->setPosition(CCPointZero);
    this->addChild(pMenu, 1);

    /////////////////////////////
    // 3. add your codes below...

    // add a label shows "Hello World"
    // create and initialize a label
    
    CCLabelTTF* pLabel = CCLabelTTF::create("Hello World", "Arial", TITLE_FONT_SIZE);
    
    // position the label on the center of the screen
    pLabel->setPosition(ccp(origin.x + visibleSize.width/2,
                            origin.y + visibleSize.height - pLabel->getContentSize().height));

    // add the label as a child to this layer
    this->addChild(pLabel, 1);

    // add "HelloWorldB" splash screen"
    CCSprite* pSprite = CCSprite::create("HelloWorld.png");

    // position the sprite on the center of the screen
    pSprite->setPosition(ccp(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));

    // add the sprite as a child to this layer
    this->addChild(pSprite, 0);

    // 讀取存檔資料
    m_iCount = CCUserDefault::sharedUserDefault()->getIntegerForKey("count",0);

    m_iCount++;

    // 寫入存檔資料
    CCUserDefault::sharedUserDefault()->setIntegerForKey("count",m_iCount);

    // 更新(完成寫檔)
    CCUserDefault::sharedUserDefault()->flush();

    // 印出來
    CCLog("m_iCount = %d",m_iCount);
    
    return true;
}

 

step1. CBase.cpp先新增標頭檔

#include "HelloWorldScene1_2.h"
#include "AppMacros.h"
#include <CCUserDefault.h>
#include "CBase64.h"

 

step2. 回到init(),我們想要先把"count"這個key給編碼,之後就只會使用編碼過後的key,就不會再使用原本的"count"

    // key 的編碼
    const std::string s = "count";
    std::string key_en = base64_encode(reinterpret_cast<const unsigned char*>(s.c_str()), s.length());

    CCLog("string before encoder %s", s.data());
    CCLog("string after encoder %s",key_en.data());

key_en這個變數存放的就是編碼過後的"count"。後面兩行只是顯示編碼前與編碼後的內容。

這時候來小小編譯一下,得出來的結果如下圖:

002-04  

count 就是編碼前的字串,Y291bnQ=是編碼後的字串。哈哈,這樣就達到我第一步目標啦!

 

step3. 修改 讀取存檔資料 這行程式。

把"count"替換成 key_en.data(),修改後如下..

    // 讀取存檔資料
    m_iCount = CCUserDefault::sharedUserDefault()->getIntegerForKey(key_en.data(),0);

 

step4. 修改 寫入存檔資料 這行程式

把"count"替換成 key_en.data(),修改後如下..

    // 寫入存檔資料
    CCUserDefault::sharedUserDefault()->setIntegerForKey(key_en.data(),m_iCount);

 

step5. 差不多了,可以run看看嚕!把UserDefault.xml砍掉我們重新run一次吧!

結果如下,很好,m_iCount是1

002-05  

 

再看看UserDefault.xml吧,非常好,這樣就看不出來內容的意義為何啦!

<?xml version="1.0" encoding="utf-8"?>
<userDefaultRoot><Y291bnQ=>1</Y291bnQ=></userDefaultRoot>

 

再run第二遍我們看看,結果是....

002-06  

糟了!怎麼結果run出來跟第一次一樣呢!?囧爆了!

 

 

base64在cocos2dx中的實作 Part3

至於發生問題的理由目前我還沒有詳細查出,等我稍微研究一下再跟大家分享。目前解決方法提供一下,我修改了一下key的內容,由原本的"count"改變成為"count+"。編碼之後key_en會變成"Y91bnQr"。同樣我們run兩遍,第二次的結果如下:

002-07

 

呼!結果終於正常了,阿麵!

 

整個程式碼參考如下:

bool HelloWorldB::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !CCLayer::init() )
    {
        return false;
    }
    
    CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
    CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();

    /////////////////////////////
    // 2. add a menu item with "X" image, which is clicked to quit the program
    //    you may modify it.

    // add a "close" icon to exit the progress. it's an autorelease object
    CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
                                        "CloseNormal.png",
                                        "CloseSelected.png",
                                        this,
                                        menu_selector(HelloWorldB::menuCloseCallback));
    
    pCloseItem->setPosition(ccp(origin.x + visibleSize.width - pCloseItem->getContentSize().width/2 ,
                                origin.y + pCloseItem->getContentSize().height/2));

    // create menu, it's an autorelease object
    CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
    pMenu->setPosition(CCPointZero);
    this->addChild(pMenu, 1);

    /////////////////////////////
    // 3. add your codes below...

    // add a label shows "Hello World"
    // create and initialize a label
    
    CCLabelTTF* pLabel = CCLabelTTF::create("Hello World", "Arial", TITLE_FONT_SIZE);
    
    // position the label on the center of the screen
    pLabel->setPosition(ccp(origin.x + visibleSize.width/2,
                            origin.y + visibleSize.height - pLabel->getContentSize().height));

    // add the label as a child to this layer
    this->addChild(pLabel, 1);

    // add "HelloWorldB" splash screen"
    CCSprite* pSprite = CCSprite::create("HelloWorld.png");

    // position the sprite on the center of the screen
    pSprite->setPosition(ccp(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));

    // add the sprite as a child to this layer
    this->addChild(pSprite, 0);

    //-------------------------
    // UserDefault 功能

    // key 的編碼
    const std::string s = "count+";
    std::string key_en = base64_encode(reinterpret_cast<const unsigned char*>(s.c_str()), s.length());
    CCLog("string before encoder %s", s.data());
    CCLog("string after encoder %s",key_en.data());

    // 讀取存檔資料
    m_iCount = CCUserDefault::sharedUserDefault()->getIntegerForKey(key_en.data(),0);

    m_iCount++;

    // 寫入存檔資料
    CCUserDefault::sharedUserDefault()->setIntegerForKey(key_en.data(),m_iCount);

    // 更新(完成寫檔)
    CCUserDefault::sharedUserDefault()->flush();

    // 印出來
    CCLog("m_iCount = %d",m_iCount);
    
    return true;
}

 

 

 

 

arrow
arrow

    巴比特 發表在 痞客邦 留言(0) 人氣()