Example #1
0
void HelloWorld::addNewMember() {
	auto new_pos = line.back()->getPosition();
	new_pos.x -= line.back()->getSpriteFrame()->getOriginalSizeInPixels().width;
	auto new_dir = line.back()->getDirection();
	auto new_anim = RepeatForever::create(Animate::create(Animation::createWithSpriteFrames(prinny_frames_left, 1.0f / 4)));
	auto new_frame = prinny_frames_left.front();
	switch (new_dir) {
	case 0:
		break;
	case 1: new_anim = RepeatForever::create(Animate::create(Animation::createWithSpriteFrames(prinny_frames_right, 1.0f / 4)));
		new_frame = prinny_frames_right.front();
		break;
	case 2: new_anim = RepeatForever::create(Animate::create(Animation::createWithSpriteFrames(prinny_frames_up, 1.0f / 4)));
		new_frame = prinny_frames_up.front();
		break;
	case 3: new_anim = RepeatForever::create(Animate::create(Animation::createWithSpriteFrames(prinny_frames_down, 1.0f / 4)));
		new_frame = prinny_frames_up.front();
		break;
	}
	Member* new_sprite = Member::create(new_frame, new_dir, new_anim);
	line.pushBack(new_sprite);
	background->addChild(new_sprite);
	new_sprite->setPosition(new_pos);

}
Example #2
0
void ALDevice::reset(const Vector<AttributePair> &attributes)
{
    if(!hasExtension(SOFT_HRTF))
        throw std::runtime_error("ALC_SOFT_HRTF not supported");
    auto do_reset = [this, &attributes]() -> ALCboolean
    {
        if(attributes.empty())
        {
            /* No explicit attributes. */
            return alcResetDeviceSOFT(mDevice, nullptr);
        }
        auto attr_end = std::find_if(attributes.begin(), attributes.end(),
            [](const AttributePair &attr) -> bool
            { return std::get<0>(attr) == 0; }
        );
        if(attr_end == attributes.end())
        {
            /* Attribute list was not properly terminated. Copy the attribute
             * list and add the 0 sentinel.
             */
            Vector<AttributePair> attrs = attributes;
            attrs.push_back({0, 0});
            return alcResetDeviceSOFT(mDevice, &std::get<0>(attrs.front()));
        }
        return alcResetDeviceSOFT(mDevice, &std::get<0>(attributes.front()));
    };
    if(!do_reset())
        throw std::runtime_error("Device reset error");
}
Example #3
0
void HelloWorld::start() {
	Vec2 origin = Director::getInstance()->getVisibleOrigin();
	Vec2 visibleSize = Director::getInstance()->getVisibleSize();
	for (int i = line.size() - 1; i >= 1; i--) {
		background->removeChild(line.at(i),true);
		line.eraseObject(line.at(i));
	}
	background->removeChild(powerUp, true);
	hasPowerUp = false;
	foodCount = 0;
	totalFoodCount = 0;
	timer = 10;
	line.front()->setPosition(origin.x + visibleSize.x / 2, origin.y + visibleSize.y / 2);
	line.front()->setDirection(1, prinnyx_move_right);
	float sizeX = prinny_frames_idle.front()->getOriginalSizeInPixels().width;
	float sizeY = prinny_frames_idle.front()->getOriginalSizeInPixels().height;
	float bgSizeX = background->getContentSize().width;
	float bgSizeY = background->getContentSize().height;
	food->setPosition(generateRandomPosition(sizeX, bgSizeX - sizeX, sizeY, bgSizeY - sizeY));
	score = 0;
	score_value_label->setString(std::to_string(score));
	level = 1;
	level_value_label->setString(std::to_string(level));
	cocos2d::Director::getInstance()->setAnimationInterval(1.0 / 10);
	cocos2d::Director::getInstance()->resume();
}
Example #4
0
bool HelloWorld::CollisionWithDeath() {
	auto headRect = line.front()->getBoundingBox();
	auto headPos = line.front()->getPosition();
	if (headPos.x < 0 || headPos.y < 0 || headPos.x > background->getBoundingBox().getMaxX() || headPos.y > background->getBoundingBox().getMaxY()) {
		return true;
	}
	for (int i = 1; i < line.size() - 1; i++) {
		auto currRect = line.at(i)->getBoundingBox();
		if (headRect.intersectsRect(currRect)) {
			return true;
		}
	}
	return false;
}
Example #5
0
bool HelloWorld::CollisionWithFood() {
	auto foodRect = food->getBoundingBox();
	auto headRect = line.front()->getBoundingBox();

	return foodRect.intersectsRect(headRect);

}
Example #6
0
Context *ALDevice::createContext(const Vector<AttributePair> &attributes)
{
    ALCcontext *ctx = [this, &attributes]() -> ALCcontext*
    {
        if(attributes.empty())
        {
            /* No explicit attributes. */
            return alcCreateContext(mDevice, nullptr);
        }
        auto attr_end = std::find_if(attributes.begin(), attributes.end(),
            [](const AttributePair &attr) -> bool
            { return std::get<0>(attr) == 0; }
        );
        if(attr_end == attributes.end())
        {
            /* Attribute list was not properly terminated. Copy the attribute
             * list and add the 0 sentinel.
             */
            Vector<AttributePair> attrs = attributes;
            attrs.push_back({0, 0});
            return alcCreateContext(mDevice, &std::get<0>(attrs.front()));
        }
        return alcCreateContext(mDevice, &std::get<0>(attributes.front()));
    }();
    if(!ctx) throw std::runtime_error("Failed to create context");

    mContexts.emplace_back(MakeUnique<ALContext>(ctx, this));
    return mContexts.back().get();
}
Example #7
0
bool HelloWorld::CollisionWithPowerUp() {
	if (hasPowerUp) {
		auto powerUpRect = powerUp->getBoundingBox();
		auto headRect = line.front()->getBoundingBox();

		return powerUpRect.intersectsRect(headRect);
	}
	return false;
}
Example #8
0
TEST(small_vector, Basic) {
  typedef folly::small_vector<int,3,uint32_t
  > Vector;

  Vector a;

  a.push_back(12);
  EXPECT_EQ(a.front(), 12);
  EXPECT_EQ(a.size(), 1);
  a.push_back(13);
  EXPECT_EQ(a.size(), 2);
  EXPECT_EQ(a.front(), 12);
  EXPECT_EQ(a.back(), 13);

  a.emplace(a.end(), 32);
  EXPECT_EQ(a.back(), 32);

  a.emplace(a.begin(), 12);
  EXPECT_EQ(a.front(), 12);
  EXPECT_EQ(a.back(), 32);
  a.erase(a.end() - 1);
  EXPECT_EQ(a.back(), 13);

  a.push_back(12);
  EXPECT_EQ(a.back(), 12);
  a.pop_back();
  EXPECT_EQ(a.back(), 13);

  const int s = 12;
  a.push_back(s); // lvalue reference

  Vector b, c;
  b = a;
  EXPECT_TRUE(b == a);
  c = std::move(b);
  EXPECT_TRUE(c == a);
  EXPECT_TRUE(c != b && b != a);

  EXPECT_GT(c.size(), 0);
  c.resize(1);
  EXPECT_EQ(c.size(), 1);

  Vector intCtor(12);
}
    bool PBC::check(const Vector &b)const{
      uint b_sz = b.size();
      if(b_sz<2) return false;
      uint M = b_sz-2;

      double b0 = b.front();
      double bM = b[M]; // next to last element

      return bM == (M+1)*b0;  // factor of 'a' cancels
    }
