Cocos2d-x   发布时间:2022-05-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了cocos2d-x中使用sqlite大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

在单机游戏中有几十个场景道具,每一个都有各自的状态(获得、未获得、获得个数)等等,如果在游戏中平凡涉及到这些道具的实时存储,那么使用文本就会稍慢、可以使用SQLite数据库来完成。

下载地址:http://www.sqlite.org/download.html

下载后,在项目中导入sqlite3.csqlite3.h两个文件即可。

附上使用代码:(如果表不存在,创建两个表、存储两种道具,再获取两个表中的数据)

        #include "sqlite/sqlite3.h"
      m_pDb = NULL; //sqlite3 *m_pDb; String path = "infor\\data.db"; //创建的txt文本,随便改个后缀名 #if CC_TARGET_PLATFORM != CC_PLATFORM_WIN32 path = CCFileUtils::sharedFileUtils()->getWritablePath()+"infor\\data.db"; #endif CCString sql; int result; result = sqlite3_open(path.c_str(),&m_pDb); if(result != @R_47_5607@OK) { CCLog("open database failed,number%d",result); m_pDb = NULL; return; } // Help map sql = "create table Help_map(ID INTEGER PRIMARY KEY,count IntegeR DEFAULT 0)"; result = sqlite3_exec(m_pDb,sql.getCString(),NULL,null); if(result != @R_47_5607@OK) CCLog("create table failed"); for (int i=0; i<100; ++i) { sql.initWithFormat("insert into Help_map values(%d,0)",i+1); result = sqlite3_exec(m_pDb,null); if(result != @R_47_5607@OK) CCLog("insert data failed!"); } // special tool sql = "create table special_tool(ID INTEGER PRIMARY KEY,state IntegeR DEFAULT 0,null); if(result != @R_47_5607@OK) CCLog("create table failed"); for (int i=0; i<20; ++i) { sql.initWithFormat("insert into special_tool values(%d,null); if(result != @R_47_5607@OK) CCLog("insert data failed!"); } //SELEct char **re; int r,c; { //第3个参数是查询结果,它依然一维数组(不要以为是二维数组,更不要以为是三维数组)。 //它内存布局是:第一行是字段名称,后面是紧接着是每个字段的值 // col个数据之后才是表数据,之前的是列名字 result = sqlite3_get_table(m_pDb,"SELEct * from Help_map",&re,&r,&c,null); CCLog("Help_map: row is %d,column is %d",r,c); m_HelpMap.clear(); for (int i=0; i< 100; ++i) { CCLog("row %d ---> id = %s,count = %s",i+1,re[c + i*c],re[c + i*c +1]); int val = CCString(re[c + i*c +1]).intValue(); m_HelpMap.push_BACk(val); } sqlite3_free_table(rE); } { result = sqlite3_get_table(m_pDb,"SELEct * from special_tool",null); CCLog("special_tool row is %d,c); m_specialItemState.clear(); m_specialItem.clear(); for (int i=0; i< 20; ++i) { CCLog("row %d ---> id = %s,state = %s,re[c + i*c +1],re[c + i*c + 2]); int val = CCString(re[c + i*c +1]).intValue(); m_specialItemState.push_BACk(val); val = CCString(re[c + i*c +2]).intValue(); m_specialItem.push_BACk(val); } sqlite3_free_table(rE); }

其实在程序中存储道具用的vector可以换成一个hash表,因为表中元素的主键是线性增长的,这样访问每个元素的时间复杂度仅o(1)

data.db(创建的数据库文件)里面插入数据后,想看一下有些什么数据、或者策划人员负责维护里面的数据表,可以下载sqlite database browser,一个非常不错的浏览sqlite数据库的工具。

下载地址:http://sourceforge.net/projects/sqlitebrowser/

大佬总结

以上是大佬教程为你收集整理的cocos2d-x中使用sqlite全部内容,希望文章能够帮你解决cocos2d-x中使用sqlite所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。