예제 #1
0
ValueMap User::saveModel()
{
	ValueMap model;

	ValueVector achieves;
	for(auto pair:_achieves)
	{
		achieves.push_back(cocos2d::Value(pair));
	}
	model["achieves"] = achieves;

	ValueVector buffs;
	for(auto pair:_buffs)
	{
		buffs.push_back(cocos2d::Value(pair->saveModel()));
	}
	model["buffs"] = buffs;

	ValueVector shareRewardsLock;
	for(int i = 0; i < 3; i++)
	{
		shareRewardsLock.push_back(cocos2d::Value(_shareRewardsLock[i]));
	}
	model["shareRewardsLock"] = shareRewardsLock;

	model["firstOpen"] = int(_firstOpen);

	model["shareRewardOpen"] = int(_shareRewardOpen);

	model["shareRewardOpenFirst"] = int(_shareRewardOpenFirst);
	return model;
	
}
예제 #2
0
bool CCBReader::readSoundKeyframesForSeq(CCBSequence* seq) {
    int numKeyframes = readInt(false);
    if(!numKeyframes) return true;

    CCBSequenceProperty* channel = new (std::nothrow) CCBSequenceProperty();
    channel->autorelease();

    for(int i = 0; i < numKeyframes; ++i) {

        float time = readFloat();
        std::string soundFile = readCachedString();
        float pitch = readFloat();
        float pan = readFloat();
        float gain = readFloat();

        ValueVector vec;
        vec.push_back(Value(soundFile));
        vec.push_back(Value(pitch));
        vec.push_back(Value(pan));
        vec.push_back(Value(gain));

        CCBKeyframe* keyframe = new (std::nothrow) CCBKeyframe();
        keyframe->setTime(time);
        keyframe->setValue(Value(vec));
        channel->getKeyframes().pushBack(keyframe);
        keyframe->release();
    }

    seq->setSoundChannel(channel);

    return true;
}
예제 #3
0
void PlotScript::dispatchAll(const char* str)
{
	// 脚本初始化
	ValueVector triggerOn;
	ValueVector vec1;
	stringToValueVector(std::string(str),"###",vec1);
	for (auto i:vec1)
	{
		ValueVector vec2;
		stringToValueVector(i.asString(),"~~~",vec2);
		if(vec2.size() < 2)
		{
			vec2.push_back(cocos2d::Value(""));
		}
		triggerOn.push_back(cocos2d::Value(vec2));
	}

	for(auto trigger:triggerOn)
	{
		auto vec = trigger.asValueVector();
		ValueMap map;
		stringToValueMap(vec.at(0).asString(),map);
		if(map["target"].asString() == "player")
		{
			map["target"] = Detect::shareDetect()->getPlayer()->getName();
		}
		EventHelper::getInstance()->dispatchByStr(valueMapToString(map),vec.at(1).asString());
	}   
}
예제 #4
0
// 查询数据库
ValueVector DBManager::executeQuery(std::string sql)
{
    ValueVector v;

    if (open()) {
        char** table;   // 查询结果
        int r, c;       // 行数、列数
        
        sqlite3_get_table(_pdb, sql.c_str(), &table, &r, &c, nullptr);
        
        // 第0行(0 ~ c-1),为字段名
        // 第1~r行(c ~ 2*c-1),第一条记录
        for(int i = 0; i <= r; i++) {
            ValueMap map;
            for(int j = 0; j < c; j++) {
//                CCLOG("%s", table[i * c + j]);
                map[table[j]] = table[i * c + j];
            }
            v.push_back((Value)map);
        }
        
        // 记得释放查询表
        sqlite3_free_table(table);
    }
    
    return v;
}
예제 #5
0
Value DataUtil::getAll(std::string sql){
    char **re;
    int r, c, res;
    char* errMsg;
    ValueVector all;
    res = sqlite3_get_table(pDB, sql.c_str(), &re, &r, &c, &errMsg);
    if (res != SQLITE_OK){
        CCLOG("select table all failed, number:%d, msg:%s, sql:%s", res, errMsg, sql.c_str());
        Director::getInstance()->getEventDispatcher()->dispatchCustomEvent(errMsg, &res);
        return Value(all);
    }
    int i, j;
    ValueVector vec;
    for (i = 1; i <= r; i++){
        ValueMap map;
        for (j = 0; j<c; j++){
            std::string k(re[j]);
            Value v(re[i * c + j]);
            map[k] = v;
        }
        vec.push_back(Value(map));
    }
    sqlite3_free_table(re);
    all = vec;
    return Value(all);
}
예제 #6
0
파일: SQLite.cpp 프로젝트: hustg4/CocosLua
cocos2d::ValueVector SQLite::executeQuery(const std::string &sql)
{
    CCLOG("SQLite:%s",sql.c_str());
    ValueVector valueArray;
    sqlite3_stmt* stmt = NULL;
    
    bool res = sqlite3_prepare(db, sql.c_str(), -1, &stmt, NULL) == SQLITE_OK;
    if (res) {
        while (sqlite3_step(stmt) == SQLITE_ROW ) {
            ValueMap columnMap;
            int columnNum = sqlite3_column_count(stmt);
            for (int i = 0; i < columnNum; i++) {
                int type = sqlite3_column_type(stmt, i);
                
                const char* name = sqlite3_column_name(stmt, i);
                
                if (type == SQLITE_INTEGER) {
                    columnMap[name]=Value(sqlite3_column_int(stmt, i));
                }else if (type == SQLITE_FLOAT){
                    columnMap[name]=Value(sqlite3_column_int(stmt, i));
                }else if (type == SQLITE_TEXT){
                    columnMap[name]=Value((char*)sqlite3_column_text(stmt, i));
                }else{
                    columnMap[name] = "";
                }
            }
            valueArray.push_back(Value(columnMap));
        }
        sqlite3_finalize(stmt);
    }
    
    return valueArray;
}
예제 #7
0
//查询所有数据方法
ValueVector NoteDAO::findAll()
{
	//初始化数据库
	initDB();
	sqlite3* db= NULL;

	string path = dbDirectoryFile();
	ValueVector listData;

	if (sqlite3_open(path.c_str(), &db) != SQLITE_OK) {
		sqlite3_close(db);
		CCASSERT(false, "DB open failure.");
	} else {
		string qsql = "SELECT cdate,content FROM Note";
		sqlite3_stmt *statement;
		//预处理过程
		if (sqlite3_prepare_v2(db, qsql.c_str(), -1, &statement, NULL) == SQLITE_OK) {
			//执行
			while (sqlite3_step(statement) == SQLITE_ROW) {

				char *cdate = (char *)sqlite3_column_text(statement, 0);
				char *content = (char *)sqlite3_column_text(statement, 1);

				ValueMap dict ;
				dict["date"] = Value(cdate);
				dict["content"] = Value(content);

				listData.push_back(Value(dict));
			}
		}
		sqlite3_finalize(statement);
		sqlite3_close(db);
	}
	return listData;
}
예제 #8
0
파일: FactBase.cpp 프로젝트: doveiya/isilme
	void FactBase::AddFact( ValuePtr a1, ValuePtr a2 )
	{
		ValueVector v;
		v.push_back(a1);
		v.push_back(a2);
		AddFact(v);
	}
