in a game, there are often a lot of monsters, as well as the monster's health, magic values and other attributes of data, which can not be written in the code to die, usually used in the configuration file to save, and then loaded into memory.
Our common configuration file is a CSV file, which is a comma-separated value (comma-separated values), as shown in.
Today, I'm going to introduce a tool class that reads a CSV file--mycsvutil.
Before accepting the Read CSV file tool class, introduce a tool class that reads the string--stringutil.
//header file StringUtil.h#ifndef __stringutil_h_#define __stringutil_h_#include "cocos2d.h"Class Stringutil: Publiccocos2d::ref{ Public:StaticStringutil *getinstance();Virtual BOOLInit ();//Delimiter split character channeling, results stored in a list, object in list is valueCocos2d::valuevector Split (Const Char* Srcstr,Const Char* SSep);Private:StaticStringutil * M_STRINGUTIL;//util is the meaning of the tool! };//Function implementation file#include "StringUtil.h"USING_NS_CC;//InitializeStringutil * Stringutil::m_stringutil = nullptr; Stringutil * Stringutil::getinstance () {if(M_stringutil = = nullptr) {M_stringutil =NewStringutil ();if(M_stringutil && m_stringutil->init ()) {m_stringutil->autorelease (); M_stringutil->retain (); }Else{Cc_safe_delete (m_stringutil); M_stringutil = nullptr; } }returnM_stringutil;}BOOLStringutil::init () { ///split string //auto strslist = stringutil::getinstance ()->split ("zhaolong,want,to,work!", ","); //for (auto str:strslist) //{ //log ("str =%s", str.asstring (). C_STR ()); //} return true;}//Detach function, Srcstr is the string to be detached, SSEP is the delimiter separatorValuevector Stringutil::split (Const Char* Srcstr,Const Char* sSep) {valuevector stringlist;//typedef std::vector<value> valuevector; intSize = strlen (SRCSTR);//Convert data to a string objectValue str = value (SRCSTR);intStartIndex =0;intEndIndex =0; EndIndex = str.asstring (). Find (SSEP); STD::stringLINESTR;//Split string based on delimiter and added to list while(EndIndex >0) {//Split string The purpose of the//SUBSTR function is to return a substring from a given character expression or Memo field. Linestr = Str.asstring (). substr (Startindex,endindex);//Put in listStringlist.push_back (Value (LINESTR));//Update the string to detachstr = Value (str.asstring (). substr (EndIndex +1, size));//Update index numberEndIndex = str.asstring (). Find (SSEP); }///The remainder of the string is also added into the list //If the remaining string is not empty compared to the empty string if(Str.asstring (). Compare ("") !=0) {//Put the string in the listStringlist.push_back (Value (str.asstring ())); }returnStringlist;}#endif
The above string tool class, the main thing is a split function, because it has written enough comments, there is no more explanation. If you want to read the string later, just include the header file, and then call the Split function.
Let's start with the real CSV file read class
We want to better process and save the CSV file data, we should treat it as an object, create a new CSVData class, his class object represents a CSV file data.
//header file CsvData.h#ifndef__csvdata_h_#define__csvdata_h_#include "Cocos2d.h"Class CSVData: PublicCocos2d:: Ref{ Public: Create_func (CSVData); virtual BOOL init ();//Add a row of data voidAddlinedata (cocos2d:: ValuevectorLinedata);//Get data for a rowCocos2d:: ValuevectorGetsinglelinedata (int iLine);//Get row and column sizeCocos2d:: SizeGetrowcolnum ();Private://Data used to store all rows of the CSV fileCocos2d:: ValuevectorM_alllinesvec;};//Function implementation file#include "CsvData.h"Using_ns_cc;bool CSVData:: Init(){return true;}voidCSVData:: Addlinedata(Valuevector Linedata) {M_alllinesvec.Push_back (Value (Linedata));} Valuevector CSVData:: Getsinglelinedata(int iLine) {returnM_alllinesvec.at (ILine).Asvaluevector ();} Size CSVData:: Getrowcolnum() {Size size=Size ();//Get the number of rows in the CSV file because the M_alllinesvec variable holds the data for each row, so the size of the M_alllinesvec is the number of rowsSize.Width=M_alllinesvec.Size ();//If the number of rows in the CSV file is greater than 0 if(Size.Width> 0) {//To find the number of data in the No. 0 row of the CSV fileSize.Height=M_alllinesvec.At0).Asvaluevector ().Size (); }returnSize;}#endif
This csvdata class is relatively simple, needless to say, just pay attention to the getrowcolnum function. This function is to get the size of the CSV file, the number of rows and the number of columns (the line number and the column number are all starting from 0).
Because the CSV file is stored in each row of data, so the size of the CSV is the number of rows, the number of columns required, the CSV file on the No. 0 row of data, the number of columns to get.
Then, then it is really writing the CSV file reading tool Class!
//header file MyCsvUtil.h#ifndef __mycsvutil_h_#define __MYCSVUTIL_H_#include "CsvData.h"classMycsvutil: Publiccocos2d::ref{ Public:StaticMycsvutil * getinstance ();Virtual BOOLInit ();//Load configuration file voidLoadFile (Const Char* spath);//Get the value of a column in a rowCocos2d::value GetValue (intIRow,intIcol,Const Char* Csvfilepath);//Get value and convert to string Const STD::stringGETSTR (intIRow,intIcol,Const Char* Csvfilepath);//Get value and convert to reshape Const intGetInt (intIRow,intIcol,Const Char* Csvfilepath);//Gets the number of rows and columns for the file ConstCocos2d::size GetFileSize (Const Char* Csvfilepath);Private:StaticMycsvutil * MS_CSVUTIL; cocos2d::map<STD::string, CSVData *> M_csvmap;};#endif//Function implementation file#include "MyCsvUtil.h"#include "StringUtil.h"USING_NS_CC; Mycsvutil * Mycsvutil::ms_csvutil =nullptr; Mycsvutil * Mycsvutil::getinstance () {if(Ms_csvutil = =nullptr) {Ms_csvutil =NewMycsvutil ();if(Ms_csvutil && ms_csvutil->init ()) {ms_csvutil->autorelease (); Ms_csvutil->retain (); }Else{Cc_safe_delete (ms_csvutil); Ms_csvutil =nullptr; } }returnMs_csvutil;}BOOLMycsvutil::init () {if(! Tback::init ()) {return false; }return true;}//Load filevoidMycsvutil::loadfile (Const Char* spath) {//object that holds a CSV fileCSVData * CSVData = Csvdata::create ();//Read the data of the file where the path is located, save to the list STD::stringstr = fileutils::getinstance ()->getstringfromfile (spath);//The resulting data will be separated by line breaks and placed in the listValuevector lineslist = stringutil::getinstance ()->split (Str.c_str (),"\ n");//Split the characters of each line (as well as separate them) for(AutoValue:lineslist) {//A string of strings separated by commas, then stored in the list, and finally stored in the CSVData object //In other words, CSVData will become a two-dimensional table that records the string of configuration file rows and columnsValuevector TARR = stringutil::getinstance ()->split (Value.asstring (). C_STR (),","); Csvdata->addlinedata (TARR); }//Add the CSVData object to the dictionaryM_csvmap.insert (spath,csvdata);}//Get file specificationsConstSize Mycsvutil::getfilesize (Const Char* Csvfilepath) {//Take out a two-dimensional table of configuration files AutoCSVData = m_csvmap.at (Csvfilepath);//If the profile does not exist, load the configuration file if(CSVData = =nullptr) {loadFile (Csvfilepath); CSVData = m_csvmap.at (Csvfilepath); }//Call the function of the CSVData classSize size = Csvdata->getrowcolnum ();returnSize;}//Get a column of a row in a fileValue Mycsvutil::getvalue (intIRow,intIcol,Const Char* Csvfilepath) {AutoCSVData = m_csvmap.at (Csvfilepath);if(CSVData = =nullptr) {loadFile (Csvfilepath); CSVData = m_csvmap.at (Csvfilepath); }//Get line IRow dataValuevector rowvector = Csvdata->getsinglelinedata (IRow);//Get column Icol dataValue Colvalue = rowvector.at (Icol);returnColvalue;}//Get a column of a row in a file and convert it to a stringConst STD::stringMYCSVUTIL::GETSTR (intIRow,intIcol,Const Char* Csvfilepath) {Value val = value (); val = GetValue (Icol,icol,csvfilepath);returnVal.asstring ();}//Get a column of a row in a file and convert to an integer typeConst intMycsvutil::getint (intIRow,intIcol,Const Char* Csvfilepath) {Value val = value (); val = GetValue (Irow,icol,csvfilepath);returnVal.asint ();}
Finally, we can include this CSV file in other programs to read the tool class header file, you can use it.
This is the result of my testing in debug mode:
#include "MyCsvUtil.h"/ *------Test Code Snippet-------* /const CHAR*spath= "Monster.csv";//file pathMycsvutil:: getinstance() -LoadFile (spath);//Load file//Get 1th row 1th column dataValue Firstmonstername=Mycsvutil:: getinstance() -GetValue (1,1, spath);//Get 2nd row 1th column dataValue Secmonstername=Mycsvutil:: getinstance() -GetValue (2,1, spath);//Print resultsLog('%s ', Firstmonstername.Asstring ().C_str ());Log('%s ', Secmonstername.Asstring ().C_str ());
Output Result:
Cocos2d-x Learning Note--csv file reading tool