• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C++ ValueMap类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中ValueMap的典型用法代码示例。如果您正苦于以下问题:C++ ValueMap类的具体用法?C++ ValueMap怎么用?C++ ValueMap使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了ValueMap类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: valmap_check

LLVMBool valmap_check(valmap_t map, LLVMValueRef v)
{
  ValueMap<Value*,void*> *vmap = (ValueMap<Value*,void*>*)map;
  Value *val = unwrap(v);
  return (LLVMBool)(vmap->find(val)!=vmap->end());
}
开发者ID:yzhao30,项目名称:llvm-project-template,代码行数:6,代码来源:valmap.cpp


示例2: toValueMap

/*
 * For converting param specs for Regions and LinkPolicies
 */
ValueMap toValueMap(const char *yamlstring,
                    Collection<ParameterSpec> &parameters,
                    const std::string &nodeType,
                    const std::string &regionName) {

  ValueMap vm;

  // special value that applies to all regions.
  ParameterSpec dim_spec("Buffer dimensions for region's global dimensions. "
                    "Syntax: {dim: [2,3]}",  // description
	                  NTA_BasicType_UInt32,
							      0,                         // elementCount (an array of unknown size)
							      "",                        // constraints
							      "",                        // defaultValue
							      ParameterSpec::ReadWriteAccess);


  std::string paddedstring(yamlstring);
  // TODO: strip white space to determine if empty
  bool empty = (paddedstring.size() == 0);

  // TODO: utf-8 compatible?
  const YAML::Node doc = YAML::Load(paddedstring);
  if(!empty) {
    // A ValueMap is specified as a dictionary
    if (doc.Type() != YAML::NodeType::Map) {
      std::string ys(yamlstring);
      if (ys.size() > 30) {
        ys = ys.substr(0, 30) + "...";
      }
      NTA_THROW
          << "YAML string '" << ys
          << "' does not not specify a dictionary of key-value pairs. "
          << "Region and Link parameters must be specified as a dictionary";
    }
  }
  // Grab each value out of the YAML dictionary and put into the ValueMap
  // if it is allowed by the nodespec.
  for (auto i = doc.begin(); i != doc.end(); i++)
  {
    ParameterSpec ps;

    const auto key = i->first.as<std::string>();
    if (key == "dim")
      ps = dim_spec;
    else {
      if (!parameters.contains(key))
      {
        std::stringstream ss;
        for (UInt j = 0; j < parameters.getCount(); j++){
          ss << "   " << parameters.getByIndex(j).first << "\n";
        }

        if (nodeType == std::string("")) {
          NTA_THROW << "Unknown parameter '" << key << "'\n"
                    << "Valid parameters are:\n" << ss.str();
        } else {
          NTA_CHECK(regionName != std::string(""));
          NTA_THROW << "Unknown parameter '" << key << "' for region '"
                    << regionName << "' of type '" << nodeType << "'\n"
                    << "Valid parameters are:\n"
                    << ss.str();
        }
      }
      ps = parameters.getByName(key); // makes a copy of ParameterSpec
    }
    if (vm.contains(key))
        NTA_THROW << "Parameter '" << key << "' specified more than once in YAML document";
    try
    {
      if (ps.accessMode == ParameterSpec::ReadOnlyAccess) {
        NTA_THROW << "Parameter '" << key << "'. This is ReadOnly access. Cannot be set.";
      }
      Value v = toValue(i->second, ps.dataType);
      if (v.isScalar() && ps.count != 1)
      {
        NTA_THROW << "Parameter '" << key << "'. Bad value in runtime parameters. Expected array value but got scalar value";
      }
      if (!v.isScalar() && ps.count == 1)
      {
        NTA_THROW << "Parameter '" << key << "'. Bad value in runtime parameters. Expected scalar value but got array value";
      }
      vm.add(key, v);
    } catch (std::runtime_error &e) {
      NTA_THROW << "Unable to set parameter '" << key << "'. " << e.what();
    }
  } //end for

  // Populate ValueMap with default values if they were not specified in the YAML dictionary.
  for (size_t i = 0; i < parameters.getCount(); i++)
  {
    const std::pair<std::string, ParameterSpec>& item = parameters.getByIndex(i);
    if (!vm.contains(item.first))
    {
      const ParameterSpec & ps = item.second;
      if (ps.defaultValue != "")
      {
//.........这里部分代码省略.........
开发者ID:breznak,项目名称:nupic.core,代码行数:101,代码来源:YAMLUtils.cpp


示例3: startElement

    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;
        }
    }
开发者ID:253056965,项目名称:cocos2d-x-lite,代码行数:90,代码来源:CCFileUtils.cpp


示例4: CC_UNUSED_PARAM

// 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 = (char*)name;
    ValueMap attributeDict;
    if (atts && atts[0])
    {
        for(int i = 0; atts[i]; i += 2) 
        {
            std::string key = (char*)atts[i];
            std::string value = (char*)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
            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 != "")
        {
            // 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.c_str());
            
            _currentFirstGID = attributeDict["firstgid"].asInt();
            if (_currentFirstGID < 0)
            {
                _currentFirstGID = 0;
            }
            _recordFirstGID = false;
            
            tmxMapInfo->parseXMLFile(externalTilesetFilename.c_str());
        }
        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;

//.........这里部分代码省略.........
开发者ID:12301043-slc,项目名称:thiefTD,代码行数:101,代码来源:CCTMXXMLParser.cpp


示例5: initWithDictionary

bool ParticleSystem::initWithDictionary(ValueMap& dictionary, const std::string& dirname)
{
    bool ret = false;
    unsigned char *buffer = nullptr;
    unsigned char *deflated = nullptr;
    Image *image = nullptr;
    do 
    {
        int maxParticles = dictionary["maxParticles"].asInt();
        // self, not super
        if(this->initWithTotalParticles(maxParticles))
        {
            // Emitter name in particle designer 2.0
            _configName = dictionary["configName"].asString();

            // angle
            _angle = dictionary["angle"].asFloat();
            _angleVar = dictionary["angleVariance"].asFloat();

            // duration
            _duration = dictionary["duration"].asFloat();

            // blend function 
            if (_configName.length()>0)
            {
                _blendFunc.src = dictionary["blendFuncSource"].asFloat();
            }
            else
            {
                _blendFunc.src = dictionary["blendFuncSource"].asInt();
            }
            _blendFunc.dst = dictionary["blendFuncDestination"].asInt();

            // color
            _startColor.r = dictionary["startColorRed"].asFloat();
            _startColor.g = dictionary["startColorGreen"].asFloat();
            _startColor.b = dictionary["startColorBlue"].asFloat();
            _startColor.a = dictionary["startColorAlpha"].asFloat();

            _startColorVar.r = dictionary["startColorVarianceRed"].asFloat();
            _startColorVar.g = dictionary["startColorVarianceGreen"].asFloat();
            _startColorVar.b = dictionary["startColorVarianceBlue"].asFloat();
            _startColorVar.a = dictionary["startColorVarianceAlpha"].asFloat();

            _endColor.r = dictionary["finishColorRed"].asFloat();
            _endColor.g = dictionary["finishColorGreen"].asFloat();
            _endColor.b = dictionary["finishColorBlue"].asFloat();
            _endColor.a = dictionary["finishColorAlpha"].asFloat();

            _endColorVar.r = dictionary["finishColorVarianceRed"].asFloat();
            _endColorVar.g = dictionary["finishColorVarianceGreen"].asFloat();
            _endColorVar.b = dictionary["finishColorVarianceBlue"].asFloat();
            _endColorVar.a = dictionary["finishColorVarianceAlpha"].asFloat();

            // particle size
            _startSize = dictionary["startParticleSize"].asFloat();
            _startSizeVar = dictionary["startParticleSizeVariance"].asFloat();
            _endSize = dictionary["finishParticleSize"].asFloat();
            _endSizeVar = dictionary["finishParticleSizeVariance"].asFloat();

            // position
            float x = dictionary["sourcePositionx"].asFloat();
            float y = dictionary["sourcePositiony"].asFloat();
            this->setPosition( Vec2(x,y) );            
            _posVar.x = dictionary["sourcePositionVariancex"].asFloat();
            _posVar.y = dictionary["sourcePositionVariancey"].asFloat();

            // Spinning
            _startSpin = dictionary["rotationStart"].asFloat();
            _startSpinVar = dictionary["rotationStartVariance"].asFloat();
            _endSpin= dictionary["rotationEnd"].asFloat();
            _endSpinVar= dictionary["rotationEndVariance"].asFloat();

            _emitterMode = (Mode) dictionary["emitterType"].asInt();

            // Mode A: Gravity + tangential accel + radial accel
            if (_emitterMode == Mode::GRAVITY)
            {
                // gravity
                modeA.gravity.x = dictionary["gravityx"].asFloat();
                modeA.gravity.y = dictionary["gravityy"].asFloat();

                // speed
                modeA.speed = dictionary["speed"].asFloat();
                modeA.speedVar = dictionary["speedVariance"].asFloat();

                // radial acceleration
                modeA.radialAccel = dictionary["radialAcceleration"].asFloat();
                modeA.radialAccelVar = dictionary["radialAccelVariance"].asFloat();

                // tangential acceleration
                modeA.tangentialAccel = dictionary["tangentialAcceleration"].asFloat();
                modeA.tangentialAccelVar = dictionary["tangentialAccelVariance"].asFloat();
                
                // rotation is dir
                modeA.rotationIsDir = dictionary["rotationIsDir"].asBool();
            }

            // or Mode B: radius movement
            else if (_emitterMode == Mode::RADIUS)
//.........这里部分代码省略.........
开发者ID:CatalystApps,项目名称:Cocos2dxv3_GAFSampleGame,代码行数:101,代码来源:CCParticleSystem.cpp


示例6: AsJSON

String AsJSON(const Value& v, const String& sep, bool pretty)
{
	String r;
	if(v.GetType() == VALUEMAP_V) {
		r << "{";
		String sep1;
		if(pretty) {
			r << "\r\n";
			sep1 = sep + '\t';
		}
		ValueMap m = v;
		ValueArray va = m.GetValues();
		for(int i = 0; i < m.GetCount(); i++) {
			if(i) {
				r << ",";
				if(pretty)
					r << "\r\n";
			}
			if(pretty)
				r << sep1;
			r << AsJSON((String)m.GetKey(i)) << (pretty ? ": " : ":")
			  << AsJSON(va[i], sep1, pretty);
		}
		if(pretty)
			r << "\r\n" << sep;
		r << "}";
		return r;
	}
	if(v.GetType() == VALUEARRAY_V) {
		r << "[";
		String sep1;
		if(pretty) {
			r << "\r\n";
			sep1 = sep + '\t';
		}
		ValueArray va = v;
		for(int i = 0; i < va.GetCount(); i++) {
			if(i) {
				r << ",";
				if(pretty)
					r << "\r\n";
			}
			if(pretty)
				r << sep1;
			r << AsJSON(va[i], sep1, pretty);
		}
		if(pretty)
			r << "\r\n" << sep;
		r << "]";
		return r;
	}
	if(IsNumber(v) && IsNull(v))
		return "null";
	if(v.GetType() == INT_V)
		return Format("%d", (int)v);
	if(v.GetType() == BOOL_V)
		return (bool)v ? "true" : "false";
	if(IsNumber(v))
		return Format("%.16g", (double)v);
	if(IsString(v))
		return AsCString((String)v, INT_MAX, NULL, ASCSTRING_JSON);
	if(IsDateTime(v))
		return AsJSON((Time)v);
	if(IsNull(v))
		return "null";
	NEVER_("Non-JSON value in AsJSON: " + v.GetTypeName());
	return "null";
}
开发者ID:koz4k,项目名称:soccer,代码行数:68,代码来源:JSON.cpp


示例7: ValueMap2SFSObject

static jobject ValueMap2SFSObject(JNIEnv* env, const ValueMap& valueMap, jobject javaObj)
{
    jclass cls = env->GetObjectClass(javaObj);
    if (!cls) return javaObj;

    for (auto it = valueMap.begin(); it != valueMap.end(); ++it)
    {
        jobject javaKey = env->NewStringUTF(it->first.c_str());
        if (it->second.getType() == Value::Type::BYTE)
        {
            jmethodID mid = env->GetMethodID(cls, "putByte", "(Ljava/lang/String;B)V");
            if (mid) env->CallVoidMethod(javaObj, mid, javaKey, it->second.asByte());
        }
        else if (it->second.getType() == Value::Type::INTEGER)
        {
            jmethodID mid = env->GetMethodID(cls, "putInt", "(Ljava/lang/String;I)V");
            if (mid) env->CallVoidMethod(javaObj, mid, javaKey, it->second.asInt());
        }
        else if (it->second.getType() == Value::Type::FLOAT)
        {
            jmethodID mid = env->GetMethodID(cls, "putFloat", "(Ljava/lang/String;F)V");
            if (mid) env->CallVoidMethod(javaObj, mid, javaKey, it->second.asFloat());
        }
        else if (it->second.getType() == Value::Type::DOUBLE)
        {
            jmethodID mid = env->GetMethodID(cls, "putFloat", "(Ljava/lang/String;F)V");
            if (mid) env->CallVoidMethod(javaObj, mid, javaKey, it->second.asDouble());
        }
        else if (it->second.getType() == Value::Type::BOOLEAN)
        {
            jmethodID mid = env->GetMethodID(cls, "putBool", "(Ljava/lang/String;Z)V");
            if (mid) env->CallVoidMethod(javaObj, mid, javaKey, it->second.asBool());
        }
        else if (it->second.getType() == Value::Type::STRING)
        {
            jmethodID mid = env->GetMethodID(cls, "putUtfString", "(Ljava/lang/String;Ljava/lang/String;)V");
            if (mid)
            {
                jobject javaValue = env->NewStringUTF(it->second.asString().c_str());
                env->CallVoidMethod(javaObj, mid, javaKey, javaValue);
                env->DeleteLocalRef(javaValue);
            }
        }
        else if (it->second.getType() == Value::Type::VECTOR)
        {
            jmethodID mid = env->GetMethodID(cls, "putSFSArray", "(Ljava/lang/String;Lcom/smartfoxserver/v2/entities/data/ISFSArray;)V");
            if (mid)
            {
                jobject javaSFSArray = getSFSArray(env);
                jobject javaValue = ValueVector2SFSArray(env, it->second.asValueVector(), javaSFSArray);
                env->CallVoidMethod(javaObj, mid, javaKey, javaValue);
                env->DeleteLocalRef(javaValue);
            }
        }
        else if (it->second.getType() == Value::Type::MAP)
        {
            jmethodID mid = env->GetMethodID(cls, "putSFSObject", "(Ljava/lang/String;Lcom/smartfoxserver/v2/entities/data/ISFSObject;)V");
            if (mid)
            {
                jobject sub_obj = getSFSObject(env);
                jobject javaValue = ValueMap2SFSObject(env, it->second.asValueMap(), sub_obj);
                env->CallVoidMethod(javaObj, mid, javaKey, javaValue);
                env->DeleteLocalRef(javaValue);
            }
        }
        else if (it->second.getType() == Value::Type::INT_KEY_MAP)
        {

        }
        env->DeleteLocalRef(javaKey);
    }
    env->DeleteLocalRef(cls);

    return javaObj;
}
开发者ID:ourgames,项目名称:nbg,代码行数:75,代码来源:NBGNetManager.cpp


示例8: CC_CALLBACK_2

// on "init" you need to initialize your instance
bool HelloWorld::init() {
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() ){
        return false;
    }
    
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();
	
	/* REGISTERING TOUCH EVENTS
	 ===================================================== */
	auto controls = EventListenerTouchAllAtOnce::create();
	controls->onTouchesBegan = CC_CALLBACK_2(HelloWorld::onTouchesBegan, this);
	_eventDispatcher->addEventListenerWithSceneGraphPriority(controls, this);

	/*  NOTE: don't get in the habit of using auto everywhere
		An iron price to be paid (extra time == life) masquerading as convenience
		No reference can be made with auto and makes code unreadable
		Justified here since controls is a one-off and will not
		be referenced anywhere else but in this temporal block
		
		ALSO: This is what is called a observer pattern in the industry
		controls would be an "interface" of known `subscribers` to the _eventDispatcher `publisher` 
		and events are "published" to the subscribers as they happen. Interface just means a 
		contractual agreement between different parts of code to follow a uniform language
	*/

	/* CREATE A TMXTILEDMAP AND EXTRACT LAYER FOR DISPLAY
	 ===================================================== */
	_tileMap = TMXTiledMap::create("TileMap.tmx");
	// DEPRECATED: _tileMap = new CCTMXTiledMap();
	//			   _tileMap->initWithTMXFile("TileMap.tmx");

	_background = _tileMap->getLayer("Background");
	// DEPRECATED: _tileMap->layerNamed("Background");

	_meta = _tileMap->layerNamed("Meta");
	_meta->setVisible(false);

	this->addChild(_tileMap);

	TMXObjectGroup *objectGroup = _tileMap->objectGroupNamed("Objects");
	// DEPRECATED: CCTMXObjectGroup *objectGroup = _tileMap->objectGroupNamed("Objects");

	if(objectGroup == NULL) {
		CCLOG("tile map has no Objects object layer");
		// DEPRECATED: CCLog("tile map has no objects object layer");
		return false;
	}

	ValueMap spawnPoint = objectGroup->objectNamed("SpawnPoint");
	// DEPRECATED:	CCDictionary *spawnPoint = objectGroup->objectNamed("SpawnPoint");
	Vec2 spawnHere = Point(300, 300);
	if(spawnPoint.size() != 0) {
		CCLOG("LOGCAT!!! There is a spawn point");
	} else {
		CCLOG("LOGCAT!!! There isn't a spawn point. Using default 300 x 300.");
	}

	_player = Sprite::create("Player.png");
	_player->setPosition(spawnHere);

	this->addChild(_player);
	this->setViewPointCenter(_player->getPosition());

	this->setTouchEnabled(true);

	/////////////////////////////
    // 2. add a menu item with "X" image, which is clicked to quit the program
    //    you may modify it.
    // create menu, it's an autorelease object
    // add a "close" icon to exit the progress. it's an autorelease object
    auto closeItem = MenuItemImage::create(
                                           "CloseNormal.png",
                                           "CloseSelected.png",
                                           CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));
    
	closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 ,
                                origin.y + closeItem->getContentSize().height/2));
    auto menu = Menu::create(closeItem, NULL);
    menu->setPosition(Vec2::ZERO);
    this->addChild(menu, 1);

    return true;
}
开发者ID:proxxzy,项目名称:TileMapV3.2,代码行数:87,代码来源:HelloWorldScene.cpp


示例9:

PushBoxScene::PushBoxScene()
{
    TMXTiledMap* mytmx = TMXTiledMap::create("Pushbox/map.tmx");
    mytmx->setPosition(visibleSize.width / 2, visibleSize.height / 2);
    mytmx->setAnchorPoint(Vec2(0,0));
    myx = (visibleSize.width - mytmx->getContentSize().width) / 2;
    myy = (visibleSize.height - mytmx->getContentSize().height) / 2;
    this->addChild(mytmx, 0);

    count = 0;
    success = 0;
    /*mon = Sprite::create("Pushbox/player.png");
    mon->setAnchorPoint(Vec2(0, 0));
    mon->setPosition(Vec2(SIZE_BLOCK*1+myx, SIZE_BLOCK*8+myy));
    mon->setTag(TAG_PLAYER);
    this->addChild(mon, 1);*/



    TMXObjectGroup* objects = mytmx->getObjectGroup("wall");
    //从对象层中获取对象数组
    ValueVector container = objects->getObjects();
    //遍历对象
    for (auto obj : container) {
        ValueMap values = obj.asValueMap();
        int x = values.at("x").asInt();
        int y = values.at("y").asInt();
        Sprite* temp = Sprite::create("Pushbox/wall.png");
        temp->setAnchorPoint(Point(0, 0));
        temp->setPosition(Point(x,y+64));
        mywall.pushBack(temp);
        this->addChild(temp, 1);
    }

    TMXObjectGroup* objects1 = mytmx->getObjectGroup("box");
    //从对象层中获取对象数组
    ValueVector container1 = objects1->getObjects();
    //遍历对象
    for (auto obj : container1) {
        ValueMap values = obj.asValueMap();
        int x = values.at("x").asInt();
        int y = values.at("y").asInt();
        Sprite* temp = Sprite::create("Pushbox/box.png");
        temp->setAnchorPoint(Point(0, 0));
        temp->setPosition(Point(x, y+64));
        mybox.pushBack(temp);
        this->addChild(temp, 3);
    }

    TMXObjectGroup* objects2 = mytmx->getObjectGroup("player");
    //从对象层中获取对象数组
    ValueVector container2 = objects2->getObjects();
    //遍历对象
    for (auto obj : container2) {
        ValueMap values = obj.asValueMap();
        int x = values.at("x").asInt();
        int y = values.at("y").asInt();
        Sprite* temp = Sprite::create("Pushbox/player.png");
        temp->setAnchorPoint(Point(0, 0));
        temp->setPosition(Point(x, y+64));
        mon = temp;
        this->addChild(temp, 2);
    }

    TMXObjectGroup* objects3 = mytmx->getObjectGroup("goal");
    //从对象层中获取对象数组
    ValueVector container3 = objects3->getObjects();
    //遍历对象
    for (auto obj : container3) {
        ValueMap values = obj.asValueMap();
        int x = values.at("x").asInt();
        int y = values.at("y").asInt();
        Sprite* temp = Sprite::create("Pushbox/goal.png");
        temp->setAnchorPoint(Point(0, 0));
        temp->setPosition(Point(x, y+64));
        mygoal.pushBack(temp);
        this->addChild(temp, 1);
    }
}
开发者ID:Coding-Le,项目名称:SE-Cocos2d-Course,代码行数:79,代码来源:PushBoxScene.cpp


示例10:

SimpleKLRetriever::SimpleKLRetriever(const ValueMap &col_probs_, double default_col_prob_, double dir_prior_):
	col_probs(col_probs_.copy()),
	default_col_prob(default_col_prob_),
	dir_prior(dir_prior_)
{
}
开发者ID:sylvanmist,项目名称:ucair_01,代码行数:6,代码来源:simple_index.cpp


示例11: CC_BREAK_IF

bool CNFServerChangeScrollLayer::InitLayer(int nItemNum)
{
    do
    {
        //初始化父类
        CC_BREAK_IF(CCLayerColor::initWithColor(Color4B(0,0,0,0))==false);
        
        
        //版本变化
        //独占触屏注册值小于-128才能屏蔽Menu(Menu默认是-128)
//        CCDirector::getInstance()->getTouchDispatcher()->addTargetedDelegate(this, -129, true);
        
        auto listener = EventListenerTouchOneByOne::create();
        listener->setSwallowTouches(true);
        
        listener->onTouchBegan = CC_CALLBACK_2(CNFServerChangeScrollLayer::onTouchBegan, this);
        listener->onTouchMoved = CC_CALLBACK_2(CNFServerChangeScrollLayer::onTouchMoved, this);
        listener->onTouchEnded = CC_CALLBACK_2(CNFServerChangeScrollLayer::onTouchEnded, this);
        listener->onTouchEnded = CC_CALLBACK_2(CNFServerChangeScrollLayer::onTouchCancelled, this);
        
        _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
        
        
//        setTouchEnabled(true);
        
        
        //初始x轴坐标
        m_fStartNodePosX = _X_START_POS_ + _NF_SCREEN_WIDTH_DIS_;
        
        ;		//页面数量
        int nPageNum = nItemNum%_ONE_PAGE_SERVER_NUM_ > 0 ? nItemNum/_ONE_PAGE_SERVER_NUM_+1 : nItemNum/_ONE_PAGE_SERVER_NUM_;
        
        //每一页宽度
        m_fPageWidth = _PAGE_WIDTH_;
        
        //页面高度
        float	fPageHeight = _PAGE_HEIGHT_;
        
        //x轴最小坐标
        m_fEndLayerPos = m_fPageWidth*(1-nPageNum);
        
        //x,y轴之间的间隔
        float fItemDisX = 11;
        float fItemDisY = 20;
        
        
        /************************************************************************/
        /*			创建按钮 
         
         
         */
        /************************************************************************/
        
//        版本变化
//        CCDictionary *pDicLang = CCDictionary::createWithContentsOfFile("ui_xml/serverselect_xml.xml");
//        CC_BREAK_IF(pDicLang==NULL);
        
        ValueMap pDicLang = FileUtils::getInstance()->getValueMapFromFile("ui_xml/serverselect_xml.xml");
         
        
        
        
        
        Menu * pMenu = Menu::create();
        CC_BREAK_IF(pMenu==NULL);
        pMenu->setPosition(Vec2::ZERO);
        addChild(pMenu,enZOrderFront,enTagMenu);
        
        //创建数组
        Ref *pObj = NULL;
        for (int k=1;k<=nItemNum;k++)
        {
            int i = k%_ONE_PAGE_SERVER_NUM_ > 0 ? k%_ONE_PAGE_SERVER_NUM_ : _ONE_PAGE_SERVER_NUM_;			//页面内ITem的ID:1~12
            int j = k%_ONE_PAGE_SERVER_NUM_ > 0 ? k/_ONE_PAGE_SERVER_NUM_+1 : k/_ONE_PAGE_SERVER_NUM_;		//当前页面ID
            
            int nCrossNum = i%3 == 0 ? 3 : i%3;				//横排
            int nVerticalNum = i%3 > 0 ? i/3+1 : i/3;		//竖排
            

            
            //创建按钮
            auto pBtn = MenuItemSprite::create(Sprite::create("ui/btn_enter_n.png"), Sprite::create("ui/btn_enter_p.png"), Sprite::create("ui/btn_enter_n.png"), CC_CALLBACK_1(CNFServerChangeScrollLayer::OnBtnCallBack, this) );
            CC_BREAK_IF(pBtn==NULL);
            pBtn->setPosition(Vec2( fItemDisX+ (nCrossNum-1)*(pBtn->getContentSize().width+fItemDisX) + m_fStartNodePosX + pBtn->getContentSize().width*0.5f + (j-1)*m_fPageWidth , fPageHeight-nVerticalNum*(pBtn->getContentSize().height+fItemDisY) + fItemDisY ));
            pMenu->addChild(pBtn,enZOrderFront,enTagBtn+k);
            
            //服务器名称label
//            std::string* 注意这里没有“*” pStrServerName = pDicLang.at("server_name").asString();
            std::string pStrServerName = pDicLang.at("server_name").asString();
            
            char szName[NAME_LEN] = {0};
            sprintf(szName,pStrServerName.c_str(),k);
            
            //版本变化
//            CCLabelTTF * pLabelServerName = CCLabelTTF::create(szName,"Arial",20);
//            CC_BREAK_IF(pLabelServerName==NULL);
            
            Label * pLabelServerName = Label::createWithSystemFont(szName, "Arial", 20);
            CC_BREAK_IF(pLabelServerName==NULL);
            
//.........这里部分代码省略.........
开发者ID:domzhaosh,项目名称:NCF2,代码行数:101,代码来源:NFServerChangeScrollLayer.cpp


示例12: CCAssert

void GB2ShapeCache::addShapesWithFile(const std::string &plist) {
    
	//const char *fullName = CCFileUtils::sharedFileUtils()->fullPathForFilename(plist.c_str()).c_str();
    ValueMap dict = FileUtils::getInstance()->getValueMapFromFile((plist.c_str()));
    // not triggered - cocos2dx delivers empty dict if non was found
    
	//CCAssert(dict != NULL, "Shape-file not found");
    
    CCAssert(!dict.empty(), "plist file empty or not existing");
	
	ValueMap metadataDict = dict.at("metadata").asValueMap();
    
    int format = metadataDict.at("format").asInt();
    ptmRatio = metadataDict.at("ptm_ratio").asFloat();
    log("ptmRatio = %f",ptmRatio);
	CCAssert(format == 1, "Format not supported");
    
    
	ValueMap bodyDict = dict.at("bodies").asValueMap();
    
    b2Vec2 vertices[b2_maxPolygonVertices];

    std::string bodyName;
	ValueMap bodyData;
    //iterate body list
    for(auto dictElem : bodyDict)
    //CCDICT_FOREACH(bodyDict,dictElem )
    {
        bodyData = dictElem.second.asValueMap();
        bodyName = dictElem.first;
        
        BodyDef *bodyDef = new BodyDef();
        bodyDef->anchorPoint = PointFromString(bodyData.at("anchorpoint").asString());
        ValueVector fixtureList = bodyData.at("fixtures").asValueVector();
        FixtureDef **nextFixtureDef = &(bodyDef->fixtures);
        
        //iterate fixture list
        //Ref *arrayElem;
        for(auto arrayElem : fixtureList)
        //CCARRAY_FOREACH(fixtureList, arrayElem)
        {
            b2FixtureDef basicData;
            ValueMap fixtureData = arrayElem.asValueMap();
            
            basicData.filter.categoryBits = fixtureData.at("filter_categoryBits").asInt();
            
            basicData.filter.maskBits = fixtureData.at("filter_maskBits").asInt();
            basicData.filter.groupIndex = fixtureData.at("filter_groupIndex").asInt();
            basicData.friction = fixtureData.at("friction").asFloat();
            
            basicData.density = fixtureData.at("density").asFloat();
            
            basicData.restitution = fixtureData.at("restitution").asFloat();
            //CCLog("%s", static_cast<__String *>(fixtureData->objectForKey("id"))->getCString());
            //basicData.userData = __String::create(static_cast<__String *>(fixtureData->objectForKey("id"))->getCString())->retain();
            
            basicData.isSensor = fixtureData.at("isSensor").asBool();
            
//            string cb = fixtureData.at("userdataCbValue").asString();
            
//            int callbackData = 0;
            
//			if (cb != "")
//				callbackData =fixtureData.at("userdataCbValue").asInt();
            
			std::string fixtureType = fixtureData.at("fixture_type").asString();
            
			if (fixtureType == "POLYGON") {
                ValueVector polygonsArray = fixtureData.at("polygons").asValueVector();
				
                //Ref *dicArrayElem;
                for(auto dicArrayElem : polygonsArray)
                //CCARRAY_FOREACH(polygonsArray, dicArrayElem)
                {
                    FixtureDef *fix = new FixtureDef();
                    fix->fixture = basicData; // copy basic data
//                    fix->callbackData = callbackData;
                    
                    b2PolygonShape *polyshape = new b2PolygonShape();
                    int vindex = 0;
                    
                    ValueVector polygonArray = dicArrayElem.asValueVector();
                    
                    assert(polygonArray.capacity() <= b2_maxPolygonVertices);
                    
                    //Ref *piter;
                    for(auto piter : polygonArray)
                    //CCARRAY_FOREACH(polygonArray, piter)
                    {
                        string verStr = piter.asString();
                        Point offset = PointFromString(verStr);
                        vertices[vindex].x = (offset.x / ptmRatio) ;
                        vertices[vindex].y = (offset.y / ptmRatio) ;
                        vindex++;
                    }
                    
                    polyshape->Set(vertices, vindex);
                    fix->fixture.shape = polyshape;
                    
                    // create a list
//.........这里部分代码省略.........
开发者ID:mengtest,项目名称:Radial-Gravity,代码行数:101,代码来源:GB2ShapeCache-x.cpp


示例13: Vec2

bool FiledScene::init(){
	if (!Layer::init())
		return false;
	
	_isGameOver = false;
	auto visibleSize = Director::getInstance()->getVisibleSize();
	_screenWidth = visibleSize.width;
	_screenHeight = visibleSize.height;

	_tileMap = TMXTiledMap::create("field_map.tmx");
	_tileMap->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
	_tileMap->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2));

	// ②获取障碍层,并设置障碍层为不可见
	_collidable = _tileMap->getLayer("collidable");
	_collidable->setVisible(false);
	/********③初始化读取地图所有网格,并确定网格对象是否是障碍物,将信息保存到网格二维数组**************/
	for (int i = 0; i < _tileMap->getMapSize().width; i++) {
		// 内部网格集合([x,0]-[x-20]),存储网格
		Vector<Grid*> inner;
		for (int j = 0; j < _tileMap->getMapSize().height; j++) {
			// 设置网格对象的x轴和y轴以及是否可通过变量值
			Grid *o = Grid::create(i, j);
			// 将网格加入到集合
			inner.pushBack(o);
		}
		// 将内部集合加入到网格集合
		_gridVector.push_back(inner);
	}
	// 循环保存根据每个网格的x轴和y轴查找对应的地图的GID,判断是否可通过
	for (int i = 0; i < _gridVector.size(); i++) {
		Vector<Grid*> inner = _gridVector.at(i);
		// 循环内部网格集合
		for (int j = 0; j < inner.size(); j++) {
			// 获取每一个网格对象
			Grid *grid = inner.at(j);
			// 获取每一个网格对象对应的的坐标
			Vec2 tileCoord = Vec2(grid->getX(), grid->getY());
			// 使用TMXLayer类的tileGIDAt函数获取TileMap坐标系里的“全局唯一标识”GID
			int tileGid = _collidable->getTileGIDAt(tileCoord);
			if (tileGid) {
				// 使用GID来查找指定tile的属性,返回一个Value
				Value properties = _tileMap->getPropertiesForGID(tileGid);
				// 返回的Value实际是一个ValueMap
				ValueMap map = properties.asValueMap();
				// 查找ValueMap,判断是否有”可碰撞的“物体,如果有,设置网格对象的isPass变量为false
				std::string value = map.at("collidable").asString();
				if (value.compare("true") == 0) {
					grid->setPass(false);
				}
			}
		}
	}

	// 人物出场特效
	auto effects_player_out = Sprite::create("effects/effects_player_out/effects_player_out_11.png");
	effects_player_out->setPosition(Vec2(visibleSize.width*0.3,visibleSize.height*0.3));
	this->addChild(effects_player_out, 1);
	auto player_out_animate = getAnimateByName("effects/effects_player_out/effects_player_out_", 0.1f, 11);
	auto delay1 = DelayTime::create(1.5f);
	auto fadeOut = FadeOut::create(0.2f);
	auto sequence = Sequence::create(delay1, player_out_animate, fadeOut, nullptr);
	effects_player_out->runAction(sequence);

	_player = SpriteBase::create("player/player_sword/player_sword_stand.png");
	this->addChild(_player, 1);
	_player->setPosition(Vec2(visibleSize.width*0.3, visibleSize.height*0.3));
	this->addChild(_tileMap,0);
	_player->setFlippedX(true);
	XmlTools::readPlayerData(_player);

	/// 传送门
	ArmatureDataManager::getInstance()->addArmatureFileInfo("/buildings/gate/AnimationStart0.png", "/buildings/gate/AnimationStart0.plist", "/buildings/gate/AnimationStart.ExportJson");
	Armature *armature = Armature::create("AnimationStart");
	armature->getAnimation()->play("Start");
	this->addChild(armature);
	armature->setScale(0.3);
	armature->setPosition(Vec2(visibleSize.width*0.9, visibleSize.height*0.7));
	auto gate_effect = ParticleSystemQuad::create("effects/gate_effect.plist");
	this->addChild(gate_effect);
	gate_effect->setScale(0.3);
	gate_effect->setPosition(Vec2(visibleSize.width*0.9, visibleSize.height*0.75));
	gate_effect->setPositionType(kCCPositionTypeRelative);

	// 结束战斗按钮
	auto end_fight_button = Button::create("ui/end_fight.png");
	end_fight_button->setPosition(Vec2(visibleSize.width*0.95, visibleSize.height*0.97));
	end_fight_button->setScale(0.5f);
	this->addChild(end_fight_button, 0);
	//结束战斗对话框
	auto end_fight_dialog_bg = Sprite::create("ui/end_fight_dialog_bg.png");
	end_fight_dialog_bg->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
	end_fight_dialog_bg->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2));
	this->addChild(end_fight_dialog_bg, 3);

	// 确定结束战斗按钮
	auto end_fight_sub_button = Button::create("ui/end_fight_sub_button.png");
	end_fight_dialog_bg->addChild(end_fight_sub_button);
	end_fight_sub_button->setAnchorPoint(Vec2::ZERO);
	end_fight_sub_button->setPosition(Vec2(20, 30));
//.........这里部分代码省略.........
开发者ID:Coulometer,项目名称:cocos2d_Graduation_Project,代码行数:101,代码来源:FiledScene.cpp


示例14: TEST

TEST(ValueTest, ValueMap)
{
  boost::shared_ptr<Scalar> s(new Scalar(NTA_BasicType_Int32));
  s->value.int32 = 10;
  boost::shared_ptr<Array> a(new Array(NTA_BasicType_Real32));
  boost::shared_ptr<std::string> str(new std::string("hello world"));
  
  ValueMap vm;
  vm.add("scalar", s);
  vm.add("array", a);
  vm.add("string", str);
  ASSERT_ANY_THROW(vm.add("scalar", s));

  ASSERT_TRUE(vm.contains("scalar"));
  ASSERT_TRUE(vm.contains("array"));
  ASSERT_TRUE(vm.contains("string"));
  ASSERT_TRUE(!vm.contains("foo"));
  ASSERT_TRUE(!vm.contains("scalar2"));
  ASSERT_TRUE(!vm.contains("xscalar"));
  
  boost::shared_ptr<Scalar> s1 = vm.getScalar("scalar");
  ASSERT_TRUE(s1 == s);
  
  boost::shared_ptr<Array> a1 = vm.getArray("array");
  ASSERT_TRUE(a1 == a);
  
  boost::shared_ptr<Scalar> def(new Scalar(NTA_BasicType_Int32));
  Int32 x = vm.getScalarT("scalar", (Int32)20);
  ASSERT_EQ((Int32)10, x);
  
  x = vm.getScalarT("scalar2", (Int32)20);
  ASSERT_EQ((Int32)20, x);

  Value v = vm.getValue("array");
  ASSERT_EQ(Value::arrayCategory, v.getCategory());
  ASSERT_TRUE(v.getArray() == a);
}
开发者ID:Containerhouse,项目名称:nupic.core,代码行数:37,代码来源:ValueTest.cpp


示例15: createGraphicalRepresentation

该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ ValueObject类代码示例发布时间:2022-05-31
下一篇:
C++ ValueLocation类代码示例发布时间:2022-05-31
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap