Ejemplo n.º 1
0
Vector3f generateRandomPosition(Vector3f* vertices, Vector3f* edges)
{
    if( getCore()->getRandToolkit()->getUniform( 0,1 ) < oneDivThree )
    {
        return generateRandomPosition( vertices[0], edges[0], vertices[0], edges[1] );
    }
    else if( getCore()->getRandToolkit()->getUniform( 0,1 ) < oneDivTwo )
    {
        return generateRandomPosition( vertices[0], edges[0], vertices[1], edges[2] );
    }
    else
    {
        return generateRandomPosition( vertices[1], edges[2], vertices[0], edges[1] );
    }
}
Ejemplo n.º 2
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();
}
Ejemplo n.º 3
0
QPointF Unit::generateNextValidPos()
{
    QPointF nextPos(0, 0);
    bool continua;
    QRectF escRect = scene()->sceneRect();
    int intentos = 0;
    do{
        if(intentos < 3){
            nextPos = pos() + generateRandomPosition(100, angRange);
            intentos++;
        }else{
            nextPos = pos() + generateRandomPosition(100, 0, 360);
        }
        continua = !((nextPos.x() > escRect.x()) && (nextPos.x() < escRect.x() + escRect.width()) && (nextPos.y() > escRect.y()) && (nextPos.y() < escRect.y() + escRect.height()));
    }while(continua);
    return nextPos;
}
Ejemplo n.º 4
0
    void generateRandomParticles(
        ParticleStore& particles,
        Bounds const& bounds,
        Generator& gen
    ) {
        typedef typename ParticleStore::value_type Particle;
        typedef typename ParticleStore::iterator PvIter;

        for(PvIter p(particles.begin()); p!=particles.end(); ++p) {
            generateRandomPosition(bounds.begin(), bounds.end(), p->beginPosition(), gen);
        }
    }
Ejemplo n.º 5
0
        void adjustBounds(
            Particle const& particle,
            PositionIter posIter,
            Alg const& alg,
            Generator& gen
        ) const {
            if(gen() < CMCR_) {
                if(gen() < PAR_) {
                    // not sure if this is exactly what was meant... but it seems to make sense.
                    moveParticleInbounds(posIter, alg.getBounds(), jitter_, gen);
                } else {
                    // use a previous good particle.
                    Particle const&
                        p(alg.getReplacementParticle());

                    std::copy(p.beginPosition(), p.endPosition(), posIter);
                    moveParticleSlightly(posIter, alg.getBounds(), jitter_, gen); // I don't think they did this bit.
                }
            } else {
                // select a new random position.
                generateRandomPosition(alg.getBounds().begin(), alg.getBounds().end(), posIter, gen);
            }
        }