Example #10
0
void printonscreen (Vector<int> & x)
{
    std::cout << "O tamanho do vetor: " << x.size() << std::endl;
    if(x.size() > 0)
    {
        std::cout << "O primeiro elemento:" << x.front() << std::endl;
        std::cout << "O ultimo elemento:" << x.back() << std::endl;
        
    }    
    if(x.size() > 3)
        std::cout << "O terceiro elemento:" << x[2] <<  std::endl;
    std::cout << "\n";
}
void CustomColorsProxy::UpdateSpriteFromConfig()
{
	if(NULL == customColorsSprite)
	{
		return;
	}
		
	RenderManager::Instance()->SetRenderTarget(customColorsSprite);
	Vector<Color> customColors = EditorConfig::Instance()->GetColorPropertyValues("LandscapeCustomColors");
	if (customColors.size())
	{
		Color color = customColors.front();
		RenderManager::Instance()->ClearWithColor(color.r, color.g, color.b, color.a);
	}
	RenderManager::Instance()->RestoreRenderTarget();
}
bool CustomColorsSystem::LoadTexture( const DAVA::FilePath &filePath, bool createUndo /* = true */ )
{
	if(filePath.IsEmpty())
		return false;

    Vector<Image*> images;
    ImageSystem::Instance()->Load(filePath, images);
	if(images.empty())
		return false;

	Image* image = images.front();
	if(image)
	{
		Texture* texture = Texture::CreateFromData(image->GetPixelFormat(),
												   image->GetData(),
												   image->GetWidth(),
												   image->GetHeight(),
												   false);
		Sprite* sprite = Sprite::CreateFromTexture(texture, 0, 0, texture->GetWidth(), texture->GetHeight());

		if (createUndo)
		{
			StoreOriginalState();
		}
		RenderManager::Instance()->SetRenderTarget(drawSystem->GetCustomColorsProxy()->GetSprite());
        
        Sprite::DrawState drawState;
		sprite->Draw(&drawState);
        
		RenderManager::Instance()->RestoreRenderTarget();
		AddRectToAccumulator(Rect(Vector2(0.f, 0.f), Vector2(texture->GetWidth(), texture->GetHeight())));

		SafeRelease(sprite);
		SafeRelease(texture);
		for_each(images.begin(), images.end(), SafeRelease<Image>);

		if (createUndo)
		{
			((SceneEditor2*)GetScene())->BeginBatch("Load custom colors texture");
			StoreSaveFileName(filePath);
			CreateUndoPoint();
			((SceneEditor2*)GetScene())->EndBatch();
		}
	}

    return true;
}
Example #13
0
void NetworkPNL::SetDefinition(int node, const std::vector<double> & definition)
{
    MarkCallFunction("SetDefinition unfin x", true);
    WDistribFun *pD = Distributions().Distribution(node);
    pnl::CDenseMatrix<float> *m = static_cast<pnl::CDenseMatrix<float> *>(pD->Matrix(pnl::matTable));
    Vector<float> def;
    int i = definition.size();

    if(m->GetRawDataLength() != i)
    {
	MarkCallFunction("SetDefinition bad call", true);
	return;
    }
    def.resize(i);
    for(; --i >= 0; def[i] = definition[i]);

    m->SetData(&def.front());
    m_aNodeValueStatus[node] = NetConst::NotUpdated;
}
void LandscapeEditorCustomColors::LoadTextureAction(const FilePath &pathToFile)
{
	if(pathToFile.IsEmpty())
		return;

	Vector<Image*> images = ImageLoader::CreateFromFile(pathToFile);
	if(images.empty())
		return;

	Image* image = images.front();
	if(image)
	{
		Texture* texture = Texture::CreateFromData(image->GetPixelFormat(),
												   image->GetData(),
												   image->GetWidth(),
												   image->GetHeight(),
												   false);

		SafeRelease(colorSprite);
		colorSprite = Sprite::CreateAsRenderTarget(texSurf->GetWidth(), texSurf->GetHeight(), FORMAT_RGBA8888);
		Sprite* sprite = Sprite::CreateFromTexture(texture, 0, 0, texture->GetWidth(), texture->GetHeight());

		StoreOriginalState();

		RenderManager::Instance()->SetRenderTarget(colorSprite);
		sprite->Draw();
		RenderManager::Instance()->RestoreRenderTarget();
		PerformLandscapeDraw();

		SafeRelease(sprite);
		SafeRelease(texture);
		for_each(images.begin(), images.end(), SafeRelease<Image>);

		StoreSaveFileName(pathToFile);

		CreateUndoPoint();
	}
}
Example #15
0
File: parse_op.cpp Project: 8l/zl
 const Syntax * parse(const Syntax * p, const char * l_i) {
   //printf("ParseExpImpl::parse: %s %s\n", ~p->sample_w_loc(), ~p->to_string());
   opr_s.clear();
   val_s.clear();
   list_is = l_i;
   Op::Types prev = 0;
   try {
     for (parts_iterator i = p->args_begin(), e = p->args_end(); i != e; ++i) {
       const Syntax * pop = *i; // parsed op
       Op::Types cur = ops.lookup_types(pop);
       if (cur & Op::Special) {
         const Syntax * res = ops.try_special(pop, i, e);
         if (res) {
           pop = res;
           cur = ops.lookup_types(pop);
         } else {
           cur &= ~Op::Special;
         }
       } 
       assert(!(cur & Op::Special));
       if (prev == 0 || prev & (Op::Prefix | Op::Bin)) {
         cur &= (Op::Prefix | Op::Other);
         if (cur == 0) 
           throw error(pop, "Expected an operand or a prefix operator.");
       } else {
         cur &= (Op::Bin | Op::Postfix);
         if (cur == 0) 
           throw error(pop, "Expected a binary or postfix operator.");
       }
       //if (cur == (Op::Prefix | Op::Other)) {
       //  if (i + 1 == sz || (ops.lookup_types(p->arg(i+1)) & (Op::Postfix | Op::Bin))) {
       //    cur &= (Op::Postfix | Op::Other);
       //    if (cur == 0)
       //      throw error(pop, "Expected an operand or a postfix operator.");
       //  } else {
       //    cur &= (Op::Bin | Op::Prefix);
       //    if (cur == 0)
       //      throw error(pop, "Expected an binary or prefix operator.");
       //  }
       //}
       const Op * op = ops.lookup(pop, cur);
       
       if (op->type == Op::Other) {
         val_s.push_back(pop);
       } else {
         while (!opr_s.empty() && 
                (opr_s.back().op->level < op->level || 
                 (opr_s.back().op->level == op->level && op->assoc == Left)))
           reduce();
         if (!opr_s.empty() && opr_s.back().op->level == op->level && op->assoc == None)
           throw error(pop, "\"%s\" is non-associative.", 
                       op->what.c_str());
         opr_s.push_back(OpInfo(op, pop)); 
       }
       prev = cur;
     }
     while (!opr_s.empty())
       reduce();
     if (val_s.size() == 0)
       throw error(p, "Empty expression.");
     if (val_s.size() > 1)
       throw error(val_s[val_s.size()-2], "Extra operand(s).");
     assert(val_s.size() == 1);
     Syntax * res = val_s.front();
     if (!res->is_a("syntax") && !res->is_a("raw_syntax"))
       res->str_ = p->str();
     return res;
   } catch (Error * err) {
     //printf("?? %s %s\n", ~p->sample_w_loc(), ~p->to_string());
     //abort();
     err->msg.span.source = p->str().source;
     err->add_note(extra_parse_info(p->str(), "<op exp>"));
     throw err;
   }
 }