예제 #9
0
int PlotScript::delayDispatch(lua_State* ls)
{
	const char *luaStr = lua_tostring(ls, 1);
	float delay = lua_tointeger(ls, 2);
	const char *curDelName = lua_tostring(ls, 3);

	ValueVector *vec = new ValueVector();
	vec->push_back(cocos2d::Value(luaStr));
	vec->push_back(cocos2d::Value(curDelName));

	auto scene = Director::getInstance()->getRunningScene();

	auto action = Sequence::create(DelayTime::create(delay),CCCallFuncND::create(scene,callfuncND_selector(PlotScript::delayCallBack),(void*)vec),NULL);
	scene->runAction(action);
	PlotScript::sharedHD()->delayCount++;

	return 1;
}
예제 #10
0
void htmInterface::fillValueVec(HtmRange &hr, ValueVector &vec)
{
	htmRange ran;
	vec.clear();
	hr.reset();
	while(hr.getNext( (Key &) ran.lo, (Key &) ran.hi)){
	  vec.push_back(ran);
	}	
}
예제 #11
0
SnapshotPtr ExpDecaySample::getSnapshot() const {
    ValueVector vals;
    vals.reserve(values_.size());
    std::lock_guard<std::mutex> rlock(mutex_);
    for(Double2Int64Map::const_iterator it = values_.begin(); it !=  values_.end(); ++it) {
    	vals.push_back(it->second);
    }
    return SnapshotPtr(new Snapshot(vals));
}
예제 #12
0
void Menu::alignItemsInRows(int rows, va_list args)
{
    ValueVector array;
    while (rows)
    {
        array.push_back(Value(rows));
        rows = va_arg(args, int);
    }
    alignItemsInRowsWithArray(array);
}
예제 #13
0
Value NDKHelper::getValueFromJson(json_t *obj)
{
    if (obj == NULL) {
        return Value::Null;
    }

    if (json_is_object(obj)) {
        ValueMap valueMap;

        const char *key;
        json_t *value;

        void *iter = json_object_iter(obj);
        while (iter) {
            key = json_object_iter_key(iter);
            value = json_object_iter_value(iter);

            valueMap[key] = NDKHelper::getValueFromJson(value);

            iter = json_object_iter_next(obj, iter);
        }

        return Value(valueMap);
    } else if (json_is_array(obj)) {
        ValueVector valueVector;

        size_t sizeArray = json_array_size(obj);

        for (unsigned int i = 0; i < sizeArray; i++) {
            valueVector.push_back(NDKHelper::getValueFromJson(json_array_get(obj, i)));
        }

        return Value(valueVector);
    } else if (json_is_boolean(obj)) {
        if (json_is_true(obj)) {
            return Value(true);
        } else {
            return Value(false);
        }
    } else if (json_is_integer(obj)) {
        int value = (int) json_integer_value(obj);

        return Value(value);
    } else if (json_is_real(obj)) {
        double value = json_real_value(obj);

        return Value(value);
    } else if (json_is_string(obj)) {
        std::string value = json_string_value(obj);

        return Value(value);
    }

    return Value::Null;
}
예제 #14
0
ValueVector CCBReader::getOwnerOutletNames()
{
    ValueVector ret;
    ret.reserve(_ownerOutletNames.size());
    std::vector<std::string>::iterator it = _ownerOutletNames.begin();
    for (; it != _ownerOutletNames.end(); ++it)
    {
        ret.push_back(Value(*it));
    }
    return ret;
}
예제 #15
0
// ============================================================
//!		@brief		文字列分割
//!		@note		
//!		@param[in]	str		文字列
//!		@param[in]	delim	分割文字
//!		@return		分割後配列
// ============================================================
ValueVector Utility::split(const std::string &str, const std::string &delim)
{
	ValueVector res;
	size_t current = 0;
	size_t found = 0;

	while ((found = str.find(delim.c_str(), current, delim.size())) != std::string::npos)
	{
		res.push_back(Value(std::string(str, current, found - current)));
		current = found + delim.size();
	}
	res.push_back(Value(std::string(str, current, str.size() - current)));

	/*	std::string lastStr = std::string(str, current, str.size() - current);
	if (lastStr.size() != 0)
	{
	res.push_back(Value(lastStr));
	}*/
	return res;
}
예제 #16
0
// 加载CSV数据
void DBManager::loadCsvData(std::string file, ValueVector& data)
{
    Csv csv = Csv(file.c_str());
    for (int i = 0; i < csv.getRowCount(); i++) {
        ValueMap map;
        for (int j = 0; j < csv[i].size(); j++) {
            map[csv[0][j]] = csv[i][j];
        }
        data.push_back((Value)map);
    }
}
예제 #17
0
void Menu::alignItemsInColumns(int columns, va_list args)
{
    CCASSERT(columns >= 0, "Columns must be >= 0");
    ValueVector rows;
    while (columns)
    {
        rows.push_back(Value(columns));
        columns = va_arg(args, int);
    }
    alignItemsInColumnsWithArray(rows);
}
예제 #18
0
void hdf5_index_create(const Input & input_data, OutputIndex & index, ValueVector & vec_value){
    typedef typename std::map<typename Input::value_type, size_t> MapIndexType;
    MapIndexType mapIndex;

    for(size_t i = 0; i < input_data.size(); ++i){
        typename MapIndexType::iterator elem = mapIndex.insert(std::make_pair(input_data[i], vec_value.size())).first;
        index[i] = elem->second;
        if(vec_value.size() == elem->second){
            vec_value.push_back(elem->first);
        }
    }
}
예제 #19
0
/*
srcStr:字符串
sSep:分隔符
作用:将字符串 用分隔符分割成一个个Value对象 放到ValueVector中
*/
ValueVector StringUtil::split(const char* srcStr, const char* sSep){
	ValueVector stringList;
	int size = strlen(srcStr);
	Value str = Value(srcStr);
	int startIndex = 0;
	int endIndex = 0;
	endIndex = str.asString().find(sSep);
	std::string lineStr;
	while (endIndex > 0 )
	{
		lineStr = str.asString().substr(startIndex,endIndex);//截取一行字符串
		stringList.push_back(Value(lineStr));				//添加到列表

		str = Value(str.asString().substr(endIndex + 1,size));//截取剩下的字符串
		endIndex = str.asString().find(sSep);					//
	}

	//剩下的字符串也添加到列表
	if (str.asString().compare("")!= 0)
	{
		stringList.push_back(Value(str.asString()));
	}
	return stringList;
}
예제 #20
0
// 随机获取当前位置周围的空地
ValueVector GlobalManager::getNextSpace(Vec2 pos)
{
    ValueVector vv;
    for (int i = 0; i < 9; i++) {
        if (DX[i] == 0 && DY[i] == 0) continue;
        int xx = pos.x + DX[i];
        int yy = pos.y + DY[i];
        if (xx < 0 || xx > TILED_TOTAL_X || yy < 0 || yy > TILED_TOTAL_Y) continue;
        if (_cover[xx][yy]) continue;
        
        ValueMap map;
        map["x"] = xx; map["y"] = yy; map["dir"] = i;
        vv.push_back((Value)map);
    }
    return vv;
}
예제 #21
0
//itemをVectorで受け取り、縦に自動で並べる(n型配置)
Menu* createMenuWithArrayColAlign(Node* parent, const Vector<MenuItem*>& arrayOfItems, int col, int zOrder, Vec2 pos){
    Menu* menu = Menu::createWithArray(arrayOfItems);
    menu->setPosition(pos);
    
    ValueVector cols = ValueVector();
    int itemCount = (int)arrayOfItems.size();
    while (itemCount > 0) {
        int thisCol = std::min(col, itemCount);
        cols.push_back(Value(thisCol));
        itemCount -= thisCol;
    }
    menu->alignItemsInRowsWithArray(cols);
    menu->setName(std::string("menu") + arrayOfItems.at(0)->getName());
    
    if (parent) {
        parent->addChild(menu, zOrder);
    }
    return menu;
}
예제 #22
0
void HelloWorld::menuCloseCallback1(Ref*pSender)
{
	ValueMap root;
	ValueVector arry;
	
	std::string currentTime =MyUtility::getCurrentTime();
	log("%s", currentTime.c_str());

	// the first elements
	ValueMap dict;
	dict["date"]=currentTime;
	dict["content"]="the third element";
	arry.push_back(Value(dict));//the key step "Value(dict)"
	root["root"]=arry;
	
	//write the dictionary object to the plist file
	auto writepath=FileUtils::getInstance()->getWritablePath();
	auto path=writepath+"NoteList.plist";
	FileUtils::getInstance()->writeToFile(root,path);

}
예제 #23
0
bool CCBReader::readCallbackKeyframesForSeq(CCBSequence* seq)
{
    int numKeyframes = readInt(false);
    if(!numKeyframes) return true;

    CCBSequenceProperty* channel = new (std::nothrow) CCBSequenceProperty();
    channel->autorelease();

    for(int i = 0; i < numKeyframes; ++i) {

        float time = readFloat();
        std::string callbackName = readCachedString();

        int callbackType = readInt(false);

        ValueVector valueVector;
        valueVector.push_back(Value(callbackName));
        valueVector.push_back(Value(callbackType));

        CCBKeyframe* keyframe = new (std::nothrow) CCBKeyframe();
        keyframe->autorelease();

        keyframe->setTime(time);
        keyframe->setValue(Value(valueVector));

        if(_jsControlled) {
            std::stringstream callbackIdentifier;
            callbackIdentifier << callbackType;
            callbackIdentifier << ":" + callbackName;
            _animationManager->getKeyframeCallbacks().push_back(Value(callbackIdentifier.str()));
        }

        channel->getKeyframes().pushBack(keyframe);
    }

    seq->setCallbackChannel(channel);

    return true;
}
예제 #24
0
void User::getShareReward(int index)
{
	if(getShareRewardsLock(index - 1) == 1)
	{
		PopPanel::getInstance()->note("shareReward","type:Text---text:"+ a2u("已经获得该奖励"),1.0f,false,true);
		return;
	}
	
	auto name = "shareReward" + cocos2d::Value(index).asString();
	
	ValueVector rewards;
	ValueVector rewardVec;
	stringToValueVector(PlotScript::sharedHD()->getLuaVarString("script/Test.lua", name.c_str()),"###",rewardVec);
	for(auto pair:rewardVec)
	{
		ValueMap rewardMap;
		stringToValueMap(pair.asString(), rewardMap);
		rewards.push_back(cocos2d::Value(rewardMap));
	}

	// 默认只有一个奖品
	auto rewardMap = rewards.at(0).asValueMap();
	int typeId = rewardMap["typeId"].asInt();
	int num = rewardMap["num"].asInt();

	for(int i = 0; i < num; i ++)
	{
		auto prop = Prop::create(typeId);
		// 获得奖励
		auto player = Detect::shareDetect()->getPlayer();
		player->addProp(prop);
	}

	auto prop = Prop::create(typeId);
	PopPanel::getInstance()->note("cantEquip","type:Text---text:"+ a2u("恭喜获得 ###") + "type:Text---text:"+ prop->getNickName() + "|color:{255,0,0}");

	setShareRewardsLock(index - 1, 1);
}
예제 #25
0
//itemをVectorで受け取り、横に自動で並べる(Z型配置)
Menu* createMenuWithArrayRowAlign(Node* parent, const Vector<MenuItem*>& arrayOfItems, int row, int zOrder, Vec2 pos){
    Menu* menu = Menu::createWithArray(arrayOfItems);
    menu->setPosition(pos);
    
    ValueVector rows = ValueVector();
    int itemCount = (int)arrayOfItems.size();
    while (itemCount > 0) {
        int thisRow = std::min(row, itemCount);
        rows.push_back(Value(thisRow));
        itemCount -= thisRow;
    }
    /*
     int col = ((int)arrayOfItems.size() + row - 1) / row;
     for (int i = 0; i < col; ++i) {
     rows.push_back(Value(row));
     }*/
    menu->alignItemsInColumnsWithArray(rows);
    menu->setName(std::string("menu") + arrayOfItems.at(0)->getName());
    
    if (parent) {
        parent->addChild(menu, zOrder);
    }
    return menu;
}
예제 #26
0
// the XML parser calls here with all the elements
void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts)
{    
    CC_UNUSED_PARAM(ctx);
    TMXMapInfo *tmxMapInfo = this;
    std::string elementName = name;
    ValueMap attributeDict;
    if (atts && atts[0])
    {
        for (int i = 0; atts[i]; i += 2)
        {
            std::string key = atts[i];
            std::string value = atts[i+1];
            attributeDict.insert(std::make_pair(key, Value(value)));
        }
    }
    if (elementName == "map")
    {
        std::string version = attributeDict["version"].asString();
        if ( version != "1.0")
        {
            CCLOG("cocos2d: TMXFormat: Unsupported TMX version: %s", version.c_str());
        }
        std::string orientationStr = attributeDict["orientation"].asString();
        if (orientationStr == "orthogonal") {
            tmxMapInfo->setOrientation(TMXOrientationOrtho);
        }
        else if (orientationStr  == "isometric") {
            tmxMapInfo->setOrientation(TMXOrientationIso);
        }
        else if (orientationStr == "hexagonal") {
            tmxMapInfo->setOrientation(TMXOrientationHex);
        }
        else if (orientationStr == "staggered") {
            tmxMapInfo->setOrientation(TMXOrientationStaggered);
        }
        else {
            CCLOG("cocos2d: TMXFomat: Unsupported orientation: %d", tmxMapInfo->getOrientation());
        }

        Size s;
        s.width = attributeDict["width"].asFloat();
        s.height = attributeDict["height"].asFloat();
        tmxMapInfo->setMapSize(s);

        s.width = attributeDict["tilewidth"].asFloat();
        s.height = attributeDict["tileheight"].asFloat();
        tmxMapInfo->setTileSize(s);

        // The parent element is now "map"
        tmxMapInfo->setParentElement(TMXPropertyMap);
    } 
    else if (elementName == "tileset") 
    {
        // If this is an external tileset then start parsing that
        std::string externalTilesetFilename = attributeDict["source"].asString();
        if (externalTilesetFilename != "")
        {
            _externalTilesetFilename = externalTilesetFilename;

            // Tileset file will be relative to the map file. So we need to convert it to an absolute path
            if (_TMXFileName.find_last_of("/") != string::npos)
            {
                string dir = _TMXFileName.substr(0, _TMXFileName.find_last_of("/") + 1);
                externalTilesetFilename = dir + externalTilesetFilename;
            }
            else 
            {
                externalTilesetFilename = _resources + "/" + externalTilesetFilename;
            }
            externalTilesetFilename = FileUtils::getInstance()->fullPathForFilename(externalTilesetFilename);
            
            _currentFirstGID = attributeDict["firstgid"].asInt();
            if (_currentFirstGID < 0)
            {
                _currentFirstGID = 0;
            }
            _recordFirstGID = false;
            
            tmxMapInfo->parseXMLFile(externalTilesetFilename);
        }
        else
        {
            TMXTilesetInfo *tileset = new (std::nothrow) TMXTilesetInfo();
            tileset->_name = attributeDict["name"].asString();
            
            if (_recordFirstGID)
            {
                // unset before, so this is tmx file.
                tileset->_firstGid = attributeDict["firstgid"].asInt();
                
                if (tileset->_firstGid < 0)
                {
                    tileset->_firstGid = 0;
                }
            }
            else
            {
                tileset->_firstGid = _currentFirstGID;
                _currentFirstGID = 0;
            }
            
            tileset->_spacing = attributeDict["spacing"].asInt();
            tileset->_margin = attributeDict["margin"].asInt();
            Size s;
            s.width = attributeDict["tilewidth"].asFloat();
            s.height = attributeDict["tileheight"].asFloat();
            tileset->_tileSize = s;

            tmxMapInfo->getTilesets().pushBack(tileset);
            tileset->release();
        }
    }
    else if (elementName == "tile")
    {
        if (tmxMapInfo->getParentElement() == TMXPropertyLayer)
        {
            TMXLayerInfo* layer = tmxMapInfo->getLayers().back();
            Size layerSize = layer->_layerSize;
            uint32_t gid = static_cast<uint32_t>(attributeDict["gid"].asInt());
            int tilesAmount = layerSize.width*layerSize.height;
            
            if (_xmlTileIndex < tilesAmount)
            {
                layer->_tiles[_xmlTileIndex++] = gid;
            }
        }
        else
        {
            TMXTilesetInfo* info = tmxMapInfo->getTilesets().back();
            tmxMapInfo->setParentGID(info->_firstGid + attributeDict["id"].asInt());
            tmxMapInfo->getTileProperties()[tmxMapInfo->getParentGID()] = Value(ValueMap());
            tmxMapInfo->setParentElement(TMXPropertyTile);
        }
    }
    else if (elementName == "layer")
    {
        TMXLayerInfo *layer = new (std::nothrow) TMXLayerInfo();
        layer->_name = attributeDict["name"].asString();

        Size s;
        s.width = attributeDict["width"].asFloat();
        s.height = attributeDict["height"].asFloat();
        layer->_layerSize = s;

        Value& visibleValue = attributeDict["visible"];
        layer->_visible = visibleValue.isNull() ? true : visibleValue.asBool();

        Value& opacityValue = attributeDict["opacity"];
        layer->_opacity = opacityValue.isNull() ? 255 : (unsigned char)(255.0f * opacityValue.asFloat());

        float x = attributeDict["x"].asFloat();
        float y = attributeDict["y"].asFloat();
        layer->_offset.set(x, y);

        tmxMapInfo->getLayers().pushBack(layer);
        layer->release();

        // The parent element is now "layer"
        tmxMapInfo->setParentElement(TMXPropertyLayer);
    } 
    else if (elementName == "objectgroup")
    {
        TMXObjectGroup *objectGroup = new (std::nothrow) TMXObjectGroup();
        objectGroup->setGroupName(attributeDict["name"].asString());
        Vec2 positionOffset;
        positionOffset.x = attributeDict["x"].asFloat() * tmxMapInfo->getTileSize().width;
        positionOffset.y = attributeDict["y"].asFloat() * tmxMapInfo->getTileSize().height;
        objectGroup->setPositionOffset(positionOffset);

        tmxMapInfo->getObjectGroups().pushBack(objectGroup);
        objectGroup->release();

        // The parent element is now "objectgroup"
        tmxMapInfo->setParentElement(TMXPropertyObjectGroup);
    }
    else if (elementName == "image")
    {
        TMXTilesetInfo* tileset = tmxMapInfo->getTilesets().back();

        // build full path
        std::string imagename = attributeDict["source"].asString();
        tileset->_originSourceImage = imagename;

        if (_TMXFileName.find_last_of("/") != string::npos)
        {
            string dir = _TMXFileName.substr(0, _TMXFileName.find_last_of("/") + 1);
            tileset->_sourceImage = dir + imagename;
        }
        else 
        {
            tileset->_sourceImage = _resources + (_resources.size() ? "/" : "") + imagename;
        }
    } 
    else if (elementName == "data")
    {
        std::string encoding = attributeDict["encoding"].asString();
        std::string compression = attributeDict["compression"].asString();

        if (encoding == "")
        {
            tmxMapInfo->setLayerAttribs(tmxMapInfo->getLayerAttribs() | TMXLayerAttribNone);
            
            TMXLayerInfo* layer = tmxMapInfo->getLayers().back();
            Size layerSize = layer->_layerSize;
            int tilesAmount = layerSize.width*layerSize.height;

            uint32_t *tiles = (uint32_t*) malloc(tilesAmount*sizeof(uint32_t));
            // set all value to 0
            memset(tiles, 0, tilesAmount*sizeof(int));

            layer->_tiles = tiles;
        }
        else if (encoding == "base64")
        {
            int layerAttribs = tmxMapInfo->getLayerAttribs();
            tmxMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribBase64);
            tmxMapInfo->setStoringCharacters(true);

            if (compression == "gzip")
            {
                layerAttribs = tmxMapInfo->getLayerAttribs();
                tmxMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribGzip);
            } else
            if (compression == "zlib")
            {
                layerAttribs = tmxMapInfo->getLayerAttribs();
                tmxMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribZlib);
            }
            CCASSERT( compression == "" || compression == "gzip" || compression == "zlib", "TMX: unsupported compression method" );
        }
    } 
    else if (elementName == "object")
    {
        TMXObjectGroup* objectGroup = tmxMapInfo->getObjectGroups().back();

        // The value for "type" was blank or not a valid class name
        // Create an instance of TMXObjectInfo to store the object and its properties
        ValueMap dict;
        // Parse everything automatically
        const char* keys[] = {"name", "type", "width", "height", "gid"};
        
        for (const auto& key : keys)
        {
            Value value = attributeDict[key];
            dict[key] = value;
        }

        // But X and Y since they need special treatment
        // X
        int x = attributeDict["x"].asInt();
        // Y
        int y = attributeDict["y"].asInt();
        
        Vec2 p(x + objectGroup->getPositionOffset().x, _mapSize.height * _tileSize.height - y  - objectGroup->getPositionOffset().y - attributeDict["height"].asInt());
        p = CC_POINT_PIXELS_TO_POINTS(p);
        dict["x"] = Value(p.x);
        dict["y"] = Value(p.y);
        
        int width = attributeDict["width"].asInt();
        int height = attributeDict["height"].asInt();
        Size s(width, height);
        s = CC_SIZE_PIXELS_TO_POINTS(s);
        dict["width"] = Value(s.width);
        dict["height"] = Value(s.height);

        // Add the object to the objectGroup
        objectGroup->getObjects().push_back(Value(dict));

        // The parent element is now "object"
        tmxMapInfo->setParentElement(TMXPropertyObject);
    } 
    else if (elementName == "property")
    {
        if ( tmxMapInfo->getParentElement() == TMXPropertyNone ) 
        {
            CCLOG( "TMX tile map: Parent element is unsupported. Cannot add property named '%s' with value '%s'",
                  attributeDict["name"].asString().c_str(), attributeDict["value"].asString().c_str() );
        } 
        else if ( tmxMapInfo->getParentElement() == TMXPropertyMap )
        {
            // The parent element is the map
            Value value = attributeDict["value"];
            std::string key = attributeDict["name"].asString();
            tmxMapInfo->getProperties().insert(std::make_pair(key, value));
        }
        else if ( tmxMapInfo->getParentElement() == TMXPropertyLayer )
        {
            // The parent element is the last layer
            TMXLayerInfo* layer = tmxMapInfo->getLayers().back();
            Value value = attributeDict["value"];
            std::string key = attributeDict["name"].asString();
            // Add the property to the layer
            layer->getProperties().insert(std::make_pair(key, value));
        }
        else if ( tmxMapInfo->getParentElement() == TMXPropertyObjectGroup ) 
        {
            // The parent element is the last object group
            TMXObjectGroup* objectGroup = tmxMapInfo->getObjectGroups().back();
            Value value = attributeDict["value"];
            std::string key = attributeDict["name"].asString();
            objectGroup->getProperties().insert(std::make_pair(key, value));
        }
        else if ( tmxMapInfo->getParentElement() == TMXPropertyObject )
        {
            // The parent element is the last object
            TMXObjectGroup* objectGroup = tmxMapInfo->getObjectGroups().back();
            ValueMap& dict = objectGroup->getObjects().rbegin()->asValueMap();

            std::string propertyName = attributeDict["name"].asString();
            dict[propertyName] = attributeDict["value"];
        }
        else if ( tmxMapInfo->getParentElement() == TMXPropertyTile ) 
        {
            ValueMap& dict = tmxMapInfo->getTileProperties().at(tmxMapInfo->getParentGID()).asValueMap();

            std::string propertyName = attributeDict["name"].asString();
            dict[propertyName] = attributeDict["value"];
        }
    }
    else if (elementName == "polygon") 
    {
        // find parent object's dict and add polygon-points to it
        TMXObjectGroup* objectGroup = _objectGroups.back();
        ValueMap& dict = objectGroup->getObjects().rbegin()->asValueMap();

        // get points value string
        std::string value = attributeDict["points"].asString();
        if (!value.empty())
        {
            ValueVector pointsArray;
            pointsArray.reserve(10);

            // parse points string into a space-separated set of points
            stringstream pointsStream(value);
            string pointPair;
            while (std::getline(pointsStream, pointPair, ' '))
            {
                // parse each point combo into a comma-separated x,y point
                stringstream pointStream(pointPair);
                string xStr, yStr;
                
                ValueMap pointDict;

                // set x
                if (std::getline(pointStream, xStr, ','))
                {
                    int x = atoi(xStr.c_str()) + (int)objectGroup->getPositionOffset().x;
                    pointDict["x"] = Value(x);
                }

                // set y
                if (std::getline(pointStream, yStr, ','))
                {
                    int y = atoi(yStr.c_str()) + (int)objectGroup->getPositionOffset().y;
                    pointDict["y"] = Value(y);
                }
                
                // add to points array
                pointsArray.push_back(Value(pointDict));
            }
            
            dict["points"] = Value(pointsArray);
        }
    } 
    else if (elementName == "polyline")
    {
        // find parent object's dict and add polyline-points to it
        TMXObjectGroup* objectGroup = _objectGroups.back();
        ValueMap& dict = objectGroup->getObjects().rbegin()->asValueMap();
        
        // get points value string
        std::string value = attributeDict["points"].asString();
        if (!value.empty())
        {
            ValueVector pointsArray;
            pointsArray.reserve(10);
            
            // parse points string into a space-separated set of points
            stringstream pointsStream(value);
            string pointPair;
            while (std::getline(pointsStream, pointPair, ' '))
            {
                // parse each point combo into a comma-separated x,y point
                stringstream pointStream(pointPair);
                string xStr, yStr;
                
                ValueMap pointDict;
                
                // set x
                if (std::getline(pointStream, xStr, ','))
                {
                    int x = atoi(xStr.c_str()) + (int)objectGroup->getPositionOffset().x;
                    pointDict["x"] = Value(x);
                }
                
                // set y
                if (std::getline(pointStream, yStr, ','))
                {
                    int y = atoi(yStr.c_str()) + (int)objectGroup->getPositionOffset().y;
                    pointDict["y"] = Value(y);
                }
                
                // add to points array
                pointsArray.push_back(Value(pointDict));
            }
            
            dict["polylinePoints"] = Value(pointsArray);
        }
    }
}
예제 #27
0
CCBKeyframe* CCBReader::readKeyframe(PropertyType type)
{
    CCBKeyframe *keyframe = new (std::nothrow) CCBKeyframe();
    keyframe->autorelease();

    keyframe->setTime(readFloat());

    CCBKeyframe::EasingType easingType = static_cast<CCBKeyframe::EasingType>(readInt(false));
    float easingOpt = 0;
    Value value;

    if (easingType == CCBKeyframe::EasingType::CUBIC_IN
        || easingType == CCBKeyframe::EasingType::CUBIC_OUT
        || easingType == CCBKeyframe::EasingType::CUBIC_INOUT
        || easingType == CCBKeyframe::EasingType::ELASTIC_IN
        || easingType == CCBKeyframe::EasingType::ELASTIC_OUT
        || easingType == CCBKeyframe::EasingType::ELASTIC_INOUT)
    {
        easingOpt = readFloat();
    }
    keyframe->setEasingType(easingType);
    keyframe->setEasingOpt(easingOpt);

    if (type == PropertyType::CHECK)
    {
        value = readBool();
    }
    else if (type == PropertyType::BYTE)
    {
        value = readByte();
    }
    else if (type == PropertyType::COLOR3)
    {
        unsigned char r = readByte();
        unsigned char g = readByte();
        unsigned char b = readByte();

        ValueMap colorMap;
        colorMap["r"] = r;
        colorMap["g"] = g;
        colorMap["b"] = b;

        value = colorMap;
    }
    else if (type == PropertyType::DEGREES)
    {
        value = readFloat();
    }
    else if (type == PropertyType::SCALE_LOCK || type == PropertyType::POSITION
         || type == PropertyType::FLOAT_XY)
    {
        float a = readFloat();
        float b = readFloat();

        ValueVector ab;
        ab.push_back(Value(a));
        ab.push_back(Value(b));

        value = ab;
    }
    else if (type == PropertyType::SPRITEFRAME)
    {
        std::string spriteSheet = readCachedString();
        std::string spriteFile = readCachedString();

        SpriteFrame* spriteFrame;

        if (spriteSheet.empty())
        {
            spriteFile = _CCBRootPath + spriteFile;

            Texture2D *texture = Director::DirectorInstance->getTextureCache()->addImage(spriteFile);
            Rect bounds = Rect(0, 0, texture->getContentSize().width, texture->getContentSize().height);

            spriteFrame = SpriteFrame::createWithTexture(texture, bounds);
        }
        else
        {
            spriteSheet = _CCBRootPath + spriteSheet;
            SpriteFrameCache* frameCache = SpriteFrameCache::getInstance();

            // Load the sprite sheet only if it is not loaded
            if (_loadedSpriteSheets.find(spriteSheet) == _loadedSpriteSheets.end())
            {
                frameCache->addSpriteFramesWithFile(spriteSheet);
                _loadedSpriteSheets.insert(spriteSheet);
            }

            spriteFrame = frameCache->getSpriteFrameByName(spriteFile);
        }

        keyframe->setObject(spriteFrame);
    }

    if (!value.isNull())
        keyframe->setValue(value);

    return  keyframe;
}
    void endElement(void *ctx, const char *name)
    {
        CC_UNUSED_PARAM(ctx);
        SAXState curState = _stateStack.empty() ? SAX_DICT : _stateStack.top();
        const std::string sName((char*)name);
        if( sName == "dict" )
        {
            _stateStack.pop();
            _dictStack.pop();
            if ( !_dictStack.empty())
            {
                _curDict = _dictStack.top();
            }
        }
        else if (sName == "array")
        {
            _stateStack.pop();
            _arrayStack.pop();
            if (! _arrayStack.empty())
            {
                _curArray = _arrayStack.top();
            }
        }
        else if (sName == "true")
        {
            if (SAX_ARRAY == curState)
            {
                _curArray->push_back(Value(true));
            }
            else if (SAX_DICT == curState)
            {
                (*_curDict)[_curKey] = Value(true);
            }
        }
        else if (sName == "false")
        {
            if (SAX_ARRAY == curState)
            {
                _curArray->push_back(Value(false));
            }
            else if (SAX_DICT == curState)
            {
                (*_curDict)[_curKey] = Value(false);
            }
        }
        else if (sName == "string" || sName == "integer" || sName == "real")
        {
            if (SAX_ARRAY == curState)
            {
                if (sName == "string")
                    _curArray->push_back(Value(_curValue));
                else if (sName == "integer")
                    _curArray->push_back(Value(atoi(_curValue.c_str())));
                else
                    _curArray->push_back(Value(utils::atof(_curValue.c_str())));
            }
            else if (SAX_DICT == curState)
            {
                if (sName == "string")
                    (*_curDict)[_curKey] = Value(_curValue);
                else if (sName == "integer")
                    (*_curDict)[_curKey] = Value(atoi(_curValue.c_str()));
                else
                    (*_curDict)[_curKey] = Value(utils::atof(_curValue.c_str()));
            }

            _curValue.clear();
        }

        _state = SAX_NONE;
    }
    void startElement(void *ctx, const char *name, const char **atts)
    {
        CC_UNUSED_PARAM(ctx);
        CC_UNUSED_PARAM(atts);
        const std::string sName(name);
        if( sName == "dict" )
        {
            if(_resultType == SAX_RESULT_DICT && _rootDict.empty())
            {
                _curDict = &_rootDict;
            }

            _state = SAX_DICT;

            SAXState preState = SAX_NONE;
            if (! _stateStack.empty())
            {
                preState = _stateStack.top();
            }

            if (SAX_ARRAY == preState)
            {
                // add a new dictionary into the array
                _curArray->push_back(Value(ValueMap()));
                _curDict = &(_curArray->rbegin())->asValueMap();
            }
            else if (SAX_DICT == preState)
            {
                // add a new dictionary into the pre dictionary
                CCASSERT(! _dictStack.empty(), "The state is wrong!");
                ValueMap* preDict = _dictStack.top();
                (*preDict)[_curKey] = Value(ValueMap());
                _curDict = &(*preDict)[_curKey].asValueMap();
            }

            // record the dict state
            _stateStack.push(_state);
            _dictStack.push(_curDict);
        }
        else if(sName == "key")
        {
            _state = SAX_KEY;
        }
        else if(sName == "integer")
        {
            _state = SAX_INT;
        }
        else if(sName == "real")
        {
            _state = SAX_REAL;
        }
        else if(sName == "string")
        {
            _state = SAX_STRING;
        }
        else if (sName == "array")
        {
            _state = SAX_ARRAY;

            if (_resultType == SAX_RESULT_ARRAY && _rootArray.empty())
            {
                _curArray = &_rootArray;
            }
            SAXState preState = SAX_NONE;
            if (! _stateStack.empty())
            {
                preState = _stateStack.top();
            }

            if (preState == SAX_DICT)
            {
                (*_curDict)[_curKey] = Value(ValueVector());
                _curArray = &(*_curDict)[_curKey].asValueVector();
            }
            else if (preState == SAX_ARRAY)
            {
                CCASSERT(! _arrayStack.empty(), "The state is wrong!");
                ValueVector* preArray = _arrayStack.top();
                preArray->push_back(Value(ValueVector()));
                _curArray = &(_curArray->rbegin())->asValueVector();
            }
            // record the array state
            _stateStack.push(_state);
            _arrayStack.push(_curArray);
        }
        else
        {
            _state = SAX_NONE;
        }
    }
