Cocos2dx3.2 develop RPG Flighting (3) to load required data from an Excel table, cocos2dx3.0label

Source: Internet
Author: User

Cocos2dx3.2 develop RPG Flighting (3) to load required data from an Excel table, cocos2dx3.0label

I. Preface

In a game, the data that needs to be used is generally provided by game planning (the planning here is done by myself ). What is the data needed? For example, I create A Role A and A have their own attack capabilities, defensive capabilities, speed, etc. Then I create another role B and B also have their own attack capabilities, defensive capabilities, and speed. Each role has some basic attributes, but different roles may have different attribute values. We cannot write the data into the code. The best way is to read data from a file (usually an Excel table) to facilitate management and modification.

Ii. Text

1. Excel

Four Excel tables are used in the Flighting game (which can be found in the excel folder of Resource ).

HeroMessage: Attributes of different heroes

MonsterMessage: corresponding to the attributes of different monsters

SkillMessage: Attributes corresponding to different skills

StageMessage: Attributes of different levels

The basic format of an Excel table is as follows:


The format is very simple. You can see what is going on.


2. Next we will use HeroMessage as an example to perform the following operations.

We have prepared the Excel tables we need, and now our goal is to save the information of the tables with objects (beans.

Here I also use the data editor provided by cocostuio. The general idea is as follows: first use the cocostudio data editor to convert an excel table into a JSON string.

Read and parse the string in the code, and save the data information with an object for convenient management.

Step 1: use the data editor

Open cocostudio1.6 and select Data Manager> File> Import template table> Excel

After the import

File-export JSON file-OK

If it succeeds, you will get a json file, which can be opened in notepad.

Next we will make the following modifications, adding the previous line of the string:

{"Json":

Add the following line to the string:

}

If you are not clear, you can see the figure: before modification:

After modification:

People who know json may know why it is. It doesn't matter if they don't understand it. Just do it first.


Step 2: Construct the corresponding information storage class (bean) in the code)

HeroMessage. h

# Ifndef _ HEROMESSAGE_H _ # define _ HEROMESSAGE_H _ # include <string> using namespace std; class HeroMessage {public: int id; // unique idstring name; // role name string r_name; // bone animation Resource Name string r_png; // bone animation pngstring r_plist; // bone animation pliststring r_ExportJson; // bone animation ExportJsonint offset_x; // x offset int offset_y; // y offset int atk_dis; // attack distance int hp; // life value int atk; // attack power int def; // defense power int speed; // movement speed double atk_speed; // Attack Speed bool naima; // whether it is a priest string bullet; // The bullet Resource Name int skill; // the corresponding skill id}; # endif

Step 3: Information Conversion Tool HeroMessageUtil

HeroMessageUtil is responsible for reading the Json file and loading the corresponding information. Save it with HeroMessage

#ifndef _HMUTIL_H_#define _HMUTIL_H_#include "HeroMessage.h"#include "json/rapidjson.h"#include "json/document.h"#include "cocos2d.h"#include <map>using namespace cocos2d;class HeroMessageUtil{public:static HeroMessageUtil* getInstance();HeroMessage getMessageById(int id);map<int,HeroMessage> getHeroMessageMap();HeroMessageUtil();~HeroMessageUtil();private:void initHeroMsgMap();private:static HeroMessageUtil* m_instance;map<int,HeroMessage> heroMsgMap;};#endif

It can be seen that in addition to the singleton method, constructor and destructor, there are three functions and one member variable.

1. map <int, HeroMessage> heroMsgMap; this is a map. The key is the unique id of the hero and the value is the corresponding information object.

2. HeroMessage getMessageById (int id); get all the information of a hero through the id of a hero
Map <int, HeroMessage> getHeroMessageMap (); get the map of the hero Information

3. void initHeroMsgMap (); initialize the hero information class, which will be called in the constructor

HeroMessageUtil::HeroMessageUtil(){initHeroMsgMap();}


Therefore, we focus on void initHeroMsgMap ()

void HeroMessageUtil::initHeroMsgMap(){std::string  jsonStr = cocos2d::FileUtils::getInstance()->getStringFromFile("Json/HeroMessage.json");rapidjson::Document _mDoc;std::string mstr = jsonStr;RETURN_IF(NULL==mstr.c_str()||!mstr.compare(""));_mDoc.Parse<0>(mstr.c_str());RETURN_IF(_mDoc.HasParseError()||!_mDoc.IsObject());const rapidjson::Value &pArr = _mDoc["json"];CCLOG("Size = %d",pArr.Capacity());for(int i=0;i<pArr.Capacity();++i){HeroMessage h;const rapidjson::Value &temp = pArr[i];int id = temp["id"].GetInt();h.id = temp["id"].GetInt();h.name = temp["name"].GetString();h.r_name = temp["r_name"].GetString();h.r_png = temp["r_png"].GetString();h.r_plist = temp["r_plist"].GetString();h.r_ExportJson = temp["r_ExportJson"].GetString();h.offset_x = temp["offset_x"].GetInt();h.offset_y = temp["offset_y"].GetInt();h.atk_dis = temp["atk_dis"].GetInt();h.hp = temp["hp"].GetInt();h.atk = temp["atk"].GetInt();h.def = temp["def"].GetInt();h.speed = temp["speed"].GetInt();h.atk_speed = temp["atk_speed"].GetDouble();int b = temp["naima"].GetInt();h.naima = b==0?false:true;h.bullet = temp["bullet_img"].GetString();h.skill = temp["skill"].GetInt();heroMsgMap.insert(make_pair(id,h));CCLOG("h : %s",h.r_png.c_str());}CCLOG("MapSize = %d",heroMsgMap.size());return;}
Here we use the rapidJson api, which is already available in the cocos2dx additional library. Therefore, we only need to introduce the following two header files.

#include "json/rapidjson.h"#include "json/document.h"

std::string  jsonStr = cocos2d::FileUtils::getInstance()->getStringFromFile("Json/HeroMessage.json");
Read the "Json/HeroMessage. json" file and convert it into a string

rapidjson::Document _mDoc;
_ MDoc is a Document object. It can be understood as a container for the moment.

_mDoc.Parse<0>(mstr.c_str());
Convert the string read from the json file into a Document Object

const rapidjson::Value &pArr = _mDoc["json"];
Read the value of the json object corresponding to _ mDoc whose key is "json" and save it in the pArr object (remember the modification to the json file just now, now, the pArr object actually contains important data)


The next for loop is used to traverse a row of data. (PArr. Capacity can be used to obtain the number of objects contained in the pArr object)

HeroMessage h; const rapidjson: Value & temp = pArr [I]; // The current row is also a Value object. Use temp to save int id = temp ["id"]. getInt (); // temp ["id"] indicates that the search key value from the value object is "id", and the GetInt method is converted to inth. id = temp ["id"]. getInt (); // Save the parsed int to our destination -- HeroMessage

After constructing the HeroMessage object, remember to put it in the map.

heroMsgMap.insert(make_pair(id,h));

In this way, the data of one row in the excel table is put into a map.


Finally, paste HeroMessageUtil in two common methods:

map<int,HeroMessage> HeroMessageUtil::getHeroMessageMap(){return heroMsgMap;}HeroMessage HeroMessageUtil::getMessageById(int id){auto it =  heroMsgMap.find(id);CCASSERT(it!=heroMsgMap.end(),"can't get hero msg of the id");return (*it).second;}

This section ends.


My csdn address: http://blog.csdn.net/hezijian22

Email Address: 578690286@qq.com

If you have any questions or suggestions, please feel free to contact me. Thank you.



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.