void
MCBackpack::loadData()
{
    CCUserDefault *userDefault = CCUserDefault::sharedUserDefault();
    
    loadEffectiveItems();
    
    if (! __icon_loaded) {
        loadIcons();
    }
    
    if (MCGameState::sharedGameState()->isSaveFileExists()) {
        string data = userDefault->getStringForKey(kMCBackpackKey, kMCZero);
        if (data.size() > 0) {
#if MC_DEBUG_SAVEDATA == 1
            const char *output = data.c_str();
#else
            const char *input = data.c_str();
            char *output;
            mc_size_t len = strlen(input);
            MCBase64Decode((mc_byte_t *) input, len, (mc_byte_t **) &output);
#endif
            JsonBox::Value v;
            v.loadFromString(output);
            
            JsonBox::Object backpack = v.getObject();
            /* 加载金钱 */
            money_ = backpack[kMCMoneyKey].getInt();
        }
    } else {
        money_ = 0;
    }
}
Esempio n. 2
0
 void GameState::loadGUIConf(const std::string& filename){
     JsonBox::Value v;
 #if defined ANDROID
     v.loadFromString(std::string(android::readAssetsFile(filename).data()));
 #else
     v.loadFromFile(filename);
 #endif
     if(!v["GUI"]["buttons"].isNull()){
         int size = v["GUI"]["buttons"].getArray().size();
         for(int i=0;i<size;++i){
             sf::Vector2f pos(v["GUI"]["buttons"][size_t(i)]["position"]["x"].getInteger(),
                              v["GUI"]["buttons"][size_t(i)]["position"]["y"].getInteger());
             sf::Vector2f bSize(v["GUI"]["buttons"][size_t(i)]["scale"]["width"].getInteger(),
                                v["GUI"]["buttons"][size_t(i)]["scale"]["height"].getInteger());
             sf::Text t;
             if(v["GUI"]["buttons"][size_t(i)]["text"]["font"].getString() != ""){
                 t.setFont(assets->getFont(v["GUI"]["buttons"][size_t(i)]["text"]["font"].getString()));
             }
             t.setString(v["GUI"]["buttons"][size_t(i)]["text"]["string"].getString());
             t.setPosition(pos);
             t.setCharacterSize(v["GUI"]["buttons"][size_t(i)]["text"]["size"].getInteger());
             sf::Sprite sprite;
             sprite.setPosition(pos);
             if(v["GUI"]["buttons"][size_t(i)]["imageID"].getString() != ""){
                 auto textureID = v["GUI"]["buttons"][size_t(i)]["imageID"].getString();
                 if(assets->hasTexture(textureID)){
                     sprite.setTexture(assets->getTexture(textureID));
                 }else{
                     throw std::runtime_error("The " + textureID + " ID doesn't exists, add it to assets.json");
                 }
             }
             std::string actionID = v["GUI"]["buttons"][size_t(i)]["action"].getString();
             constructorSystem::command action = [](Entity* e,sf::VertexArray* va,sf::FloatRect bounds){};
             if(actionID == "climb"){
                 action = Constructions::climb;
             }else if(actionID == "dig"){
                 action = Constructions::hole;
             }else if(actionID == "tunnel"){
                 action = Constructions::tunnel;
             }else if(actionID == "stairs"){
                 action = Constructions::stairs;
             }else if(actionID == "wall"){
                 action = Constructions::wall;
             }else if(actionID == "stop"){
                 action = Constructions::stop;
             }else if(actionID == "bridge"){
                 action = Constructions::bridge;
             }else if(actionID == "downhill"){
                 action = Constructions::downhill;
             }else if(actionID == "uphill"){
                 action = Constructions::uphill;
             }else if(actionID == "explosion"){
                 action = Constructions::explosion;
             }
             buttons.emplace_back(std::make_unique<GUI::Button>(pos,sprite,t,action));
         }
     }
 }
Esempio n. 3
0
 void GameState::loadConfig(const std::string& filename){
     JsonBox::Value v;
 #if defined ANDROID
     v.loadFromString(std::string(android::readAssetsFile(filename).data()));
 #else
     v.loadFromFile(filename);
 #endif
     if(v["Config"]["font"].getString() != ""){
         font = v["Config"]["font"].getString();
     }
 }
void EntityManager::loadJson(const std::string& filename)
{
	JsonBox::Value v;
	v.loadFromFile(filename);

	JsonBox::Object o = v.getObject();
	for(auto entity : o)
	{
		std::string key = entity.first;
		this->data[key] = dynamic_cast<Entity*>(new T(key, entity.second, this));
	}
}
Esempio n. 5
0
inline void unserialize(const JsonBox::Value & o, sf::Transform & t)
{
	assert(o.isArray());

	const JsonBox::Array & a = o.getArray();

	t = sf::Transform(
		a[0].getDouble(), a[4].getDouble(), a[12].getDouble(),
		a[1].getDouble(), a[5].getDouble(), a[13].getDouble(),
		a[3].getDouble(), a[7].getDouble(), a[15].getDouble()
	);
}
/**
 * 从数据包加载任务
 */