예제 #30
0
Swap::Swap(std::string buyer, std::string seller)
{
	_buyer = dynamic_cast<Actor*>(Detect::shareDetect()->getCellByName(buyer));
	_seller = dynamic_cast<Actor*>(Detect::shareDetect()->getCellByName(seller));

	auto swapId = _seller->getModelByName("swapId").asInt();
	int swapCount = _seller->getSwapCount();
	//shopId = 1;
	std::string shopStr;
	std::string preCondtion;
	std::string swapName = "swap" + cocos2d::Value(swapId).asString() + "_" + cocos2d::Value(swapCount).asString();
	std::string swapNumStr = "swap" + cocos2d::Value(swapId).asString() + "_num";
	int swapNum = cocos2d::Value(PlotScript::sharedHD()->getLuaVarString("script/Test.lua", swapNumStr.c_str())).asInt();
	if(swapNum == 0) swapNum = 1;

	bool canSwap = true;

	while(true)
	{
		if(swapCount >= swapNum)
		{
			PopPanel::getInstance()->note("cannt","type:Text---text:"+ a2u("超过交易上限,无法使用"), 1.0f, true, true);
			canSwap = false;
			break;
		}

		shopStr = PlotScript::sharedHD()->getLuaVarOneOfTable("script/Test.lua", swapName.c_str(),"content");
		title = PlotScript::sharedHD()->getLuaVarOneOfTable("script/Test.lua", swapName.c_str(),"title");
		preCondtion = PlotScript::sharedHD()->getLuaVarOneOfTable("script/Test.lua", swapName.c_str(),"preCondition");
		if(preCondtion != "")
		{
			ValueMap preVec;
			stringToValueMap(preCondtion,preVec);
			for (auto pair:preVec)
			{
				auto num = pair.second.asInt();
				if(pair.first == "level")
				{
					if(_buyer->getLevel() > num)
					{
						PopPanel::getInstance()->note("levelBeyond","type:Text---text:"+ a2u("等级过高,无法使用"), 1.0f, true, true);
						canSwap = false;
						break;
					}
				}
				else if(pair.first == "")
				{

				}
				else if(pair.first == "")
				{

				}
				else if(pair.first == "")
				{

				}
				else if(pair.first == "")
				{

				}
			}
		}
		break;
	}
	

	if(canSwap == false)
	{
		this->removeFromParent();
		return;
	}

	if(shopStr != "")
	{
		ValueVector vec1;
		stringToValueVector(shopStr,"###",vec1);
		for (auto i:vec1)
		{
			ValueVector vec2;
			stringToValueVector(i.asString(),"~~~",vec2);
			ValueVector option;
			for(auto j:vec2)
			{
				ValueVector vec3;
				ValueVector vecout;
				stringToValueVector(j.asString(),"$$$",vec3);
				for(auto k:vec3)
				{
					ValueMap map;
					stringToValueMap(k.asString(), map);
					vecout.push_back(cocos2d::Value(map));
				}
				option.push_back(cocos2d::Value(vecout));
			}
			options.push_back(cocos2d::Value(option));
		}
	}
	_swapPanel = SwapPanel::create("swap");
	_swapPanel->build(this);
	PopPanel::getInstance()->addPanel(_swapPanel,1);
}