quick cocos2dx 游戏数据存储

前端之家收集整理的这篇文章主要介绍了quick cocos2dx 游戏数据存储前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

整理一下项目中经常用到的几种数据格式,推荐GameState
1:json数据格式
json->table

@H_502_5@local str = json.encode({a=1,b=2,c={123}}) print(str)

结果 {“a”:1,”c”:[123],”b”:”cc”}
table->json

@H_502_5@local str2 = json.decode('{"a":1,"c":[123],"b":"cc"}') dump(str2)

结果

@H_502_5@[LUA-print] - "<var>" = { [LUA-print] - "a" = 1 [LUA-print] - "b" = "cc" [LUA-print] - "c" = { [LUA-print] - 1 = 123 [LUA-print] - } [LUA-print] - }

2: UserDefault - -支持c++ lua 语言
存储数据

@H_502_5@cc.UserDefault:getInstance():setIntegerForKey("Pass",1) --Integer,Double,Bool,Float,String,cc.UserDefault:getInstance():flush()

在writablePath路径下会生成UserDefault.xml文件
获取数据

@H_502_5@local user_integer = cc.UserDefault:getInstance():getIntegerForKey("Pass")

3 : GameState 只有在cocos2dx-Lua下使用,经常在项目中使用,可以进行加解密、格式化、存储table
(1)导入GameState

@H_502_5@local GameState = import("framework.ui.utils.GameState")

(2)初始化

@H_502_5@GameState.init(function(param) local returnValue = nil if param.errorCode then print("error code" .. param.errorCode) else --crypto if param.name == "save" then local str = json.encode(param.values) str = crypto.encryptXXTEA(str,"abcd")--使用XXT加密算法 returnValue = {data = str} elseif param.name == "load" then local str = crypto.decryptXXTEA(param.values.data,"abcd") returnValue = json.decode(str) end end return returnValue end,"data.txt","abcd") --保存到writablePathdata.txt文件中,加密口令"abcd"

导入数据

@H_502_5@GameData = GameState.load() or {}

导出到文件

@H_502_5@GameData.name = "uud" GameData.age = 10 GameData.level = 15 GameState.save(GameData)

4:FileUtils 在 c++ 或者lua中使用

@H_502_5@cc.FileUtils:getInstance():getString/ValueMap/IntegerFromFile(filePath) cc.FileUtils:getInstance():writeToFile(tb,filePath)

filePath 一定是 cc.FileUtils:getInstance():getWritablePath()返回的路径

猜你在找的Cocos2d-x相关文章