Example #16
0
bool
NetCallback::CommonAttachFactors(pnl::CGraphicalModel &pnlModel,
	const ProbabilisticNet &net)
{
    static const char fname[] = "CommonAttachFactors";
 
    int i, iPNL, iWNode;
    Vector<String> aNodeName(net.Graph().Names());

    // attach parameters for every nodes
    for(i = 0; i < aNodeName.size(); i++)
    {
	// it is index for wrapper node, pnl node index is 'iPNL'
	iWNode = net.Graph().INode(aNodeName[i]);
	iPNL = net.Graph().IGraph(iWNode);

	WDistribFun *pWDF = net.Distributions().Distribution(iWNode);
        PNL_CHECK_IS_NULL_POINTER(pWDF);

        pnlModel.AllocFactor(iPNL);

	pnl::CFactor *pPNLF = pnlModel.GetFactor(iPNL);
        PNL_CHECK_IS_NULL_POINTER(pPNLF);

        pnl::CDistribFun *pPNLdf = pPNLF->GetDistribFun();
        PNL_CHECK_IS_NULL_POINTER(pPNLdf);

        if (net.pnlNodeType(iWNode).IsDiscrete())
        {
            bool isSoftMax = false;
            DistribFunDesc  *des = pWDF->desc();
            for (int j=0; j<des->nNode(); j++ )
            {
                TokIdNode *tokId = des->node(j);
                if (!static_cast<pnl::CNodeType*>(tokId->v_prev->data)->IsDiscrete() )
                {
                    isSoftMax = true;
                    break;
                }
            }
            bool isCondSoftMax = false;
            
            if (isSoftMax)
            {
                for (int j=0; j<des->nNode()-1; j++ )
                {
                    TokIdNode * tokId = des->node(j);
                    if (static_cast<pnl::CNodeType*>(tokId->v_prev->data)->IsDiscrete() )
                    {
                        isCondSoftMax = true;
                        break;
                    }
                }
            }
            if (isCondSoftMax)
            {
                pPNLdf->CreateDefaultMatrices();
                pnl::CCondSoftMaxDistribFun *pCondSoftMaxDFHigh = 
                    dynamic_cast<WCondSoftMaxDistribFun*>(pWDF)->GetDistribution();
                PNL_CHECK_IS_NULL_POINTER(pCondSoftMaxDFHigh);
                
                pnl::CCondSoftMaxDistribFun *pCondSoftMaxDFPNL = 
                    dynamic_cast<pnl::CCondSoftMaxDistribFun*>(pPNLdf);
                PNL_CHECK_IS_NULL_POINTER(pCondSoftMaxDFPNL);
                
                pnl::CMatrixIterator<pnl::CSoftMaxDistribFun*>* iterHigh =
                    pCondSoftMaxDFHigh->GetMatrixWithDistribution()->InitIterator();
                
                pnl::CMatrixIterator<pnl::CSoftMaxDistribFun*>* iterPNL =
                    pCondSoftMaxDFPNL->GetMatrixWithDistribution()->InitIterator();

                for (iterHigh, iterPNL; 
                    (pCondSoftMaxDFHigh->GetMatrixWithDistribution()->IsValueHere(iterHigh))&&
                    (pCondSoftMaxDFPNL->GetMatrixWithDistribution()->IsValueHere(iterPNL));
                    pCondSoftMaxDFHigh->GetMatrixWithDistribution()->Next(iterHigh),
                    pCondSoftMaxDFPNL->GetMatrixWithDistribution()->Next(iterPNL) )
                {
                    pnl::CSoftMaxDistribFun* DataHigh =
                        *(pCondSoftMaxDFHigh->GetMatrixWithDistribution()->Value(iterHigh));
                    PNL_CHECK_IS_NULL_POINTER(DataHigh);

                    pnl::CMatrix<float> *matr = DataHigh->GetMatrix(pnl::matWeights);
                    pnl::floatVector *ofVect = DataHigh->GetOffsetVector();
                    
                    pnl::CSoftMaxDistribFun* DataPNL =
                        *(pCondSoftMaxDFPNL->GetMatrixWithDistribution()->Value(iterPNL));
                    PNL_CHECK_IS_NULL_POINTER(DataPNL);

                    DataPNL->AttachOffsetVector(ofVect);
                    DataPNL->AttachMatrix(matr, pnl::matWeights);
                }
            }
            else
                if (isSoftMax)
                {
                    pnl::CDenseMatrix<float> *weight = pWDF->Matrix(pnl::matWeights, 0);
                    PNL_CHECK_IS_NULL_POINTER(weight);
                    pPNLF->AttachMatrix(weight, pnl::matWeights);
                    // offsetVector 
                    pnl::floatVector *offVector = dynamic_cast<WSoftMaxDistribFun*>(pWDF)->
                        OffsetVector();
                    pnl::CDistribFun *df = pPNLF->GetDistribFun();
                    
                    dynamic_cast<pnl::CSoftMaxDistribFun*>(df)->AttachOffsetVector(offVector);
                }
                else
                {
                    pnl::CDenseMatrix<float> *mat = pWDF->Matrix(pnl::matTable);
                    PNL_CHECK_IS_NULL_POINTER(mat);
                    
                    pPNLF->AttachMatrix(mat, pnl::matTable);
                    pPNLF->AttachMatrix(mat->Copy(mat), pnl::matDirichlet);
                }
        }
        else
        {
	    WGaussianDistribFun* pGWDF = dynamic_cast<WGaussianDistribFun* >(pWDF);
	    WCondGaussianDistribFun* pCGWDF = dynamic_cast<WCondGaussianDistribFun* >(pWDF);

            //Gaussian or cond. gaussian case
	    if (pGWDF || pCGWDF)
	    {
                Vector<int> indexes;
                pnl::CMatrix<pnl::CGaussianDistribFun* > * pCondMatrix = 0;

                if (pCGWDF)
                {
                    //Gaussian matrixes for all combinations of discrete parents
                    pCondMatrix = pCGWDF->GetPNLDistribFun()->GetMatrixWithDistribution();
                }
                else
                {
                    const int range = 1;
                    pnl::CGaussianDistribFun* pGDF = dynamic_cast<pnl::CGaussianDistribFun*>(pPNLF->GetDistribFun());
                    //For gaussian case there is only 1 distrib function
                    pCondMatrix = pnl::CDenseMatrix<pnl::CGaussianDistribFun* >::Create(1, &range, &pGDF);
                };

                pnl::CMatrixIterator<pnl::CGaussianDistribFun* > * iterThis = pCondMatrix->InitIterator();
                //Excess all distrib functions to attach them to pPNLF
                for( iterThis; pCondMatrix->IsValueHere( iterThis );
                    pCondMatrix->Next(iterThis))
                {                 
                    //Discrete parent combination for cond. gaussian case
                    pCondMatrix->Index( iterThis, &indexes );

                    bool isDistributionSpecific = (pGWDF)?
                        (pGWDF->IsDistributionSpecific() == 1):(pCGWDF->IsDistributionSpecific() == 1);

                    if (isDistributionSpecific)
		    {
                        if (pGWDF)
                        {
		            const pnl::pConstNodeTypeVector* ntVec = pPNLF->GetDistribFun()
			        ->GetNodeTypesVector();
		            int NumberOfNodes = pPNLF->GetDistribFun()->GetNumberOfNodes();

		            pnl::CGaussianDistribFun *gaudf = pnl::CGaussianDistribFun
			        ::CreateUnitFunctionDistribution(NumberOfNodes, &ntVec->front());
		            pPNLF->SetDistribFun(gaudf);
                
		            delete gaudf;
                        }
                        else
                        {
                            ThrowUsingError("At the moment of writing this function WCondGaussianDistribFun class could not be specific. Please contact developers.", fname);
                        };
		    }
		    else
		    {
                        const int *pDiscrParentValues = 0;

                        if (pCGWDF)
                        {
                            pDiscrParentValues = &(indexes.front());
                        };

		        pnl::CDenseMatrix<float> *mean = pWDF->Matrix(pnl::matMean, -1, pDiscrParentValues);
		        PNL_CHECK_IS_NULL_POINTER(mean);
		        pnl::CDenseMatrix<float> *cov = pWDF->Matrix(pnl::matCovariance, -1, pDiscrParentValues);
		        PNL_CHECK_IS_NULL_POINTER(cov);

		        pPNLF->AttachMatrix(mean, pnl::matMean, -1, pDiscrParentValues);
		        pPNLF->AttachMatrix(mean->Copy(mean), pnl::matWishartMean, -1, pDiscrParentValues);

		        pPNLF->AttachMatrix(cov, pnl::matCovariance, -1, pDiscrParentValues);
		        pPNLF->AttachMatrix(cov->Copy(cov), pnl::matWishartCov, -1, pDiscrParentValues);

		        int NDims;
		        const int *Ranges;
		        cov->GetRanges(&NDims, &Ranges);

                        pnl::CGaussianDistribFun* a = dynamic_cast<pnl::CGaussianDistribFun*>(pPNLF->GetDistribFun());

		        if (pGWDF)
                        {
                            dynamic_cast<pnl::CGaussianDistribFun*>(pPNLF->GetDistribFun())
			        ->SetFreedomDegrees(1 , Ranges[0] + 2); 
                        }
                        else
                        {
                            const_cast<pnl::CGaussianDistribFun *>(dynamic_cast<pnl::CCondGaussianDistribFun*>(pPNLF->GetDistribFun())->GetDistribution(pDiscrParentValues))->
			        SetFreedomDegrees(1 , Ranges[0] + 2); 
                        };
                
                        int ContParent = 0;
		        int NumOfNds = pPNLF->GetDistribFun()->GetNumberOfNodes();
                        const pnl::pConstNodeTypeVector *pNodeTypes = pPNLF->GetDistribFun()->GetNodeTypesVector();
                        for (int parent = 0; parent < (NumOfNds-1); parent++)
		        {
                            if (!((*pNodeTypes)[parent]->IsDiscrete()))
                            {
			        pnl::CDenseMatrix<float> *weight = pWDF->Matrix(pnl::matWeights, ContParent, pDiscrParentValues);
			        PNL_CHECK_IS_NULL_POINTER(weight);

			        pPNLF->AttachMatrix(weight, pnl::matWeights, ContParent, pDiscrParentValues);
                                ContParent++;
                            };
		        }
		    };
                };
	    }
	    else 
	    {
                PNL_CHECK_IS_NULL_POINTER(pGWDF);
	    };
        }
    }

    return true;
}
Example #17
0
void TemplateVectorTest::onEnter()
{
    UnitTestDemo::onEnter();

    Vector<Node*> vec;
    CCASSERT(vec.empty(), "");
    CCASSERT(vec.capacity() == 0, "");
    CCASSERT(vec.size() == 0, "");
    CCASSERT(vec.max_size() > 0, "");

    auto node1 = Node::create();
    node1->setTag(1);
    vec.pushBack(node1);
    CCASSERT(node1->getReferenceCount() == 2, "");

    auto node2 = Node::create();
    node2->setTag(2);
    vec.pushBack(node2);
    CCASSERT(vec.getIndex(node1) == 0, "");
    CCASSERT(vec.getIndex(node2) == 1, "");

    auto node3 = Node::create();
    node3->setTag(3);
    vec.insert(1, node3);
    CCASSERT(vec.at(0)->getTag() == 1, "");
    CCASSERT(vec.at(1)->getTag() == 3, "");
    CCASSERT(vec.at(2)->getTag() == 2, "");

    // Test copy constructor
    Vector<Node*> vec2(vec);
    CCASSERT(vec2.size() == vec.size(), "");
    ssize_t size = vec.size();
    for (ssize_t i = 0; i < size; ++i)
    {
        CCASSERT(vec2.at(i) == vec.at(i), "");
        CCASSERT(vec.at(i)->getReferenceCount() == 3, "");
        CCASSERT(vec2.at(i)->getReferenceCount() == 3, "");
    }

    // Test copy assignment operator
    Vector<Node*> vec3;
    vec3 = vec2;
    CCASSERT(vec3.size() == vec2.size(), "");
    size = vec3.size();
    for (ssize_t i = 0; i < size; ++i)
    {
        CCASSERT(vec3.at(i) == vec2.at(i), "");
        CCASSERT(vec3.at(i)->getReferenceCount() == 4, "");
        CCASSERT(vec2.at(i)->getReferenceCount() == 4, "");
        CCASSERT(vec.at(i)->getReferenceCount() == 4, "");
    }

    // Test move constructor

    auto createVector = [this]() {
        Vector<Node*> ret;

        for (int i = 0; i < 20; i++)
        {
            ret.pushBack(Node::create());
        }

        int j = 1000;
        for (auto& child : ret)
        {
            child->setTag(j++);
        }

        return ret;
    };

    Vector<Node*> vec4(createVector());
    for (const auto& child : vec4)
    {
        CC_UNUSED_PARAM(child);
        CCASSERT(child->getReferenceCount() == 2, "");
    }

    // Test init Vector<T> with capacity
    Vector<Node*> vec5(10);
    CCASSERT(vec5.capacity() == 10, "");
    vec5.reserve(20);
    CCASSERT(vec5.capacity() == 20, "");

    CCASSERT(vec5.size() == 0, "");
    CCASSERT(vec5.empty(), "");

    auto toRemovedNode = Node::create();
    vec5.pushBack(toRemovedNode);
    CCASSERT(toRemovedNode->getReferenceCount() == 2, "");

    // Test move assignment operator
    vec5 = createVector();
    CCASSERT(toRemovedNode->getReferenceCount() == 1, "");
    CCASSERT(vec5.size() == 20, "size should be 20");

    for (const auto& child : vec5)
    {
        CC_UNUSED_PARAM(child);
        CCASSERT(child->getReferenceCount() == 2, "");
    }

    // Test Vector<T>::find
    CCASSERT(vec.find(node3) == (vec.begin() + 1), "");
    CCASSERT(std::find(std::begin(vec), std::end(vec), node2) == (vec.begin() + 2), "");

    CCASSERT(vec.front()->getTag() == 1, "");
    CCASSERT(vec.back()->getTag() == 2, "");

    CCASSERT(vec.getRandomObject(), "");
    CCASSERT(!vec.contains(Node::create()), "");
    CCASSERT(vec.contains(node1), "");
    CCASSERT(vec.contains(node2), "");
    CCASSERT(vec.contains(node3), "");
    CCASSERT(vec.equals(vec2), "");
    CCASSERT(vec.equals(vec3), "");

    // Insert
    vec5.insert(2, node1);
    CCASSERT(vec5.at(2)->getTag() == 1, "");
    CCASSERT(vec5.size() == 21, "");
    vec5.back()->setTag(100);
    vec5.popBack();
    CCASSERT(vec5.size() == 20, "");
    CCASSERT(vec5.back()->getTag() != 100, "");

    // Erase and clear
    Vector<Node*> vec6 = createVector();
    Vector<Node*> vec7 = vec6;  // Copy for check

    CCASSERT(vec6.size() == 20, "");
    vec6.erase(vec6.begin() + 1);  //
    CCASSERT(vec6.size() == 19, "");
    CCASSERT((*(vec6.begin() + 1))->getTag() == 1002, "");
    vec6.erase(vec6.begin() + 2, vec6.begin() + 10);
    CCASSERT(vec6.size() == 11, "");
    CCASSERT(vec6.at(0)->getTag() == 1000, "");
    CCASSERT(vec6.at(1)->getTag() == 1002, "");
    CCASSERT(vec6.at(2)->getTag() == 1011, "");
    CCASSERT(vec6.at(3)->getTag() == 1012, "");
    vec6.erase(3);
    CCASSERT(vec6.at(3)->getTag() == 1013, "");
    vec6.eraseObject(vec6.at(2));
    CCASSERT(vec6.at(2)->getTag() == 1013, "");
    vec6.clear();

    auto objA = Node::create(); // retain count is 1
    auto objB = Node::create();
    auto objC = Node::create();
    {
        Vector<Node*> array1;
        Vector<Node*> array2;

        // push back objA 3 times
        array1.pushBack(objA); // retain count is 2
        array1.pushBack(objA); // retain count is 3
        array1.pushBack(objA); // retain count is 4

        array2.pushBack(objA); // retain count is 5
        array2.pushBack(objB);
        array2.pushBack(objC);

        for (auto obj : array1) {
            array2.eraseObject(obj);
        }
        CCASSERT(objA->getReferenceCount() == 4, "");
    }
    CCASSERT(objA->getReferenceCount() == 1, "");

    {
        Vector<Node*> array1;
        // push back objA 3 times
        array1.pushBack(objA); // retain count is 2
        array1.pushBack(objA); // retain count is 3
        array1.pushBack(objA); // retain count is 4
        CCASSERT(objA->getReferenceCount() == 4, "");
        array1.eraseObject(objA, true); // Remove all occurrences in the Vector.
        CCASSERT(objA->getReferenceCount() == 1, "");

        array1.pushBack(objA); // retain count is 2
        array1.pushBack(objA); // retain count is 3
        array1.pushBack(objA); // retain count is 4

        array1.eraseObject(objA, false);
        CCASSERT(objA->getReferenceCount() == 3, ""); // Only remove the first occurrence in the Vector.
    }

    // Check the retain count in vec7
    CCASSERT(vec7.size() == 20, "");
    for (const auto& child : vec7)
    {
        CC_UNUSED_PARAM(child);
        CCASSERT(child->getReferenceCount() == 2, "");
    }

    // Sort
    Vector<Node*> vecForSort = createVector();
    std::sort(vecForSort.begin(), vecForSort.end(), [](Node* a, Node* b) {
        return a->getTag() >= b->getTag();
    });

    for (int i = 0; i < 20; ++i)
    {
        CCASSERT(vecForSort.at(i)->getTag() - 1000 == (19 - i), "");
    }

    // Reverse
    vecForSort.reverse();
    for (int i = 0; i < 20; ++i)
    {
        CCASSERT(vecForSort.at(i)->getTag() - 1000 == i, "");
    }

    // Swap
    Vector<Node*> vecForSwap = createVector();
    vecForSwap.swap(2, 4);
    CCASSERT(vecForSwap.at(2)->getTag() == 1004, "");
    CCASSERT(vecForSwap.at(4)->getTag() == 1002, "");
    vecForSwap.swap(vecForSwap.at(2), vecForSwap.at(4));
    CCASSERT(vecForSwap.at(2)->getTag() == 1002, "");
    CCASSERT(vecForSwap.at(4)->getTag() == 1004, "");

    // shrinkToFit
    Vector<Node*> vecForShrink = createVector();
    vecForShrink.reserve(100);
    CCASSERT(vecForShrink.capacity() == 100, "");
    vecForShrink.pushBack(Node::create());
    vecForShrink.shrinkToFit();
    CCASSERT(vecForShrink.capacity() == 21, "");

    // get random object
    // Set the seed by time
    srand((unsigned)time(nullptr));
    Vector<Node*> vecForRandom = createVector();
    log("<--- begin ---->");
    for (int i = 0; i < vecForRandom.size(); ++i)
    {
        log("Vector: random object tag = %d", vecForRandom.getRandomObject()->getTag());
    }
    log("<---- end  ---->");

    // Self assignment
    Vector<Node*> vecSelfAssign = createVector();
    vecSelfAssign = vecSelfAssign;
    CCASSERT(vecSelfAssign.size() == 20, "");

    for (const auto& child : vecSelfAssign)
    {
        CC_UNUSED_PARAM(child);
        CCASSERT(child->getReferenceCount() == 2, "");
    }

    vecSelfAssign = std::move(vecSelfAssign);
    CCASSERT(vecSelfAssign.size() == 20, "");

    for (const auto& child : vecSelfAssign)
    {
        CC_UNUSED_PARAM(child);
        CCASSERT(child->getReferenceCount() == 2, "");
    }

    // const at
    Vector<Node*> vecConstAt = createVector();
    constFunc(vecConstAt);
}
void PivotJointScene::onEnter()
{
    BaseDemo::onEnter();
    auto visibleSize = VisibleRect::getVisibleRect().size;
    
    float pierPosY = 100.0f;
    Sprite* bridgePierL = createBox(Point(visibleSize.width/2 - 400, pierPosY), Size(40, 40));
    Sprite* bridgePierR = createBox(Point(visibleSize.width/2 + 400, pierPosY), Size(40, 40));
    bridgePierL->setRotation(0);
    bridgePierR->setRotation(0);
    bridgePierL->getPhysicsBody()->setDynamic(false);
    bridgePierR->getPhysicsBody()->setDynamic(false);
    bridgePierL->getPhysicsBody()->setTag(0);
    bridgePierR->getPhysicsBody()->setTag(0);
    this->addChild(bridgePierL);
    this->addChild(bridgePierR);
    
    float ballRadius = 40.0f;
    Sprite* fallingBall = createBall(Point(visibleSize.width/2, visibleSize.height-ballRadius), ballRadius);
    this->addChild(fallingBall);
    
    Vector<Sprite*> bamboos;
    for (int i = 0; i < BAMBOO_SEGMENTS_NUM; i++)
    {
        auto box = createBox(Point(bridgePierL->getPositionX() + BAMBOO_SEGMENT_SIZE.width * i, pierPosY), BAMBOO_SEGMENT_SIZE);
        box->setRotation(0);
        this->addChild(box);
        
        bamboos.pushBack(box);
    }
    
    PhysicsJointPin* pinJointL = PhysicsJointPin::construct(bridgePierL->getPhysicsBody(), bamboos.front()->getPhysicsBody(),bridgePierL->getPosition());
    PhysicsJointPin* pinJointR = PhysicsJointPin::construct(bridgePierR->getPhysicsBody(), bamboos.back()->getPhysicsBody(),bridgePierR->getPosition());
    pinJointL->setCollisionEnable(false);
    pinJointR->setCollisionEnable(false);
    _world->addJoint(pinJointL);
    _world->addJoint(pinJointR);

    
    for (int i = 0; i < BAMBOO_SEGMENTS_NUM - 1; i++)
    {
        auto body1 = bamboos.at(i)->getPhysicsBody();
        auto body2 = bamboos.at(i+1)->getPhysicsBody();
        
        PhysicsJointPin* pivotJointUp = PhysicsJointPin::construct(body1, body2, bamboos.at(i+1)->getPosition() + Point(-BAMBOO_SEGMENT_SIZE.width/2, BAMBOO_SEGMENT_SIZE.height/2));
        
        PhysicsJointPin* pivotJointDown = PhysicsJointPin::construct(body1, body2, bamboos.at(i+1)->getPosition() + Point(-BAMBOO_SEGMENT_SIZE.width/2, -BAMBOO_SEGMENT_SIZE.height/2));
        
        PhysicsJointRotarySpring* springJoint = PhysicsJointRotarySpring::construct(body1, body2, 2000, 0.8f);
        
        pivotJointUp->setCollisionEnable(false);
        pivotJointDown->setCollisionEnable(false);
        springJoint->setCollisionEnable(false);
        _world->addJoint(pivotJointUp);
        _world->addJoint(pivotJointDown);
        _world->addJoint(springJoint);
    }
}
TauInstrumentList::TauInstrumentList(const char* filename, const char* beginInstr, const char* endInstr, const char* beginExcl, const char* endExcl){
    init(filename, 0, '=', '/');

    functions = new FileList();
    loops = new FileList();

    functions->setFileName(filename);
    loops->setFileName(filename);

    functions->setSeparator('?');
    loops->setSeparator('=');

    bool instrState = false;
    bool exclState = false;

    for (uint32_t i = 0; i < fileTokens.size(); i++){
        Vector<char*>* toks = fileTokens[i];
        if (toks->size() == 0){
            continue;
        }
        char* t = toks->front();

        if (!strcmp(t, beginInstr)){
            if (instrState || exclState){
                PRINT_ERROR("Error parsing TAU loop tracking file: unexpected token %s", beginInstr);
            }

            instrState = true;
            continue;
        } else if (!strcmp(t, endInstr)){
            if (!instrState || exclState){
                PRINT_ERROR("Error parsing TAU loop tracking file: unexpected token %s", endInstr);
            }

            instrState = false;
            continue;
        } else if (!strcmp(t, beginExcl)){
            if (exclState || instrState){
                PRINT_ERROR("Error parsing TAU loop tracking file: unexpected token %s", beginExcl);
            }

            exclState = true;
            continue;
        } else if (!strcmp(t, endExcl)){
            if (!exclState || instrState){
                PRINT_ERROR("Error parsing TAU loop tracking file: unexpected token %s", endExcl);
            }

            exclState = false;
            continue;
        }

        if (instrState){
            if (strcmp(TAU_INST_LOOPS_TOKEN, t)){
                PRINT_ERROR("Format of instrumentation directive is '%s=\"<tau_instr_regex>\"', invalid LHS found: %s", TAU_INST_LOOPS_TOKEN, t);
            }
            if (toks->size() == 1){
                PRINT_ERROR("Format of instrumentation directive is '%s=\"<tau_instr_regex>\"', no RHS found: %s", TAU_INST_LOOPS_TOKEN, t);
            }
            if (toks->size() > 2){
                PRINT_ERROR("Format of instrumentation directive is '%s=\"<tau_instr_regex>\"', too many '=' found", TAU_INST_LOOPS_TOKEN);
            }

            loops->appendLine(TauRegexToC(toks->back(), true));
            continue;
        }

        if (exclState){
            if (toks->size() != 1){
                PRINT_ERROR("Format of exclusion directive is '\"<tau_instr_regex>\"', found: %s", t);
            }

            functions->appendLine(TauRegexToC(toks->back(), false));
            continue;
        }
    }
    ASSERT(instrState == false && "Cannot leave unclosed INSTRUMENT section in TAU instrument file");
    ASSERT(exclState == false && "Cannot leave unclosed EXCLUDE section in TAU instrument file");

    while (fileTokens.size()){
        Vector<char*>* v = fileTokens.remove(0);
        while (v->size()){
            char* c = v->remove(0);
            delete[] c;
        }
        ASSERT(v->size() == 0);
        delete v;
    }
    ASSERT(fileTokens.size() == 0);

    functions->print();
    loops->print();
}
Example #20
0
bool HelloWorld::init()
{
    if ( !Layer::init() )
    {
        return false;
    }
    SpriteFrameCache::getInstance()->addSpriteFramesWithFile("prinny.plist");
	
    Vec2 origin = Director::getInstance()->getVisibleOrigin();
    Vec2 visibleSize = Director::getInstance()->getVisibleSize();
	prinnyx_frames_right = getAnimation("PRINNYX/WALK_RIGHT/frame%d.png", 4);
	prinnyx_move_right = RepeatForever::create(Animate::create(Animation::createWithSpriteFrames(prinnyx_frames_right, 1.0f / 8)));
	prinnyx_move_right->retain();
	prinnyx_frames_left = getAnimation("PRINNYX/WALK_LEFT/frame%d.png", 4);
	prinnyx_move_left = RepeatForever::create(Animate::create(Animation::createWithSpriteFrames(prinnyx_frames_left, 1.0f / 8)));
	prinnyx_move_left->retain();
	prinnyx_frames_down = getAnimation("PRINNYX/WALK_DOWN/frame%d.png", 4);
	prinnyx_move_down = RepeatForever::create(Animate::create(Animation::createWithSpriteFrames(prinnyx_frames_down, 1.0f / 8)));
	prinnyx_move_down->retain();
	prinnyx_frames_up = getAnimation("PRINNYX/WALK_UP/frame%d.png", 4);
	prinnyx_move_up = RepeatForever::create(Animate::create(Animation::createWithSpriteFrames(prinnyx_frames_up, 1.0f / 8)));
	prinnyx_move_up->retain();

	prinny_frames_right = getAnimation("PRINNY/WALK_RIGHT/frame%d.png", 4);
	prinny_frames_left = getAnimation("PRINNY/WALK_LEFT/frame%d.png", 4);
	prinny_frames_down = getAnimation("PRINNY/WALK_DOWN/frame%d.png", 4);
	prinny_frames_up = getAnimation("PRINNY/WALK_UP/frame%d.png", 4);

	prinny_frames_idle = getAnimation("PRINNY/IDLE/frame%d.png", 2);
	prinny_idle = RepeatForever::create(Animate::create(Animation::createWithSpriteFrames(prinny_frames_idle, 1.0f / 4)));
	prinny_idle->retain();

	prinny_frames_spin = getAnimation("PRINNY/SPINSPIN/frame%d.png", 8);
	prinny_spin = RepeatForever::create(Animate::create(Animation::createWithSpriteFrames(prinny_frames_spin, 1.0f / 16)));
	prinny_spin->retain();

	//preload effects
	for (int i = 1; i <= 135; i++) {
		char s[256];
		sprintf(s, "sounds/prinny (%d).wav", i);
		CocosDenshion::SimpleAudioEngine::getInstance()->preloadEffect(s);
	}
	CocosDenshion::SimpleAudioEngine::getInstance()->preloadBackgroundMusic("sounds/Start Menu.wav");

    // background
    background = Sprite::createWithSpriteFrameName("background.png");
    background->setPosition(origin.x + visibleSize.x / 2,origin.y + visibleSize.y/2);
    this->addChild(background);
    
	Member* sprite = Member::create(prinnyx_frames_right.front(), 1, prinnyx_move_right);
	line.pushBack(sprite);
    background->addChild(sprite);
    sprite->setPosition(origin.x + visibleSize.x / 2, origin.y + visibleSize.y / 2);

	food = Sprite::createWithSpriteFrame(prinny_frames_spin.front());
	background->addChild(food);
	float sizeX = prinny_frames_spin.front()->getOriginalSizeInPixels().width;
	float sizeY = prinny_frames_spin.front()->getOriginalSizeInPixels().height;
	float bgSizeX = background->getContentSize().width;
	float bgSizeY = background->getContentSize().height;
	food->setPosition(generateRandomPosition(sizeX,bgSizeX - sizeX, sizeY, bgSizeY - sizeY));
	food->runAction(prinny_spin);
	
	this->scheduleUpdate();

	auto eventListener = EventListenerKeyboard::create();
	eventListener->onKeyPressed = [&](EventKeyboard::KeyCode keyCode, Event* event) {
		switch (keyCode) {
		case EventKeyboard::KeyCode::KEY_LEFT_ARROW:
		case EventKeyboard::KeyCode::KEY_A:
			((Member *)event->getCurrentTarget())->setSpriteFrame(prinnyx_frames_left.front());
			((Member *)event->getCurrentTarget())->setDirection(0, prinnyx_move_left);
			break;
		case EventKeyboard::KeyCode::KEY_RIGHT_ARROW:
		case EventKeyboard::KeyCode::KEY_D:
			((Member *)event->getCurrentTarget())->setSpriteFrame(prinnyx_frames_right.front());
			((Member *)event->getCurrentTarget())->setDirection(1, prinnyx_move_right);
			break;
		case EventKeyboard::KeyCode::KEY_UP_ARROW:
		case EventKeyboard::KeyCode::KEY_W:
			((Member *)event->getCurrentTarget())->setSpriteFrame(prinnyx_frames_up.front());
			((Member *)event->getCurrentTarget())->setDirection(2, prinnyx_move_up);
			break;
		case EventKeyboard::KeyCode::KEY_DOWN_ARROW:
		case EventKeyboard::KeyCode::KEY_S:
			((Member *)event->getCurrentTarget())->setSpriteFrame(prinnyx_frames_down.front());
			((Member *)event->getCurrentTarget())->setDirection(3, prinnyx_move_down);
			break;
		case EventKeyboard::KeyCode::KEY_SPACE: game_over_label->setVisible(false);
			this->start();
			break;
		}
	};

	this->_eventDispatcher->addEventListenerWithSceneGraphPriority(eventListener, sprite);

	game_over_label = cocos2d::Label::createWithSystemFont("Game Over", "Calibri", 72);
	game_over_label->setPosition(origin.x + visibleSize.x / 2, origin.y + visibleSize.y / 2);
	background->addChild(game_over_label, 5);
	game_over_label->setVisible(false);

	score_label = cocos2d::Label::createWithSystemFont("Score:", "Calibri", 20);
	score_label->setAnchorPoint(Vec2(0, 0));
	score_label->setPosition(10,10);
	background->addChild(score_label, 5);

	score_value_label = cocos2d::Label::createWithSystemFont("0", "Calibri", 20);
	score_value_label->setAnchorPoint(Vec2(0, 0));
	score_value_label->setPosition(10 + score_label->getBoundingBox().getMaxX(), 10);
	background->addChild(score_value_label, 5);

	level_label = cocos2d::Label::createWithSystemFont("Level ", "Calibri", 20);
	level_label->setAnchorPoint(Vec2(0, 0));
	level_label->setPosition(10, 10 + score_label->getBoundingBox().getMaxY());
	background->addChild(level_label, 5);

	level_value_label = cocos2d::Label::createWithSystemFont("1", "Calibri", 20);
	level_value_label->setAnchorPoint(Vec2(0, 0));
	level_value_label->setPosition(10 + level_label->getBoundingBox().getMaxX(), 10 + score_label->getBoundingBox().getMaxY());
	background->addChild(level_value_label, 5);


	CocosDenshion::SimpleAudioEngine::getInstance()->setBackgroundMusicVolume(0.5);
	CocosDenshion::SimpleAudioEngine::getInstance()->playBackgroundMusic("sounds/Start Menu.wav", true);

    return true;
}
Example #21
0
void GameMain::createHelp()
{
    auto layer=LayerColor::create(Color4B::BLACK);
    
    auto winSize=Director::getInstance()->getWinSize();
    
    
    Vector<Sprite*> helps;
    Vector<Sprite*> buttons;
    for(int i=1;i<=4;i++){
        //ヘルプ作成
        auto help=Sprite::create(StringUtils::format("help%d.png",i));
        help->setPosition(winSize/2);
        help->setVisible(false);
        layer->addChild(help);
        helps.pushBack(help);
        
        //ヘルプ選択ボタン作成
        auto button=Sprite::create("button_help_select_off.png");
        auto onButton=Sprite::create("button_help_select_on.png");
        onButton->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT);
        onButton->setPosition(Vec2::ZERO);
        onButton->setVisible(false);
        button->addChild(onButton);
        button->setPosition(HELP_SELECT+HELP_SELECT_DIFF*(i-1));
        layer->addChild(button);
        buttons.pushBack(button);
    }
    helps.front()->setVisible(true);
    buttons.front()->getChildren().front()->setVisible(true);
    
    auto listener=EventListenerTouchOneByOne::create();
    listener->onTouchBegan=[](Touch* touch,Event* event){return true;};
    listener->onTouchEnded=[helps,buttons](Touch* touch,Event* event){
        auto position=touch->getLocation();
        
        for(int i=0;i<4;i++){
            auto button=buttons.at(i);
            //どのボタンがタッチされたか調べる
            if(button->getBoundingBox().containsPoint(position)){
                //タッチされたボタンに対応するヘルプを表示
                helps.at(i)->setVisible(true);
                button->getChildren().front()->setVisible(true);
                
                //他のヘルプは消す
                for(int j=0;j<4;j++){
                    if(j==i){continue;}//表示するヘルプは飛ばす
                    helps.at(j)->setVisible(false);
                    buttons.at(j)->getChildren().front()->setVisible(false);
                }
                
                break;
            }
        }
    };
    listener->setSwallowTouches(true);
    Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener,layer);
    
    auto close=MenuItemImage::create("button_close_off.png"
                                     ,"button_close_on.png"
                                     ,[layer](Ref* pButton){
                                         layer->removeFromParent();
                                     });
    close->setPosition(Vec2(320,1200));
    
    auto menu=Menu::create(close,NULL);
    menu->setPosition(Vec2::ZERO);
    layer->addChild(menu);
    
    this->addChild(layer,convertLayerZPositionIntoInt(LayerZPosition::HELP));
}
Example #22
0
		double x_min() const
		{
			return m_x.front();
		}