Ejemplo n.º 6
0
void Particles::draw(){

    for(int i = 0; i < particles.size(); i++){
        //przestawiamy dotkniete
        if(particles[i]->wasTouched()){
            //it->destroy();
            //it = particles.erase(it);
            particles[i]->resetTouched();
            particles[i]->setPosition(generateRandomPosition());
            //generateParticle();
        }


        if (!program || !PV) return;

        // Calculate model matrix
        glm::mat4 model(1.0f);

        const b2Vec2 &pos = particles[i]->getPosition();
        model = glm::translate(model, glm::vec3(pos.x, pos.y,-20));
        model = glm::scale(model, scale);

        program->use();
        glUniformMatrix4fv(PVLocation, 1, GL_FALSE, glm::value_ptr(*PV));
        glUniformMatrix4fv(MLocation, 1, GL_FALSE, glm::value_ptr(model));

        glActiveTexture(GL_TEXTURE0);

        glBindTexture(GL_TEXTURE_2D, texture.id());
        glUniform1i(texLocation, 0);

        glBindVertexArray(vao);
        glDrawArrays(GL_TRIANGLES, 0, vertices.size());
        glBindVertexArray(0);
    }
}
Ejemplo n.º 7
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;
}
Ejemplo n.º 8
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);
	}
}
Ejemplo n.º 9
0
void Particles::generateParticle(){
    b2Vec2 pos = generateRandomPosition();

    particles.push_back(new Particle());
    particles.back()->setPhysics(world,pos.x,pos.y);
}
Ejemplo n.º 10
0
Forest::Forest(Actor* parent, ForestDesc* desc) : Actor( parent )
{
    assert( desc );
    assert( desc->surface );
    assert( desc->assetName.length() );
    assert( desc->cache.length() );

    // copy descriptor
    _desc = *desc;    

    // load asset
    _asset = Gameplay::iEngine->createAsset( engine::atBinary, _desc.assetName.c_str() );

    // enumerate clumps
    callback::ClumpL clumps;    
    _asset->forAllClumps( callback::enumerateClumps, &clumps );
    assert( clumps.size() );

    // fill batch schemes
    Matrix4f clumpM;
    MatrixConversion trunkConversion;
    MatrixConversion canopyConversion;
    _canopyScheme.numLods = _trunkScheme.numLods = clumps.size();
    for( callback::ClumpI clumpI = clumps.begin(); clumpI != clumps.end(); clumpI++ )
    {
        // determine lod Id and check for consistency
        unsigned int lodId = getClumpLodId( *clumpI );
        if( _trunkScheme.lodGeometry[lodId] )
        {
            throw Exception( "Clump \"%s\" is a duplication of existing LOD!", (*clumpI)->getName() );
        }
        // fill schemes
        engine::IAtomic* trunkAtomic     = Gameplay::iEngine->getAtomic( *clumpI, Gameplay::iEngine->findFrame( (*clumpI)->getFrame(), "Trunk" ) ); assert( trunkAtomic );
        engine::IAtomic* canopyAtomic    = Gameplay::iEngine->getAtomic( *clumpI, Gameplay::iEngine->findFrame( (*clumpI)->getFrame(), "Canopy" ) ); assert( canopyAtomic );
        _trunkScheme.lodGeometry[lodId]  = trunkAtomic->getGeometry();        
        _canopyScheme.lodGeometry[lodId] = canopyAtomic->getGeometry();
        _trunkScheme.lodDistance[lodId] = _canopyScheme.lodDistance[lodId] = _desc.lodDistance[lodId];
        // calculate conversions for nearest LOD
        if( lodId == 0 )
        {
            clumpM = (*clumpI)->getFrame()->getLTM();
            trunkConversion.setup( clumpM, trunkAtomic->getFrame()->getLTM() );
            canopyConversion.setup( clumpM, canopyAtomic->getFrame()->getLTM() );
        }
    }

    _trunkScheme.flags = _canopyScheme.flags = 0;

    // check schemes
    assert( _trunkScheme.isValid() );
    assert( _canopyScheme.isValid() );

    // create full cache names
    std::string instanceCache  = _desc.cache; instanceCache  += ".matrices";
    std::string trunkBspCache  = _desc.cache; trunkBspCache  += ".trunk";
    std::string canopyBspCache = _desc.cache; canopyBspCache += ".canopy";

    // try to load forest from cache
    IResource* resource = getCore()->getResource( instanceCache.c_str(), "rb" );
    if( resource )
    {
        unsigned int numTrees;
        fread( &numTrees, sizeof(unsigned int), 1, resource->getFile() );
        _treeMatrix.resize( numTrees );
        fread( &_treeMatrix[0], sizeof(Matrix4f), numTrees, resource->getFile() );
        resource->release();
    }
    else
    {
        // obtain surface properties
        Matrix4f ltm = _desc.surface->getFrame()->getLTM();
        engine::IGeometry* geometry = _desc.surface->getGeometry();
        engine::Mesh* mesh = geometry->createMesh();

        float preservedDistance = _desc.collScale * ( geometry->getAABBSup() - geometry->getAABBInf() ).length();

        // iterate surface triangles
        Vector3f vertex[3];
        Vector3f edge[3];
        Vector3f edgeN[2];
        Vector3f normal;
        Vector3f pos;
        float cosA, sinA, angle, square, probability, scale;
        unsigned int i,j,numTreesInTriangle;
        Matrix4f instanceM;    
        for( i=0; i<mesh->numTriangles; i++ )
        {
            // transform triangle vertices to world space
            vertex[0] = Gameplay::iEngine->transformCoord( mesh->vertices[mesh->triangles[i].vertexId[0]], ltm );
            vertex[1] = Gameplay::iEngine->transformCoord( mesh->vertices[mesh->triangles[i].vertexId[1]], ltm );
            vertex[2] = Gameplay::iEngine->transformCoord( mesh->vertices[mesh->triangles[i].vertexId[2]], ltm );
            // calculate triangle square value...
            edge[0] = vertex[1] - vertex[0];
            edge[1] = vertex[2] - vertex[0];
            edge[2] = vertex[2] - vertex[1];
            edgeN[0] = edge[0]; edgeN[0].normalize();
            edgeN[1] = edge[1]; edgeN[1].normalize();
            normal.cross( edgeN[0], edgeN[1] );
            cosA = Vector3f::dot( edgeN[0], edgeN[1] );
            if( cosA > 1.0f ) angle = 0.0f; 
            else if( cosA < -1.0f ) angle = 180; 
            else angle = acosf( cosA );
            sinA = sin( angle );
            square = 0.5f * edge[0].length() * edge[1].length() * sinA / 10000.0f;
            // obtain number of particles in this triangle
            numTreesInTriangle = unsigned int( square * _desc.density );
            if( !numTreesInTriangle )
            {
                // include probability method to decide to place grass on to this triangle
                probability = square / ( 1 / _desc.density );
                assert( probability <= 1.0f );
                if( probability > 0 && getCore()->getRandToolkit()->getUniform( 0, 1 ) <= probability ) numTreesInTriangle++;
            }
            // generate trees
            for( j=0; j<numTreesInTriangle; j++ )
            {
                // generate scale
                scale = getCore()->getRandToolkit()->getUniform( _desc.minScale, _desc.maxScale );
                // generate coordinate
                pos = generateRandomPosition( vertex, edge );                
                // generate matrix
                instanceM.set(
                    clumpM[0][0] * scale, clumpM[0][1] * scale, clumpM[0][2] * scale, 0.0f,
                    clumpM[1][0] * scale, clumpM[1][1] * scale, clumpM[1][2] * scale, 0.0f,
                    clumpM[2][0] * scale, clumpM[2][1] * scale, clumpM[2][2] * scale, 0.0f,
                    0.0f, 0.0f, 0.0f, 1.0f
                );
                instanceM = Gameplay::iEngine->rotateMatrix( instanceM, Vector3f(0,1,0), getCore()->getRandToolkit()->getUniform(0,360) );
                instanceM[3][0] = pos[0];
                instanceM[3][1] = pos[1];
                instanceM[3][2] = pos[2];
                _treeMatrix.push_back( instanceM );
            }
            Scene::progressCallback( 
                Gameplay::iLanguage->getUnicodeString(844),
                float( i ) / float( mesh->numTriangles ),
                getScene()
            );
        }

        // release temporary resources
        Gameplay::iEngine->releaseMesh( mesh );

        // write solution
        ccor::IResource* resource = getCore()->getResource( instanceCache.c_str(), "wb" );
        unsigned int numTrees = _treeMatrix.size();
        fwrite( &numTrees, sizeof(unsigned int), 1, resource->getFile() );
        fwrite( &_treeMatrix[0], sizeof(Matrix4f), numTrees, resource->getFile() );
        resource->release();
    }
    
    // build batches
    _trunkBatch  = Gameplay::iEngine->createBatch( _treeMatrix.size(), &_trunkScheme ); assert( _trunkBatch );
    _canopyBatch = Gameplay::iEngine->createBatch( _treeMatrix.size(), &_canopyScheme ); assert( _canopyBatch );
    // fill batches
    for( unsigned int i=0; i<_treeMatrix.size(); i++ )
    {
        _trunkBatch->setMatrix( i, trunkConversion.convert( _treeMatrix[i] ) );
        _canopyBatch->setMatrix( i, canopyConversion.convert( _treeMatrix[i] ) );
    }

    // create spatial acceleration structures BSP trees
    _trunkBatch->createBatchTree( _desc.bspLeafSize, trunkBspCache.c_str() );
    _canopyBatch->createBatchTree( _desc.bspLeafSize, canopyBspCache.c_str() );
    
    // add batches to scene
    getScene()->getStage()->add( _trunkBatch );
    getScene()->getStage()->add( _canopyBatch );

    // add layers to scene
    if( _desc.layers )
    {
        getScene()->getStage()->add( _desc.layers );
    }

    // set no sound
    _rustleSound = _squeakSound = NULL;
}
Ejemplo n.º 11
0
void Board::init()
{
	// Fill the board with random jewels
	for (size_t i = 0; i < m_board.size(); ++i)
	{
		m_board[i] = generateRandomJewel();

		// For every third jewel, make sure it's different from the previous three
		if (i % 3 == 2)
		{
			while (m_board[i] == m_board[i-1])
			{
				m_board[i] = generateRandomJewel();
			}
		}
	}

	// Now we know there are no horizontal matches, we need to check for vertical
	// It's enough if we check every second row
	std::vector<int> matches;

	for (size_t i = m_columns; i < m_board.size(); ++i)
	{
		if (findVerticalMatches(i, matches))
		{
			// Change every 3rd element so it doesn't match others
			for (size_t j = 0; j < matches.size(); ++j)
			{
				if(j % 3 == 2)
				{
					int k = matches[j];

					if (k == 0 || k == m_board.size() - 1)
					{
						k = matches[j-1];
					}
					
					while(m_board[k] == m_board[k-1] && m_board[k] == m_board[k+1] && m_board[k] == m_board[k-m_columns])
					{
						m_board[i] = generateRandomJewel();
					}
				}
			}
		}

		// Skip one row
		if (isFirstColumn(i))
		{
			i += m_columns;
		}
	}

	// Make sure there are some possible moves on the board
	int pos;
	int swap;

	for (size_t i = 0; i < 2; ++i) // change 2 to m_difficulty
	{
		pos = generateRandomPosition();
		swap = generateRandomSwap(pos);
		
		if (swap == pos - m_columns || swap == pos + m_columns)
		{
			m_board[pos - 1] = m_board[pos];
			m_board[pos + 2] = m_board[pos];
			doSwap(pos, swap);
		}
		else
		{
			m_board[pos - m_columns] = m_board[pos];
			m_board[pos + m_columns] = m_board[pos];
			doSwap(pos, swap);
		}
	}

	// Validate and remove any remaining matches
	for (size_t i = 0; i < m_board.size(); ++i)
	{
		matches.clear();

		while (checkPosition(i, matches))
		{
			for (size_t j = 0; j < matches.size(); ++j)
			{
				if (j % 2 == 0)
				{				
					m_board[matches[j]] = generateRandomJewel();
				}
			}
		}
	}
}