bool
MCTaskAccessor::loadTasks(const char *aFilePath)
{
    bool result = false;
    
    do {
        JsonBox::Value in;
        JsonBox::Object o;
        JsonBox::Object tasksDict;
        JsonBox::Object::iterator oIter;
        
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
        CCString* pstrFileContent = CCString::createWithContentsOfFile(aFilePath);
        if (pstrFileContent) {
            in.loadFromString(pstrFileContent->getCString());
        }
#else
        in.loadFromFile(CCFileUtils::sharedFileUtils()->fullPathForFilename(aFilePath).c_str());
#endif
        
        CC_BREAK_IF(! in.isObject());
        
        tasksDict = in.getObject();
        for (oIter = tasksDict.begin(); oIter != tasksDict.end(); ++oIter) {
            std::string t_id = oIter->first;
            const char *s_t_id = t_id.c_str();
            mc_object_id_t o_id = {
                s_t_id[0],
                s_t_id[1],
                s_t_id[2],
                s_t_id[3]
            };
            MCTask *task = new MCTask;
            task->autorelease();
            if (task) {
                task->setID(o_id);
                o = oIter->second.getObject();
                task->loadTaskContent(o);
                /* 默认为未完成状态,然后会在加载存档数据的时候更新为正确状态 */
                task->setTaskStatus(MCTaskUncompleted);
                task->proto_ = NULL;
                tasks_->setObject(task, MCObjectIdToDickKey(o_id));
            }
        }
        
        result = true;
    } while (0);
    
    return result;
}
Inventory::Inventory(JsonBox::Value& v, EntityManager* mgr)
{
	JsonBox::Object o = v.getObject();
	load<Item>(o["items"], mgr);
	load<Weapon>(o["weapons"], mgr);
	load<Armor>(o["armor"], mgr);
}
Esempio n. 8
0
void Weapon::load(const JsonBox::Value& v, EntityManager* mgr)
{
	JsonBox::Object o = v.getObject();
	this->damage = o["damage"].getInteger();

	return;
}
Esempio n. 9
0
void Armor::load(JsonBox::Value& v, EntityManager* mgr)
{
	JsonBox::Object o = v.getObject();
	this->defense = o["defense"].getInteger();

	return;
}
Esempio n. 10
0
void Creature::load(const JsonBox::Value& v, EntityManager* mgr)
{
	JsonBox::Object o = v.getObject();
	this->name = o["name"].getString();
	this->hp = o["hp"].getInteger();
	if(o.find("hp_max") != o.end())
	{
		this->maxHp = o["hp_max"].getInteger();
	}
	else
	{
		this->maxHp = hp;
	}
	this->strength = o["strength"].getInteger();
	this->agility = o["agility"].getInteger();
	this->evasion = o["evasion"].getDouble();
	this->xp = o["xp"].getInteger();

	if(o.find("inventory") != o.end())
	{
		this->inventory = Inventory(o["inventory"], mgr);
	}
	if(o.find("equipped_weapon") != o.end())
	{
		std::string equippedWeaponName = o["equipped_weapon"].getString();
		this->equippedWeapon = equippedWeaponName == "nullptr" ? nullptr : mgr->getEntity<Weapon>(equippedWeaponName);
	}
	if(o.find("equipped_armor") != o.end())
	{
		std::string equippedArmorName = o["equipped_armor"].getString();
		this->equippedArmor = equippedArmorName == "nullptr" ? nullptr : mgr->getEntity<Armor>(equippedArmorName);
	}

	return;
}
Esempio n. 11
0
void RPCClient::request(JsonBox::Value& json, char* method, JsonBox::Object params)
{
	string result = "";
	stringstream sstream("");
	
	DeviceInfo *dev = ((AppDelegate*)cocos2d::CCApplication::sharedApplication())->getDeviceInfo();
	JsonBox::Object device;
	dev->getJSONString(device);
	
	params["authkey"] = JsonBox::Value(dev->getAuthKey());
	params["device"] = JsonBox::Value(device);
	
	JsonBox::Object data;
	data["jsonrpc"] = JsonBox::Value("2.0");
	data["id"] = JsonBox::Value("1");
	data["method"] = JsonBox::Value(method);
	data["params"] = JsonBox::Value(params);

	sstream << data;

	if(_send(sstream.str()))
		_recv(result);
	
	sstream.flush();

	json.loadFromString(result);
}
Esempio n. 12
0
void Item::Load(JsonBox::Value& v, EntityManager* manager)
{
	JsonBox::Object obj = v.getObject();
	
	name = obj["name"].getString();
	description = obj["description"].getString();
}
Esempio n. 13
0
void Player::Load(JsonBox::Value& saveData, EntityManager* manager)
{
	Creature::Load(saveData, manager);
	JsonBox::Object obj = saveData.getObject();

	className = obj["CclassName"].getString();
	level = obj["level"].getInteger();
}
Esempio n. 14
0
void Inventory::load(JsonBox::Value& v, EntityManager* mgr)
{
	for(auto item : v.getArray())
	{
		std::string itemId = item.getArray()[0].getString();
		int quantity = item.getArray()[1].getInteger();
		this->items.push_back(std::make_pair(mgr->getEntity<T>(itemId), quantity));
	}
}
Esempio n. 15
0
void unserialize(const JsonBox::Value & o, std::unordered_set<T> & v)
{
	const JsonBox::Array & a = o.getArray();
	for(u32 i = 0; i < a.size(); ++i)
	{
		T elem;
		unserialize(a[i], elem);
		v.insert(elem);
	}
}
Esempio n. 16
0
void Player::LoadArea(JsonBox::Value& areaData, EntityManager* manager)
{
	JsonBox::Object obj = areaData.getObject();
	for (auto area : obj)
	{
		std::string key = area.first;
		manager->GetEntity<Area>(key)->Load(area.second, manager);
		visitedAreas.insert(key);
	}
}
Esempio n. 17
0
void unserialize(const JsonBox::Value & o, std::vector<T> & v)
{
	const JsonBox::Array & a = o.getArray();
	v.resize(a.size());
	for(u32 i = 0; i < a.size(); ++i)
	{
		const JsonBox::Value & jv = a[i];
		unserialize(jv, v[i]);
	}
}
Esempio n. 18
0
void RegisterLayer::clickRegister(CCObject* pSender)
{
	map<string,string> post;
	post["api"] = "sign_up";
	post["username"] = usernameText->getString();
	post["password"] = passwordText->getString();
	post["role_type"] = Utils::int2str((int)USER->getRoleType());
	post["level"] = Utils::int2str(USER->getLevel());
	post["exp"] = Utils::int2str(USER->getExp());
	post["basic_agi"] = Utils::int2str(USER->getBasicAGI());
	post["basic_str"] = Utils::int2str(USER->getBasicSTR());
	post["basic_def"] = Utils::int2str(USER->getBasicDEF());
	post["current_weapon"] = Utils::int2str((int)USER->getEquipment().getWeapon());
	post["current_base"] = Utils::int2str((int)USER->getEquipment().getBase());
	post["current_plate"] = Utils::int2str((int)USER->getEquipment().getPlate());
	post["open_chapters_number"] = Utils::int2str(USER->getOpenChaptersNumber());
	post["win_online_game_number"] = Utils::int2str(USER->getWinOnlineGamesNumber());
	post["play_online_game_number"] = Utils::int2str(USER->getPlayOnlineGamesNumber());
	post["money"] = Utils::int2str(USER->getMoney());
	post["honor"] = Utils::int2str(USER->getHonor());

	std::string jsonStr = POST(post);
	
	JsonBox::Value data;
	CCLOG(jsonStr.c_str());
	data.loadFromString(jsonStr);
	if(data["result"].getString()=="OK"){
		USER->setUsername(usernameText->getString());
		USER->setPassword(passwordText->getString());
		USER->setHasSignin(true);
		USER->setIsBeginner(false);
		CCNode* parent = this->getParent();
		this->removeFromParentAndCleanup();
		INFORMATION_BOX(CN("register_and_login_successfully"),parent);
	}
	else if(data["result"].getString()=="Username existed"){
		INFORMATION_BOX(CN("username_existed"),this);
	}
	else{
		INFORMATION_BOX(CN("register_failed"),this);
	}
}
Esempio n. 19
0
bool Camera::parse(const JsonBox::Value &cameraVal, Camera &camera)
{
	JsonBox::Object cameraObj;

	if (!cameraVal.isObject())
	{
		cerr << "Error: Camera must be an Object." << endl;
		return false;
	}

	cameraObj = cameraVal.getObject();

	if
	(
		!cameraObj["origin"].isArray() || !cameraObj["direction"].isArray() || !cameraObj["top"].isArray()
		||
		!cameraObj["origin"].getArray()[0].isNumber()	|| !cameraObj["origin"].getArray()[1].isNumber() || !cameraObj["origin"].getArray()[2].isNumber()
		||
		!cameraObj["direction"].getArray()[0].isNumber() || !cameraObj["direction"].getArray()[1].isNumber() || !cameraObj["direction"].getArray()[2].isNumber()
		||
		!cameraObj["top"].getArray()[0].isNumber() || !cameraObj["top"].getArray()[1].isNumber() || !cameraObj["top"].getArray()[2].isNumber()
	)
	{
		cerr << "Error: invalid Camera vectors (origin, direction and top)." << endl;
		return false;
	}

	if (!cameraObj["fovy"].isNumber() || !cameraObj["width"].isInteger() || !cameraObj["height"].isInteger() || !cameraObj["filename"].isString())
	{
		cerr << "Error: invalid Camera parameters (fovy, width, height and filename)." << endl;
		return false;
	}

	Point origin = Point(cameraObj["origin"].getArray()[0].getNumber(), cameraObj["origin"].getArray()[1].getNumber(), cameraObj["origin"].getArray()[2].getNumber());
	Vector direction = Point(cameraObj["direction"].getArray()[0].getNumber(), cameraObj["direction"].getArray()[1].getNumber(), cameraObj["direction"].getArray()[2].getNumber());
	Vector top = Point(cameraObj["top"].getArray()[0].getNumber(), cameraObj["top"].getArray()[1].getNumber(), cameraObj["top"].getArray()[2].getNumber());

	camera = Camera(origin, direction, top, cameraObj["fovy"].getNumber() * (2 * M_PI) / 360.0, cameraObj["width"].getInt(), cameraObj["height"].getInt(), cameraObj["filename"].getString());

	return true;
}
Esempio n. 20
0
void LogIntoLayer::clickLogInto(CCObject* pSender)
{
	map<string,string> post;
	post["api"] = "login";
	post["username"]=usernameText->getString();
	post["password"]=passwordText->getString();
	std::string jsonStr = POST(post);
	JsonBox::Value data;
	CCLOG(jsonStr.c_str());
	data.loadFromString(jsonStr);
	if(data["result"].getString()=="OK"){
		CCLOG("Login Successfully!");
		USER->setUserID(atoi(data["0"]["user_id"].getString().c_str()));
		USER->setUsername(data["0"]["username"].getString());
		USER->setPassword(data["0"]["password"].getString());
		USER->setLevel(atoi(data["0"]["level"].getString().c_str()));
		USER->setExp(atoi(data["0"]["exp"].getString().c_str()));
		USER->setBasicAGI(atoi(data["0"]["basic_agi"].getString().c_str()));
		USER->setBasicSTR(atoi(data["0"]["basic_str"].getString().c_str()));
		USER->setBasicDEF(atoi(data["0"]["basic_def"].getString().c_str()));
		Equipment* equipment = new Equipment();
		equipment->setWeapon(Weapon(atoi(data["0"]["current_weapon"].getString().c_str())));
		equipment->setBase(Base(atoi(data["0"]["current_base"].getString().c_str())));
		equipment->setPlate(Plate(atoi(data["0"]["current_plate"].getString().c_str())));//
		USER->setOpenChaptersNumber(atoi(data["0"]["open_chapters_number"].getString().c_str()));
		USER->setWinOnlineGamesNumber(atoi(data["0"]["win_online_game_number"].getString().c_str()));
		USER->setPlayOnlineGamesNumber(atoi(data["0"]["play_online_game_number"].getString().c_str()));
		USER->setMoney(atoi(data["0"]["money"].getString().c_str()));
		CCLOG(data["0"]["money"].getString().c_str());
		USER->setHonor(atoi(data["0"]["honor"].getString().c_str()));
		USER->setHasSignin(true);
		USER->setIsBeginner(false);
		USER->flush();
		CCNode* parent = this->getParent();
		this->removeFromParentAndCleanup();
		INFORMATION_BOX("Login successfully!",parent);
	}
	else{
		PopWindowsLayer::createInfomationBox("Login failed!",this);
	}
}
Esempio n. 21
0
		JsonBox::Array SpellChecker::Check(const std::string &text)
		{
			JsonBox::Value result;

			std::wstring wide_text = Helpers::String::strtowstr(text);
			std::string utf8_text = Helpers::String::ToUtf8(wide_text);

			std::string encoded_text = Helpers::String::UriEncode(utf8_text);

			std::stringstream url;
			url << m_spell_check_url << encoded_text;

			std::stringstream data;
			Helpers::Files::DownloadFile(url.str(), data);

			std::string answer = data.str();

			result.loadFromString(answer);

			return result.getArray();
		}