Example #23
0
 /*!
  * Create a reference vector from a std::vector container.
  * Therefore: rv[n] == vec[n] and rv.size() == vec.size()
  * \param vec a const reference to an std::vector
  */
 template <typename Vector> ref_vector(const Vector &vec):
     _ptr(T()), _mem(_mem_t(&vec.front())), _size(vec.size())
 {
     /* NOP */
 }
Example #24
0
void HelloWorld::update(float delta) {
	if (foodCount >=5) {
		hasPowerUp = true;
		foodCount = 0;
		timer = 10;
		this->schedule(schedule_selector(HelloWorld::updateTimer), 1.0f);
		float sizeX = prinny_frames_idle.front()->getOriginalSizeInPixels().width;
		float sizeY = prinny_frames_idle.front()->getOriginalSizeInPixels().height;
		float bgSizeX = background->getContentSize().width;
		float bgSizeY = background->getContentSize().height;
		powerUp = Sprite::createWithSpriteFrame(prinny_frames_idle.front());
		powerUp->runAction(prinny_idle);
		background->addChild(powerUp);
		powerUp->setPosition(generateRandomPosition(sizeX, bgSizeX - sizeX, sizeY, bgSizeY - sizeY));
	}

	if (timer <= 0) {
		hasPowerUp = false;
		background->removeChild(powerUp, true);
		this->unschedule(schedule_selector(HelloWorld::updateTimer));
	}

	auto front = line.front();
	auto position = front->getPosition();

	switch (front->getDirection()) {
	case 0: position.x -= front->getSpriteFrame()->getOriginalSizeInPixels().width + 1;
		break;
	case 1: position.x += front->getSpriteFrame()->getOriginalSizeInPixels().width + 1;
		break;
	case 2: position.y += front->getSpriteFrame()->getOriginalSizeInPixels().height + 1;
		break;
	case 3: position.y -= front->getSpriteFrame()->getOriginalSizeInPixels().height + 1;
		break;
	default:
		break;
	}
	if (CollisionWithDeath()) {
		game_over_label->setVisible(true);
		cocos2d::Director::getInstance()->pause();
		return;
	}
	if (CollisionWithPowerUp()) {
		hasPowerUp = false;
		background->removeChild(powerUp, true);
		this->unschedule(schedule_selector(HelloWorld::updateTimer));
		score += 500;
		score_value_label->setString(std::to_string(score));

		cocos2d::Director::getInstance()->getScheduler()->performFunctionInCocosThread(CC_CALLBACK_0(HelloWorld::playRandomPrinnySound, this));
	}
	if (CollisionWithFood()) {
		float sizeX = prinny_frames_idle.front()->getOriginalSizeInPixels().width;
		float sizeY = prinny_frames_idle.front()->getOriginalSizeInPixels().height;
		float bgSizeX = background->getContentSize().width;
		float bgSizeY = background->getContentSize().height;
		food->setPosition(generateRandomPosition(sizeX, bgSizeX - sizeX, sizeY, bgSizeY - sizeY));
		if (!hasPowerUp) {
			foodCount++;
		}
		cocos2d::Director::getInstance()->getScheduler()->performFunctionInCocosThread(CC_CALLBACK_0(HelloWorld::playRandomPrinnySound, this));
		totalFoodCount++;
		score += 50;
		score_value_label->setString(std::to_string(score));
		addNewMember();
		if (totalFoodCount % 3 == 0) {
			auto interval = 10 + totalFoodCount/3;
			cocos2d::Director::getInstance()->setAnimationInterval(1.0 / interval);
			level++;
			level_value_label->setString(std::to_string(level));
		}
	}
	else{
		for (int i = line.size() - 1; i >= 1; i--) {
			auto prev = line.at(i - 1);
			auto curr = line.at(i);

			if (prev->getDirection() != curr->getDirection()) {
				auto new_dir = prev->getDirection();
				switch (new_dir) {
				case 0: curr->setDirection(new_dir, RepeatForever::create(Animate::create(Animation::createWithSpriteFrames(prinny_frames_left, 1.0f / 8))));
					break;
				case 1: curr->setDirection(new_dir, RepeatForever::create(Animate::create(Animation::createWithSpriteFrames(prinny_frames_right, 1.0f / 8))));
					break;
				case 2: curr->setDirection(new_dir, RepeatForever::create(Animate::create(Animation::createWithSpriteFrames(prinny_frames_up, 1.0f / 8))));
					break;
				case 3: curr->setDirection(new_dir, RepeatForever::create(Animate::create(Animation::createWithSpriteFrames(prinny_frames_down, 1.0f / 8))));
					break;
				default:
					break;
				}
			}
			curr->setPosition(prev->getPosition());
		}
		
		front->setPosition(position);
	}
}
int main(){
    
    std::cout << "Declaring a vector of tests, with objects of type \"int\"...\n";
    Vector<int> vtest;
    
    std::cout << "Testing if the vector is empty even...\n";
    assert( vtest.empty() );
    std::cout << ".. Everything seemed to go well...\n";
    
    std::cout << "Testing capacity [" << vtest.capacity() << "...\n";
    assert( vtest.capacity() == 10 );
    
    std::cout << "Starting tests in push_back method...\n";

    for( auto i = 0; i < 6; i++){
        std::cout << "push_back [" << i <<"]\n";
        vtest.push_back(i);
    }
    
    std::cout << "\nThe vector after insertions: [ ";
    for ( auto var : vtest )
        std::cout << var << " ";
    std::cout << "]\n";
    
    assert( vtest.size() == 6 );
    
    std::cout << "=========================================\n";
    
    /*
    std::cout << "Testing the method data...\n";
    int *ptr = vtest.data();
    for (auto i = 0; i < 10; i++)
        assert(*(ptr+i) == i);
        
    std::cout << "=========================================\n";
    */
    
    std::cout << "Testing methods front and back...\n";
    assert( vtest.front() == 0 );
    assert( vtest.back() == 5 );
    
    std::cout << "=========================================\n";
    
    std::cout << "Testing method pop_back...\n";
    vtest.pop_back();
    
    std::cout << "\nThe vector after removal: [ ";
    for ( auto var : vtest )
        std::cout << var << " ";
    std::cout << "]\n";
    
    assert( vtest.size() == 5 );
    
    std::cout << "=========================================\n";
    
    std::cout << "Testing operator[] and operator=...\n";
    std::cout << "vector[4] = 100 testing...\n";
    vtest[4] = 100;
    
    std::cout << "\nThe vector after insertion: [ ";
    for ( auto var : vtest )
        std::cout << var << " ";
    std::cout << "]\n";
    
    std::cout << "Testing at operator...\n";
    assert( vtest.at(4) == 100 );
    
    std::cout << "=========================================\n";
    
    std::cout << "Testing method assign... \n";
    
    vtest.assign(500);
    
    std::cout << "\nThe vector after asign: [ ";
    for ( auto var : vtest )
        std::cout << var << " ";
    std::cout << "]\n";
    
    assert( vtest.front() == 500 );
    assert( vtest.back() == 500 );
    
    std::cout << "=========================================\n";
    
    std::cout << "Testing clear method...\n";
    
    vtest.clear();
    
    std::cout << "\nThe vector after clear: [ ";
    for ( auto var : vtest )
        std::cout << var << " ";
    std::cout << "]\n";
    
    std::cout << "=========================================\n";
    
    for( auto i = 0; i < 10; i++)
        vtest.push_back(i);
    
    std::cout << "\nJust filling again: [ ";
    for ( auto var : vtest )
        std::cout << var << " ";
    std::cout << "]\n";
    
    std::cout << "=========================================\n";
    
    size_type newCpct = 20;
    vtest.reserve( newCpct );
    
    for( auto i = 10; i < 20; i++)
        vtest.push_back(i);
    
    std::cout << "\nVector after reserve memory: [ ";
    for ( auto var : vtest )
        std::cout << var << " ";
    std::cout << "]\n";
    std::cout << "=========================================\n";
    
    std::cout << "Testing \"copy assign\" and \"copy move\"...\n";
    
    std::cout << "Creating a vector of int [v2]...\n";
    Vector<int> v2 ( vtest );
    std::cout << "Creating a vector of int [v3] and type v3 = v2... \n";
    Vector<int> v3 = v2;
    
    std::cout << "Cheking...\n";
    for (auto i = 0; i < 9; i++) {
        assert(v2[i] == i);
        assert(v3[i] == i);
    }
    
    std::cout << "Creating v4 and moving v2's elements to it... \n";
    Vector<int> v4 ( std::move( v2 ) );
    std::cout << "Creating v5 and moving v3's elements to it... \n";
    Vector<int> v5 = std::move( v3 );
    
    std::cout << "Checking...\n";
    for (auto i = 0; i < 9; i++) {
        assert(v4[i] == i);
        assert(v5[i] == i);
    }
    
    std::cout << "Benchmark v2 and v3 is null...\n";
    
    assert( v2.data() == nullptr );
    assert( v3.data() == nullptr );
    
    std::cout << "It seems that everything worked out here... \n";
    
    std::cout << "=========================================\n";
    
    std::cout << "Testing iterators... \n";
    std::cout << "Creatin a vector [vtest2].\n";
    Vector<int> vtest2;
    
    for( auto i = 0; i < 10; i++)
        vtest2.push_back(i);
    
    std::cout << "\nJust filling: [ ";
    for ( auto var : vtest )
        std::cout << var << " ";
    std::cout << "]\n";
    
    auto i = 0;
    for ( auto it = vtest2.begin(); it != vtest2.end(); it++, i++)
        assert(*it == i);

    assert( vtest2.cbegin() != vtest2.cend() );
    
    std::cout << "=========================================\n";
    std::cout << "Everything seemed to run fine, leaving the program ...\n";

    return EXIT_SUCCESS;
}