Esempio n. 22
0
		ZD_STATUS Language::LoadNode(JsonBox::Value &node, const std::string &prefix)
		{
			if (node.isObject())
			{
				JsonBox::Object obj = node.getObject();

				for (auto &i : obj)
				{
					std::stringstream new_prefix;

					if (prefix.length() > 0)
					{
						new_prefix << prefix << m_delimiter;						
					}

					new_prefix << i.first;

					LoadNode(i.second, new_prefix.str());
				}
			}
			else if (node.isString())
			{
				m_words[prefix] = node.getString();
			}
			else if (node.isInteger())
			{
				m_words[prefix] = Helpers::String::To(node.getInt());
			}
			return ZD_NOERROR;
		}
void
MCBackpack::loadEffectiveItems()
{
    MCItemManager *itemManager = MCItemManager::sharedItemManager();
    CCUserDefault *userDefault = CCUserDefault::sharedUserDefault();
    string data = userDefault->getStringForKey(kMCEffectiveItemsKey, "");
    
    if (MCGameState::sharedGameState()->isSaveFileExists()
        && data.size() > 0) {
#if MC_DEBUG_SAVEDATA == 1
        const char *output = data.c_str();
#else
        const char *input = data.c_str();
        char *output;
        mc_size_t len = strlen(input);
        MCBase64Decode((mc_byte_t *) input, len, (mc_byte_t **) &output);
#endif
        JsonBox::Value v;
        v.loadFromString(output);
        
        JsonBox::Array effectiveItems = v.getArray();
        
        healthPotion_->count = effectiveItems.at(0).getInt();
        physicalPotion_->count = effectiveItems.at(1).getInt();
        fireballTrapWide_->count = effectiveItems.at(2).getInt();
        fireballTrapDamage_->count = effectiveItems.at(3).getInt();
        curseTrapWide_->count = effectiveItems.at(4).getInt();
        curseTrapDamage_->count = effectiveItems.at(5).getInt();
        paralysisTrapWide_->count = effectiveItems.at(6).getInt();
        paralysisTrapDamage_->count = effectiveItems.at(7).getInt();
        fogTrapWide_->count = effectiveItems.at(8).getInt();
        fogTrapDamage_->count = effectiveItems.at(9).getInt();
        flashTrapWide_->count = effectiveItems.at(10).getInt();
        flashTrapDamage_->count = effectiveItems.at(11).getInt();
#if MC_DEBUG_SAVEDATA != 1
        delete []output;
#endif
    } else {
        healthPotion_->count = 0;
        physicalPotion_->count = 0;
        fireballTrapWide_->count = 0;
        fireballTrapDamage_->count = 0;
        curseTrapWide_->count = 0;
        curseTrapDamage_->count = 0;
        paralysisTrapWide_->count = 0;
        paralysisTrapDamage_->count = 0;
        fogTrapWide_->count = 0;
        fogTrapDamage_->count = 0;
        flashTrapWide_->count = 0;
        flashTrapDamage_->count = 0;
    }
    
    /* load items */
    healthPotion_->item = itemManager->effectiveItemForObjectId(effectiveItemsOID[kMCHealthPotion]);
    healthPotion_->item->retain();
    physicalPotion_->item = itemManager->effectiveItemForObjectId(effectiveItemsOID[kMCPhysicalPotion]);
    physicalPotion_->item->retain();
    fireballTrapWide_->item = itemManager->effectiveItemForObjectId(effectiveItemsOID[kMCFireballWide]);
    fireballTrapWide_->item->retain();
    fireballTrapDamage_->item = itemManager->effectiveItemForObjectId(effectiveItemsOID[kMCFireballDamage]);
    fireballTrapDamage_->item->retain();
    curseTrapWide_->item = itemManager->effectiveItemForObjectId(effectiveItemsOID[kMCCurseWide]);
    curseTrapWide_->item->retain();
    curseTrapDamage_->item = itemManager->effectiveItemForObjectId(effectiveItemsOID[kMCCurseDamage]);
    curseTrapDamage_->item->retain();
    paralysisTrapWide_->item = itemManager->effectiveItemForObjectId(effectiveItemsOID[kMCParalysisWide]);
    paralysisTrapWide_->item->retain();
    paralysisTrapDamage_->item = itemManager->effectiveItemForObjectId(effectiveItemsOID[kMCParalysisDamage]);
    paralysisTrapDamage_->item->retain();
    fogTrapWide_->item = itemManager->effectiveItemForObjectId(effectiveItemsOID[kMCFogWide]);
    fogTrapWide_->item->retain();
    fogTrapDamage_->item = itemManager->effectiveItemForObjectId(effectiveItemsOID[kMCFogDamage]);
    fogTrapDamage_->item->retain();
    flashTrapWide_->item = itemManager->effectiveItemForObjectId(effectiveItemsOID[kMCFlashWide]);
    flashTrapWide_->item->retain();
    flashTrapDamage_->item = itemManager->effectiveItemForObjectId(effectiveItemsOID[kMCFlashDamage]);
    flashTrapDamage_->item->retain();
}
Esempio n. 24
0
//쓰레드펑션
void* GraphDog::t_function(void *_insertIndex)
{	
	int insertIndex = (int)_insertIndex;
//	std::map<int, CommandType>& commands = graphdog->commands;
//	pthread_mutex_lock(&graphdog->cmdsMutex);
	CommandsType& command = graphdog->commandQueue[insertIndex];
	pthread_mutex_lock(&command.caller->t_functionMutex);
	string token=GraphDog::get()->getToken();
	string paramStr = toBase64(desEncryption(graphdog->sKey, command.commandStr));
	string dataset = "&token=" + token + "&command=" + paramStr + "&appver=" + GraphDog::get()->getAppVersionString();
	
    string commandurl = "http://www.graphdog.net/command/";
    commandurl=commandurl.append(GraphDog::get()->getGraphDogVersion());
    commandurl=commandurl.append("/");
    commandurl=commandurl.append(GraphDog::get()->aID);
    
	// << "&param=" << paramStr
	//curl으로 명령을 날리고 겨로가를 얻는다.
	CURL *handle = GraphDog::get()->getCURL();
    curl_easy_setopt(handle, CURLOPT_URL, commandurl.c_str());
	curl_easy_setopt(handle, CURLOPT_POSTFIELDS,dataset.c_str());
	curl_easy_setopt(handle, CURLOPT_WRITEDATA, (void *)&command.chunk);
	
	//		curl_setopt($ch,CURLOPT_TIMEOUT,1000);
//	pthread_mutex_unlock(&graphdog->cmdsMutex);
	CURLcode resultCode = curl_easy_perform(handle);
	
	//##
	JsonBox::Object resultobj;
	string resultStr;
	if(resultCode == CURLE_OK)
	{
		resultStr = command.chunk.memory;// gdchunk.memory;
		if(*resultStr.rbegin() == '#') // success
		{
			try
			{
				vector<char> encText = base64To(std::string(resultStr.begin(), resultStr.end() - 1) ); // unbase64
				resultStr = desDecryption(graphdog->sKey, std::string(encText.begin(), encText.end())); // des Decryption
				resultobj = GraphDogLib::StringToJsonObject(resultStr);// result.getObject();
			}
			catch(const std::string& msg)
			{
				resultCode = CURLE_CHUNK_FAILED;
			}
		}
		else
		{
			resultCode = CURLE_CHUNK_FAILED;
		}
	}
	else
	{
		//resultCode = CURLE_CHUNK_FAILED;
	}
	
	//callbackparam 통신과 무관함. 넣어준거 그대로 피드백.
	for(auto iter = command.commands.begin(); iter != command.commands.end(); ++iter)
	{
		if(iter->second.paramStr != "")
		{
			JsonBox::Object param = GraphDogLib::StringToJsonObject(iter->second.paramStr);
			resultobj[iter->first]["param"] = JsonBox::Value(param);
		}
	}
	
	bool newToken = false;
	// 새토큰발급일 경우
	if(resultobj["tokenUpdate"].getString()=="ok"){
		//정상결과시 AuID,Token 다시 세팅
		if(resultobj["state"].getString()=="ok"){
			command.caller->setAuID(resultobj["auID"].getString());
			command.caller->setCTime(resultobj["createTime"].getString());
			command.caller->isLogin=true;
		}else{
			command.caller->setCTime("9999");
		}
		//첫실행일경우 받아온 nick,flag 저장.
//		if(resultobj["isFirst"].getBoolean()==true){
//			command.caller->setNick(resultobj["nick"].getString());
//			command.caller->setFlag(resultobj["flag"].getString());
//		}
		//기존명령 다시 등록
		std::vector<CommandParam> vcp;
		for(std::map<string, CommandType>::const_iterator iter = command.commands.begin(); iter != command.commands.end(); ++iter)
		{
			JsonBox::Value param;
			param.loadFromString(iter->second.paramStr);
			vcp.push_back(CommandParam(iter->second.action, param.getObject(), iter->second.target, iter->second.selector ));
		}
		command.caller->command(vcp);
		
		for(std::map<string, CommandType>::iterator iter = command.commands.begin(); iter != command.commands.end(); ++iter)
		{
			iter->second.target = 0;
			iter->second.selector = 0;
		}
		newToken = true;
	}
	
	if(resultobj["errorcode"].getInt()==9999){
		command.caller->setCTime("9999");
		command.caller->errorCount++;
		if(command.caller->errorCount<5){
			std::vector<CommandParam> vcp;
			for(std::map<string, CommandType>::const_iterator iter = command.commands.begin(); iter != command.commands.end(); ++iter)
			{
				JsonBox::Value param;
				param.loadFromString(iter->second.paramStr);
				CommandParam cp;
				cp.action = iter->second.action;
				cp.param = param.getObject();
				cp.selector = iter->second.selector;
				cp.target = iter->second.target;
				vcp.push_back(cp);
			}
			command.caller->command(vcp);
			for(std::map<string, CommandType>::iterator iter = command.commands.begin(); iter != command.commands.end(); ++iter)
			{
				iter->second.target = 0;
				iter->second.selector = 0;
			}
		}
		newToken = true;
	}
	
	if(newToken == false) // 새토큰 발급이 아닌 경우.
	{
//		for(auto iter = command.commands.begin(); iter != command.commands.end(); ++iter)
//		{
//			CommandType test = iter->second;
//			CCLog("dummy");
//		}
		if(resultobj["state"].getString()=="ok"){
			command.caller->errorCount=0;
		}
		command.result = resultobj;
		command.chunk.resultCode = resultCode;
	}
	pthread_mutex_unlock(&command.caller->t_functionMutex);
	
	return NULL;
}
void
MCItemManager::loadEquipmentItems()
{
    JsonBox::Value weapon;
    JsonBox::Value armor;
    JsonBox::Object root;
    JsonBox::Object::iterator rootIterator;
    MCOreManager *oreManager = MCOreManager::sharedOreManager();
    
    /* 读取武器 */
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
    CCString* pstrFileContent = CCString::createWithContentsOfFile(kMCEquipmentItemWeaponFilepath);
    if (pstrFileContent) {
        weapon.loadFromString(pstrFileContent->getCString());
    }
#else
    weapon.loadFromFile(CCFileUtils::sharedFileUtils()->fullPathForFilename(kMCEquipmentItemWeaponFilepath).c_str());
#endif
    
    root = weapon.getObject();
    for (rootIterator = root.begin(); rootIterator != root.end(); ++rootIterator) {
        const char *c_str_o_id = rootIterator->first.c_str();
        JsonBox::Object object = rootIterator->second.getObject();
        mc_object_id_t o_id = {
            c_str_o_id[0],
            c_str_o_id[1],
            c_str_o_id[2],
            c_str_o_id[3]
        };
        MCEquipmentItem *item = MCEquipmentItem::create(MCEquipment::MCWeapon);
        CCString *ccstring;
        
        item->setID(o_id);
        ccstring = CCString::create(object["name"].getString().c_str());
        item->setName(ccstring);
        ccstring->retain();
        ccstring = CCString::create(object["icon"].getString().c_str());
        item->setIcon(ccstring);
        ccstring->retain();
        item->setPrice(object["price"].getInt());
        JsonBox::Object damage = object["damage"].getObject();
        
        MCWeapon *equipment = dynamic_cast<MCWeapon *>(item->equipment_);
        
        /* effect-id */
        c_str_o_id = object["effect-id"].getString().c_str();
        mc_object_id_t e_id = {
            c_str_o_id[0],
            c_str_o_id[1],
            c_str_o_id[2],
            c_str_o_id[3]
        };
        MCEffectManager *effectManager = MCEffectManager::sharedEffectManager();
        MCEffect *effect = effectManager->effectForObjectId(e_id);
        equipment->attackEffect = effect;
        effect->retain();
        
        equipment->damage = MCMakeDiceType(damage["count"].getInt(), damage["size"].getInt());
        equipment->criticalHit = object["critical-hit"].getInt();
        JsonBox::Object diceRange = object["critical-hit-visible"].getObject();
        JsonBox::Object diceRangeDice = diceRange["dice"].getObject();
        equipment->criticalHitVisible.min = diceRange["min"].getInt();
        equipment->criticalHitVisible.max = diceRange["max"].getInt();
        equipment->criticalHitVisible.dice = MCMakeDiceType(diceRangeDice["count"].getInt(),
                                                              diceRangeDice["size"].getInt());
        diceRange = object["critical-hit-invisible"].getObject();
        diceRangeDice = diceRange["dice"].getObject();
        equipment->criticalHitInvisible.min = diceRange["min"].getInt();
        equipment->criticalHitInvisible.max = diceRange["max"].getInt();
        equipment->criticalHitInvisible.dice = MCMakeDiceType(diceRangeDice["count"].getInt(),
                                                              diceRangeDice["size"].getInt());
        equipment->distance = object["distance"].getInt();
        if (object["effect"].isInteger()) {
            equipment->effect = object["effect"].getInt();
            diceRange = object["effect-check"].getObject();
            diceRangeDice = diceRange["dice"].getObject();
            equipment->effectCheck.min = diceRange["min"].getInt();
            equipment->effectCheck.max = diceRange["max"].getInt();
            equipment->effectCheck.dice = MCMakeDiceType(diceRangeDice["count"].getInt(),
                                                          diceRangeDice["size"].getInt());
        } else {
            equipment->effect = MCNormalState;
        }
        
        /* consume Double */
        equipment->consume = object["consume"].isDouble()
                              ? (float) object["consume"].getDouble()
                              : (float) object["consume"].getInt();
        equipment->dexterity = object["dexterity"].getInt();
        
        /* action-effect String */
        equipment->actionEffect.assign(object["action-effect"].getString());
        
        /* 读取默认矿石,加载背包的时候更新为正确矿石 */
        item->ore_ = oreManager->defaultOre();
        equipmentItems_->setObject(item, MCObjectIdToDickKey(o_id));
    }
    
    /* 读取防具 */
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
    pstrFileContent = CCString::createWithContentsOfFile(kMCEquipmentItemArmorFilepath);
    if (pstrFileContent) {
        armor.loadFromString(pstrFileContent->getCString());
    }
#else
    armor.loadFromFile(CCFileUtils::sharedFileUtils()->fullPathForFilename(kMCEquipmentItemArmorFilepath).c_str());
#endif
    
    root = armor.getObject();
    for (rootIterator = root.begin(); rootIterator != root.end(); ++rootIterator) {
        const char *c_str_o_id = rootIterator->first.c_str();
        JsonBox::Object object = rootIterator->second.getObject();
        mc_object_id_t o_id = {
            c_str_o_id[0],
            c_str_o_id[1],
            c_str_o_id[2],
            c_str_o_id[3]
        };
        MCEquipmentItem *item = MCEquipmentItem::create(MCEquipment::MCArmor);
        CCString *ccstring;
        
        item->setID(o_id);
        ccstring = CCString::create(object["name"].getString().c_str());
        item->setName(ccstring);
        ccstring->retain();
        ccstring = CCString::create(object["description"].getString().c_str());
        item->setDescription(ccstring);
        ccstring->retain();
        ccstring = CCString::create(object["icon"].getString().c_str());
        item->setIcon(ccstring);
        ccstring->retain();
        item->setPrice(object["price"].getInt());
        
        MCArmor *equipment = dynamic_cast<MCArmor *>(item->equipment_);
        equipment->defense = object["defense"].getInt();
        equipment->dexterity = object["dexterity"].getInt();
        equipment->armorCheckPenalty = object["armor-check-penalty"].getInt();
        /* 读取默认矿石,加载背包的时候更新为正确矿石 */
        item->ore_ = oreManager->defaultOre();
        equipmentItems_->setObject(item, MCObjectIdToDickKey(o_id));
    }
}
void
MCItemManager::loadEffectiveItems()
{
    JsonBox::Value v;
    JsonBox::Object root;
    JsonBox::Object::iterator rootIterator;
    MCEffectiveItem *item;
    MCEffectManager *effectManager = MCEffectManager::sharedEffectManager();
    
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
    CCString* pstrFileContent = CCString::createWithContentsOfFile(kMCEffectiveItemFilepath);
    if (pstrFileContent) {
        v.loadFromString(pstrFileContent->getCString());
    }
#else
    v.loadFromFile(CCFileUtils::sharedFileUtils()->fullPathForFilename(kMCEffectiveItemFilepath).c_str());
#endif
    
    root = v.getObject();
    for (rootIterator = root.begin(); rootIterator != root.end(); ++rootIterator) {
        const char *c_str_o_id = rootIterator->first.c_str();
        JsonBox::Object object = rootIterator->second.getObject();
        mc_object_id_t o_id = {
            c_str_o_id[0],
            c_str_o_id[1],
            c_str_o_id[2],
            c_str_o_id[3]
        };
        
        if (o_id.class_ == 'P') {
            item = MCEffectiveItem::create();
        } else {
            MCTrap *trap = new MCTrap;
            
            trap->init(o_id);
            trap->autorelease();
            item = trap;
        }
        CCString *ccstring;
        
        item->setID(o_id);
        ccstring = CCString::create(object["name"].getString().c_str());
        item->setName(ccstring);
        ccstring->retain();
        ccstring = CCString::create(object["description"].getString().c_str());
        item->setDescription(ccstring);
        ccstring->retain();
        ccstring = CCString::create(object["icon"].getString().c_str());
        item->setIcon(ccstring);
        ccstring->retain();
        
        /* effect-id */
        c_str_o_id = object["effect-id"].getString().c_str();
        mc_object_id_t e_id = {
            c_str_o_id[0],
            c_str_o_id[1],
            c_str_o_id[2],
            c_str_o_id[3]
        };
        MCEffect *effect = effectManager->effectForObjectId(e_id);
        item->effect = effect;
        effect->retain();
        
        item->setPrice(object["price"].getInt());
        item->radius = object["radius"].getInt() * 24 / CC_CONTENT_SCALE_FACTOR(); /* 24为一个单位 */
        item->hp = object["hp"].getInt();
        item->pp = object["pp"].getInt();
        item->positive_state = object["positive-state"].getInt();
        item->lasting_time = object["lasting-time"].isDouble()
                                ? (float) object["lasting-time"].getDouble()
                                : (float) object["lasting-time"].getInt();
        
        effectiveItems_->setObject(item, MCObjectIdToDickKey(o_id));
    }
}
Esempio n. 27
0
File: Army.cpp Progetto: skji/miwu
void Army::onInfoRequestCompleted(CCHttpClient *sender, CCHttpResponse *response)
{
    if (!response)
    {
        return;
    }
    
    // You can get original request type from: response->request->reqType
    if (0 != strlen(response->getHttpRequest()->getTag()))
    {
        CCLog("%s completed", response->getHttpRequest()->getTag());
    }
    
    int statusCode = response->getResponseCode();
    char statusString[64] = {};
    sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag());
    CCLog("response code: %d", statusCode);
    
    if (!response->isSucceed())
    {
        CCLog("response failed");
        CCLog("error buffer: %s", response->getErrorBuffer());
        return;
    }
    
    // dump data
    std::vector<char> *buffer = response->getResponseData();
    const std::string jsonStr(buffer->begin(),buffer->end());
    JsonBox::Value json;
    json.loadFromString(jsonStr);
    
    if (json["data"]["isSuccess"].getBoolean()) {
        this->clearArmyShow();
        JsonBox::Array arms = json["data"]["arms"].getArray();
        for (i = 0; i < 9; i++) {
          switch(atoi(arms[i]["armId"].getString().c_str())) {
          case 1:
            if(atoi(arms[i]["level"].getString().c_str())>0) {
              this->show_s1->setVisible(true);
            }
            break;
          case 2:
            if(atoi(arms[i]["level"].getString().c_str())>0) {
              this->show_s2->setVisible(true);
            }
            break;
          case 3:
            if(atoi(arms[i]["level"].getString().c_str())>0) {
              this->show_s3->setVisible(true);
            }
            break;
          case 4:
            if(atoi(arms[i]["level"].getString().c_str())>0) {
              this->show_s4->setVisible(true);
            }
            break;
          case 5:
            if(atoi(arms[i]["level"].getString().c_str())>0) {
              this->show_s5->setVisible(true);
            }
            break;
          case 6:
            if(atoi(arms[i]["level"].getString().c_str())>0) {
              this->show_s6->setVisible(true);
            }
            break;
          case 7:
            if(atoi(arms[i]["level"].getString().c_str())>0) {
              this->show_s7->setVisible(true);
            }
            break;
          case 8:
            if(atoi(arms[i]["level"].getString().c_str())>0) {
              this->show_s8->setVisible(true);
            }
            break;
          case 9:
            if(atoi(arms[i]["level"].getString().c_str())>0) {
              this->show_s9->setVisible(true);
            }
            break;
          }
        }
    }
}
Esempio n. 28
0
inline void unserialize(const JsonBox::Value & o, f32 & v) { v = o.getDouble(); }
Esempio n. 29
0
inline void unserialize(const JsonBox::Value & o, std::string & s) { s = o.getString(); }
Esempio n. 30
0
inline void unserialize(const JsonBox::Value & o, u8 & v) { v = o.getInt(); }