Пример #1
0
/*----------------------------------------------------------------------------*/
int GameStep(struct GameData* pGameData)
{
	int rt = 1;		/* 0=game over, 1=0K, 2=new piece, 3=new level */
	if (pGameData->m_FallingRow == -1) 
	{
		rt = 2;
		pGameData->m_FallingCol = pGameData->m_Center;
		pGameData->m_FallingPiece = pGameData->m_Preview;
		pGameData->m_BlkRot = 0;
		pGameData->m_BlkNum = pGameData->m_BlkPreviewNum;
		pGameData->m_BlkPreviewNum = (int)(rand()/(double)0x7fffffff*pGameData->m_MaxPieces);
		pGameData->m_Preview = pGameData->m_Shapes[pGameData->m_BlkPreviewNum][pGameData->m_BlkRot];
		pGameData->m_FallingRow = 0;
		if (!PlacePiece(pGameData, pGameData->m_FallingRow, pGameData->m_FallingCol) || pGameData->m_Level == pGameData->m_LastLevel+1)	// try to place
		{
			pGameData->m_GameOver = 1;
			rt = 0;		/* game over */
		}
	}
	else
	{
		if (!MovePieceDown(pGameData))
		{
			pGameData->m_StepDuration = 640-55*pGameData->m_Level;	/* speedInt[m_Level-1]; */
			rt = GameClearFullRows(pGameData);
			CalculateScore(pGameData);
		}
	}
//		Sleep(10000);
	if (pGameData->m_DropCount > 0)
	{
		pGameData->m_DropCount++;
	}
	return rt;
}
Пример #2
0
void AdItemList::InitScoreByThreshosld(const UserProfile & user_profile, const set<AdGroupPtr> & groups) {
  for(set<AdGroupPtr>::const_iterator it = groups.begin(); it != groups.end(); ++it) {
    AdGroupPtr group = *it;
    double score = CalculateScore(user_profile, group->max_price());
    AdItemPtr item = new AdItem(group->group_id(), group->max_price(), 1, score);
    items_.insert(item);
  }
}
Пример #3
0
void ScreenEvaluation::Init(EvaluationData _Data, String SongAuthor, String SongTitle)
{
	if (!ScreenEvaluationMusic)
	{
		ScreenEvaluationMusic = new SoundStream();
		ScreenEvaluationMusic->Open((GameState::GetInstance().GetSkinPrefix() + "screenevaluationloop.ogg").c_str());
		ScreenEvaluationMusic->SetLoop(true);
		MixerAddStream(ScreenEvaluationMusic);
	}

	ScreenEvaluationMusic->SeekTime(0);
	ScreenEvaluationMusic->Play();


	Background.SetImage(GameState::GetInstance().GetSkinImage(Configuration::GetSkinConfigs("EvaluationBackground")));
	Background.AffectedByLightning = true;
	if (!Font)
	{
		Font = new BitmapFont();
		Font->LoadSkinFontImage("font_screenevaluation.tga", Vec2(10, 20), Vec2(32, 32), Vec2(10,20), 32);
		Font->SetAffectedByLightning(true);
	}
	Results = _Data;

	char _Results[256];
	const char *Text ="Excellent: \n"
					  "Perfect:   \n"
					  "Great:     \n"
					  "Bad:       \n"
					  "NG:        \n"
					  "OK:        \n"
					  "Misses:    \n"
					  "\n"
					  "Max Combo: \n"
					  "Score:     \n";

	ResultsString = Text;

	sprintf(_Results, "%d\n%d\n%d\n%d\n%d\n%d\n%d\n\n%d\n%d\n",
	Results.NumExcellents,
		Results.NumPerfects,
		Results.NumGreats,
		Results.NumBads,
		Results.NumNG,
		Results.NumOK,
		Results.NumMisses,
		Results.MaxCombo,
		CalculateScore());

	ResultsNumerical = _Results;
	WindowFrame.SetLightMultiplier(1);
	WindowFrame.SetLightPosition(glm::vec3(0,0,1));

	TitleFormat = SongTitle + " by " + SongAuthor;
}
Пример #4
0
int CAlnVec::CalculateScore(TNumrow row1, TNumrow row2) const
{
    TNumrow       numrows = m_NumRows;
    TNumrow       index1 = row1, index2 = row2;
    TSignedSeqPos start1, start2;
    string        buff1, buff2;
    bool          isAA1, isAA2;
    int           score = 0;
    TSeqPos       len;
    
    isAA1 = GetBioseqHandle(row1).GetBioseqCore()
        ->GetInst().GetMol() == CSeq_inst::eMol_aa;

    isAA2 = GetBioseqHandle(row2).GetBioseqCore()
        ->GetInst().GetMol() == CSeq_inst::eMol_aa;

    CSeqVector&   seq_vec1 = x_GetSeqVector(row1);
    TSeqPos       size1    = seq_vec1.size();
    CSeqVector &  seq_vec2 = x_GetSeqVector(row2);
    TSeqPos       size2    = seq_vec2.size();

    for (TNumseg seg = 0; seg < m_NumSegs; seg++) {
        start1 = m_Starts[index1];
        start2 = m_Starts[index2];

        if (start1 >=0  &&  start2 >= 0) {
            len = m_Lens[seg];

            if (IsPositiveStrand(row1)) {
                seq_vec1.GetSeqData(start1,
                                    start1 + len,
                                    buff1);
            } else {
                seq_vec1.GetSeqData(size1 - (start1 + len),
                                    size1 - start1,
                                    buff1);
            }
            if (IsPositiveStrand(row2)) {
                seq_vec2.GetSeqData(start2,
                                    start2 + len,
                                    buff2);
            } else {
                seq_vec2.GetSeqData(size2 - (start2 + len),
                                    size2 - start2,
                                    buff2);
            }
            score += CalculateScore(buff1, buff2, isAA1, isAA2);
        }

        index1 += numrows;
        index2 += numrows;
    }
    return score;
}
Пример #5
0
/*----------------------------------------------------------------------------*/
int GameDrop(struct GameData* pGameData)
{
	printf("in GameDrop\n");
	int rtc = 0;
	pGameData->m_DropCount = 0;
	if (pGameData->m_FallingRow >= 0)
	{
		while (pGameData->m_FallingRow >= 0) 
		{
			if (MovePieceDown(pGameData)) pGameData->m_DropCount++;
		}
		rtc = GameClearFullRows(pGameData);
		CalculateScore(pGameData);
	}
	return rtc;
}
Пример #6
0
void VisionEngine::ProcessContours() {
	Contour pContour;
	//GRIP Network Table

	std::vector<double> width = table->GetNumberArray("width",
			llvm::ArrayRef<double>());
	std::vector<double> height = table->GetNumberArray("height",
			llvm::ArrayRef<double>());
	std::vector<double> area = table->GetNumberArray("area",
			llvm::ArrayRef<double>());
	std::vector<double> centerX = table->GetNumberArray("centerX",
			llvm::ArrayRef<double>());
	std::vector<double> centerY = table->GetNumberArray("centerY",
			llvm::ArrayRef<double>());
	size_t contourCount = width.size();

	AgeContourList();
	ContourList.remove_if(Contour::ContourExpired);

	if (contourCount > 0) {
		for (size_t i = 0; i < contourCount; i++) {
			Contour pContour(width[i], height[i], area[i], centerX[i], centerY[i]);
			CalculateScore(pContour);
			ContourList.push_front(pContour);
		}
	}

	AgeContourList();
	ContourList.remove_if(Contour::ContourExpired);

	// remove "runts" from contour list
	ContourList.remove_if(Contour::ContourIsRunt);

	if (!ContourList.empty()) {
		//Sort the contour list to find the best
		ContourList.sort(Contour::ScoreSort);

		BestNewContour = ContourList.begin();

		// Age current best contour
		AgeContour(BestContour);

		BestContour = SelectBestContour(*BestNewContour);
	}
}
Пример #7
0
SearchSpot* SearchGroup::FindBestSearchSpot(EntityId entityID, SearchSpotQuery* query)
{
	SearchSpotIter it = m_searchSpots.begin();
	SearchSpotIter end = m_searchSpots.end();

	SearchSpot* bestScoredSearchSpot = NULL;
	SearchSpot* lastSeenSearchSpot = NULL;
	float bestScore = FLT_MIN;

	Vec3 targetCurrentPos(ZERO);
	if(m_targetID)
	{
		Agent agent(m_targetID);
		if(agent.IsValid())
			targetCurrentPos = agent.GetPos();
	}

	for ( ; it != end; ++it)
	{
		SearchSpot& searchSpot = (*it);

		if (searchSpot.GetStatus() == NotSearchedYet)
		{
			float score = CalculateScore(searchSpot, entityID, query, targetCurrentPos);
			if (score > bestScore)
			{
				bestScoredSearchSpot = &searchSpot;
				bestScore = score;
			}
		}

		if(searchSpot.GetStatus() != Unreachable && searchSpot.GetStatus() != BeingSearchedRightAboutNow)
		{
			if(!lastSeenSearchSpot || searchSpot.m_lastTimeObserved.GetValue() < lastSeenSearchSpot->m_lastTimeObserved.GetValue())
			{
				lastSeenSearchSpot = &searchSpot;
			}
		}
	}

	return bestScoredSearchSpot ? bestScoredSearchSpot : lastSeenSearchSpot;
}
Пример #8
0
MoveNode::MoveNode(const ChessMove& GuessMove, MoveNode* _parent, bool _bEvaluate, bool _MinLevel, Chromosome* _calcChromo, ChessBoard* _ChessBoardInstance)
{ 
	//move = ChessMove(_ChessBoardInstance);
	move = GuessMove; 
	BoardScore = -1; 
	parent = _parent; 
	bEvaluate = _bEvaluate;
	if(!_calcChromo)
		ChessAssert();
	calcChromo = _calcChromo;
	if (bEvaluate)
		CalculateScore(); 
	bLeafNode = false;
	bMinLevel = _MinLevel;
	bestNode = NULL;
	iMinScore = 0x7FFFFFFF;
	iMaxScore = -1000000;
	ChessBoardInstance = _ChessBoardInstance;
	UnThreadedCopy = NULL;
}
Пример #9
0
float ComboController::ExecuteCombo()
{
	TriggerAction action;
	switch (m_activeComboType)
	{
	case ComboTypeBoost30:
		action = TriggerActionBoost30Combo;
		break;

	case ComboTypeBoost45:
		action = TriggerActionBoost45Combo;
		break;

	case ComboTypeBoost60:
		action = TriggerActionBoost60Combo;
		break;

	case ComboTypeStop:
		action = TriggerActionStopCombo;
		break;

	case ComboTypeBlock45:
		action = TriggerActionBlock45Combo;
		break;

	case ComboTypeBlock60:
		action = TriggerActionBlock60Combo;
		break;

	default:
		action = TriggerActionStop;
		assert("Bad m_activeComboType.");
		break;
	}
	m_activeTrigger->SetAction(action);

	PerformTriggerAction();

	return CalculateScore();
}
Пример #10
0
void OptimizeIndices(ModelSubGeometryLodLevel* subGeom, ModelVertexBuffer* vb, ModelIndexBuffer* ib)
{
    PODVector<Triangle> oldTriangles;
    PODVector<Triangle> newTriangles;

    if (subGeom->indexCount_ % 3)
    {
        PrintLine("Index count is not divisible by 3, skipping index optimization");
        return;
    }

    for (unsigned i = 0; i < vb->vertices_.Size(); ++i)
    {
        vb->vertices_[i].useCount_ = 0;
        vb->vertices_[i].cachePosition_ = -1;
    }

    for (unsigned i = subGeom->indexStart_; i < subGeom->indexStart_ + subGeom->indexCount_; i += 3)
    {
        Triangle triangle;
        triangle.v0_ = ib->indices_[i];
        triangle.v1_ = ib->indices_[i + 1];
        triangle.v2_ = ib->indices_[i + 2];
        vb->vertices_[triangle.v0_].useCount_++;
        vb->vertices_[triangle.v1_].useCount_++;
        vb->vertices_[triangle.v2_].useCount_++;
        oldTriangles.Push(triangle);
    }

    for (unsigned i = 0; i < vb->vertices_.Size(); ++i)
        CalculateScore(vb->vertices_[i]);

    PODVector<unsigned> vertexCache;

    while (oldTriangles.Size())
    {
        unsigned bestTriangle = M_MAX_UNSIGNED;
        float bestTriangleScore = -1.0f;

        // Find the best triangle at this point
        for (unsigned i = 0; i < oldTriangles.Size(); ++i)
        {
            Triangle& triangle = oldTriangles[i];
            float triangleScore =
                vb->vertices_[triangle.v0_].score_ +
                vb->vertices_[triangle.v1_].score_ +
                vb->vertices_[triangle.v2_].score_;

            if (triangleScore > bestTriangleScore)
            {
                bestTriangle = i;
                bestTriangleScore = triangleScore;
            }
        }

        if (bestTriangle == M_MAX_UNSIGNED)
        {
            PrintLine("Could not find next triangle, aborting index optimization");
            return;
        }

        // Add the best triangle
        Triangle triangleCopy = oldTriangles[bestTriangle];
        newTriangles.Push(triangleCopy);
        oldTriangles.Erase(oldTriangles.Begin() + bestTriangle);

        // Reduce the use count
        vb->vertices_[triangleCopy.v0_].useCount_--;
        vb->vertices_[triangleCopy.v1_].useCount_--;
        vb->vertices_[triangleCopy.v2_].useCount_--;

        // Model the LRU cache behaviour
        // Erase the triangle vertices from the middle of the cache, if they were there
        for (unsigned i = 0; i < vertexCache.Size(); ++i)
        {
            if ((vertexCache[i] == triangleCopy.v0_) ||
                    (vertexCache[i] == triangleCopy.v1_) ||
                    (vertexCache[i] == triangleCopy.v2_))
            {
                vertexCache.Erase(vertexCache.Begin() + i);
                --i;
            }
        }

        // Then push them to the front
        vertexCache.Insert(vertexCache.Begin(), triangleCopy.v0_);
        vertexCache.Insert(vertexCache.Begin(), triangleCopy.v1_);
        vertexCache.Insert(vertexCache.Begin(), triangleCopy.v2_);

        // Update positions & scores of all vertices in the cache
        // Give position -1 if vertex is going to be erased
        for (unsigned i = 0; i < vertexCache.Size(); ++i)
        {
            ModelVertex& vertex = vb->vertices_[vertexCache[i]];
            if (i >= VERTEX_CACHE_SIZE)
                vertex.cachePosition_ = -1;
            else
                vertex.cachePosition_ = i;
            CalculateScore(vertex);
        }

        // Finally erase the extra vertices
        if (vertexCache.Size() > VERTEX_CACHE_SIZE)
            vertexCache.Resize(VERTEX_CACHE_SIZE);
    }

    // Rewrite the index data now
    unsigned i = subGeom->indexStart_;
    for (unsigned j = 0; j < newTriangles.Size(); ++j)
    {
        ib->indices_[i++] = newTriangles[j].v0_;
        ib->indices_[i++] = newTriangles[j].v1_;
        ib->indices_[i++] = newTriangles[j].v2_;
    }
}
Пример #11
0
//游戏结束
bool __cdecl CTableFrameSink::OnEventGameEnd(WORD wChairID, IServerUserItem * pIServerUserItem, BYTE cbReason)
{
	switch (cbReason)
	{
	case GER_NORMAL:		//常规结束	
		{
			//派发扑克
			DispatchTableCard();

			//计算分数
			__int64 iBankerWinScore=CalculateScore();

			//递增次数
			m_wBankerTime++;

			//结束消息
			CMD_S_GameEnd GameEnd;
			ZeroMemory(&GameEnd,sizeof(GameEnd));

			//庄家信息
			GameEnd.nBankerTime = m_wBankerTime;
			GameEnd.iBankerTotallScore=m_iBankerWinScore;
			GameEnd.iBankerScore=iBankerWinScore;
			GameEnd.cbGoalAnimal = m_iGoalAnimal;

			//发送积分
			GameEnd.cbTimeLeave=TIME_GAME_END;	
			for ( WORD wUserIndex = 0; wUserIndex < GAME_PLAYER; ++wUserIndex )
			{
				IServerUserItem *pIServerUserItem = m_pITableFrame->GetServerUserItem(wUserIndex);
				if ( pIServerUserItem == NULL ) 
					continue;

				//设置成绩
				GameEnd.iUserScore=m_iUserWinScore[wUserIndex];

				//返还积分
				GameEnd.iUserReturnScore=m_iUserReturnScore[wUserIndex];

				//设置税收
				if (m_iUserRevenue[wUserIndex]>0) 
					GameEnd.iRevenue=m_iUserRevenue[wUserIndex];
				else if (m_wCurrentBanker!=INVALID_CHAIR) 
					GameEnd.iRevenue=m_iUserRevenue[m_wCurrentBanker];
				else 
					GameEnd.iRevenue=0;

				//发送消息					
				m_pITableFrame->SendTableData(wUserIndex,SUB_S_GAME_END,&GameEnd,sizeof(GameEnd));
				m_pITableFrame->SendLookonData(wUserIndex,SUB_S_GAME_END,&GameEnd,sizeof(GameEnd));
			}

			return true;
		}
	case GER_USER_LEFT:		//用户离开
		{
			//闲家离开,即刻结算
			if (m_wCurrentBanker!=wChairID)
			{
				//变量定义
				__int64 iScore=0;
				__int64 iRevenue=0;
				enScoreKind ScoreKind=enScoreKind_Flee;

				//统计成绩
				for( int i=0; i<JETTON_AREA_COUNT; i++)
					iScore += m_iUserAreaScore[wChairID][i];
				iScore = -iScore;

				//写入积分
				if (iScore!=0L) 
					m_pITableFrame->WriteUserScore(pIServerUserItem, iScore,iRevenue, ScoreKind);

				return true;
			}

			//庄家离开,状态判断
			if (m_pITableFrame->GetGameStatus()!=GS_GAME_END)
			{
				//提示消息
				TCHAR szTipMsg[128];
				_sntprintf(szTipMsg,CountArray(szTipMsg),TEXT("由于庄家[ %s ]强退,游戏提前结束!"),pIServerUserItem->GetAccounts());

				//发送消息
				SendGameMessage(INVALID_CHAIR,szTipMsg);	

				//设置状态
				m_pITableFrame->SetGameStatus(GS_GAME_END);

				//设置时间
				m_pITableFrame->KillGameTimer(IDI_PLACE_JETTON);
				m_pITableFrame->SetGameTimer(IDI_GAME_END,TIME_GAME_END*1000,1,0L);

				//派发扑克
				DispatchTableCard();

				//计算分数
				CalculateScore();

				//结束消息
				CMD_S_GameEnd GameEnd;
				ZeroMemory(&GameEnd,sizeof(GameEnd));

				//庄家信息
				GameEnd.nBankerTime = m_wBankerTime;
				GameEnd.iBankerTotallScore=m_iBankerWinScore;
				if (m_iBankerWinScore>0) 
					GameEnd.iBankerScore=0;

				//发送积分
				GameEnd.cbTimeLeave=TIME_GAME_END;	
				for ( WORD wUserIndex = 0; wUserIndex < GAME_PLAYER; ++wUserIndex )
				{
					IServerUserItem *pIServerUserItem = m_pITableFrame->GetServerUserItem(wUserIndex);
					if ( pIServerUserItem == NULL ) 
						continue;

					//设置成绩
					GameEnd.iUserScore=m_iUserWinScore[wUserIndex];

					//返还积分
					GameEnd.iUserReturnScore=m_iUserReturnScore[wUserIndex];

					//设置税收
					if (m_iUserRevenue[wUserIndex]>0) 
						GameEnd.iRevenue=m_iUserRevenue[wUserIndex];
					else if (m_wCurrentBanker!=INVALID_CHAIR) 
						GameEnd.iRevenue=m_iUserRevenue[m_wCurrentBanker];
					else 
						GameEnd.iRevenue=0;

					//发送消息					
					m_pITableFrame->SendTableData(wUserIndex,SUB_S_GAME_END,&GameEnd,sizeof(GameEnd));
					m_pITableFrame->SendLookonData(wUserIndex,SUB_S_GAME_END,&GameEnd,sizeof(GameEnd));
				}
			}

			//扣除分数
			if (m_iUserWinScore[m_wCurrentBanker]<0)
			{
				m_pITableFrame->WriteUserScore(m_wCurrentBanker,m_iUserWinScore[m_wCurrentBanker], m_iUserRevenue[m_wCurrentBanker], enScoreKind_Flee);
			}

			//切换庄家
			ChangeBanker(true);

			return true;
		}
	}

	return false;
}
Пример #12
0
bool Controller::LogicsController::FindAndRemoveChains()
{
	chains.clear();
	vector<Model::BoardElement> elementsInChain;
	bool chainRemoved = false;
	int boardHeight = gameBoardModel->GetBoardHeight();
	int boardWidth = gameBoardModel->GetBoardWidth();
	vector<Model::BoardElement> diamonds = gameBoardModel->GetBoardElements();

	vector<int> elementsInXChain;
	vector<int> elementsInYChain;

	for(int row = 0; row < boardHeight; row++)
	{
		for(int col = 0; col < boardWidth; col++)
		{
			chains.clear();
			Model::BoardElement currentElement = diamonds[(row * boardWidth) + col];

			if(currentElement.type != None)
			{

				// check elements to the right
				for(int i = col + 1; i < boardWidth; i++)
				{
					if(diamonds[(row * boardWidth) + i].type == currentElement.type)
					{
						elementsInXChain.push_back(diamonds[(row * boardWidth) + i].id);
						elementsInChain.push_back(diamonds[(row * boardWidth) + i]);
					}
					else
						break;
				}

				// check elements to the left
				for(int j = col - 1; j >= 0; j--)
				{
					if(diamonds[(row * boardWidth) + j].type == currentElement.type)
					{
						elementsInXChain.push_back(diamonds[((row * boardWidth) + j)].id);
						elementsInChain.push_back(diamonds[(row * boardWidth) + j]);
					}
					else
						break;
				}

				// check if there are more than 3 elements in a row
				if((elementsInXChain.size() + 1) >= 3)
				{
					chains.push_back(elementsInChain);
					Model::BoardElement tmpEl = currentElement;
					tmpEl.type = None;
					gameBoardModel->SetBoardElementByID(tmpEl.id, tmpEl);

					for(unsigned int i = 0; i < elementsInXChain.size(); i++)
					{
						diamonds[elementsInXChain.at(i)].type = None;
						gameBoardModel->SetBoardElementByID(elementsInXChain.at(i), diamonds[elementsInXChain.at(i)]);
					}
					elementsInXChain.clear();
					chainRemoved = true;
				}
				else
				{
					elementsInXChain.clear();
					elementsInChain.clear();
				}

				// check elements down
				for(int ii = row + 1; ii < boardHeight; ii++)
				{
					if(diamonds[(ii * boardWidth) + col].type == currentElement.type)
					{
						elementsInYChain.push_back(diamonds[(ii * boardWidth) + col].id);
						elementsInChain.push_back(diamonds[(ii * boardWidth) + col]);
					}
					else
						break;
				}

				// check elements up
				for(int jj = row - 1; jj >= 0; jj--)
				{
					if(diamonds[(jj * boardWidth) + col].type == currentElement.type)
					{
						elementsInYChain.push_back(diamonds[(jj * boardWidth) + col].id);
						elementsInChain.push_back(diamonds[(jj * boardWidth) + col]);
					}
					else
						break;
				}

				// check if there are more than 3 elements in a column
				if((elementsInYChain.size() + 1) >= 3)
				{
					chains.push_back(elementsInChain);
					Model::BoardElement tmpEl = currentElement;
					tmpEl.type = None;
					gameBoardModel->SetBoardElementByID(tmpEl.id, tmpEl);

					for(unsigned int i = 0; i < elementsInYChain.size(); i++)
					{
						diamonds[elementsInYChain.at(i)].type = None;
						gameBoardModel->SetBoardElementByID(elementsInYChain.at(i), diamonds[elementsInYChain.at(i)]);
					}
					elementsInYChain.clear();
					chainRemoved = true;
				}
				else
				{
					elementsInYChain.clear();
					elementsInChain.clear();
				}

				CalculateScore();

			}
			else
				continue;

		}
	}

	return chainRemoved;
}
Пример #13
0
// aligns the query sequence to the anchor using the Smith Waterman Gotoh algorithm
void CBandedSmithWaterman::Align(Alignment& alignment, const char* s1, const unsigned int s1Length, const char* s2, const unsigned int s2Length, HashRegion& hr) {

	// determine the hash region type
	unsigned int rowOffset;
	unsigned int columnOffset;
	PositionType positionType;

	if(hr.Begin == 0) {
		if(hr.QueryBegin == 0) {
			rowOffset    = 1;
			columnOffset = (mBandwidth / 2) + 1;
			positionType = Position_REF_AND_QUERY_ZERO;
		} else {
			rowOffset    = 1 - hr.QueryBegin;
			columnOffset = (mBandwidth / 2) + 1 + hr.QueryBegin;
			positionType = Position_REF_ZERO;
		}
	} else {
		if(hr.QueryBegin == 0) {
			rowOffset    = 1;
			columnOffset = (mBandwidth / 2) + 1 - hr.Begin;
			positionType = Position_QUERY_ZERO;
		} else {
			rowOffset    = 1 - hr.QueryBegin;
			columnOffset = (mBandwidth / 2) + 1 + hr.QueryBegin - hr.Begin;
			positionType = Position_REF_AND_QUERO_NONZERO;
		}
	}

	// =========================
	// Reinitialize the matrices
	// =========================

	ReinitializeMatrices(positionType, s1Length, s2Length, hr);

	// =======================================
	// Banded Smith-Waterman forward algorithm
	// =======================================

	unsigned int bestColumn	= 0;
	unsigned int bestRow	= 0;
	float bestScore         = FLOAT_NEGATIVE_INFINITY;
	float currentQueryGapScore;

	// rowNum and column indicate the row and column numbers in the Smith-Waterman matrix respectively
	unsigned int rowNum    = hr.QueryBegin;
	unsigned int columnNum = hr.Begin;

	// indicates how many rows including blank elements in the Banded SmithWaterman
	int numBlankElements = (mBandwidth / 2) - columnNum;

	// upper triangle matrix in Banded Smith-Waterman
	for( ; numBlankElements > 0; numBlankElements--, rowNum++){
		// in the upper triangle matrix, we always start at the 0th column
		columnNum = 0;

		// columnEnd indicates how many columns which should be dealt with in the current row
		unsigned int columnEnd = min((mBandwidth - numBlankElements), (s1Length - columnNum + 1) );
		currentQueryGapScore = FLOAT_NEGATIVE_INFINITY;
		for( unsigned int j = 0; j < columnEnd; j++){
			float score = CalculateScore(s1, s2, rowNum, columnNum, currentQueryGapScore, rowOffset, columnOffset);
			UpdateBestScore(bestRow, bestColumn, bestScore, rowNum, columnNum, score);
			columnNum++;
		}

		// replace the columnNum to the middle column in the Smith-Waterman matrix
		columnNum = columnNum - (mBandwidth / 2);
	}

	// complete matrix in Banded Smith-Waterman
	unsigned int completeNum = min((s1Length - columnNum - (mBandwidth / 2)), (s2Length - rowNum));
	for(unsigned int i = 0; i < completeNum; i++, rowNum++){
		columnNum = columnNum - (mBandwidth / 2);

		// there are mBandwidth columns which should be dealt with in each row
		currentQueryGapScore = FLOAT_NEGATIVE_INFINITY;

		for(unsigned int j = 0; j < mBandwidth; j++){
			float score = CalculateScore(s1, s2, rowNum, columnNum, currentQueryGapScore, rowOffset, columnOffset);
			UpdateBestScore(bestRow, bestColumn, bestScore, rowNum, columnNum, score);
			columnNum++;
		}

		// replace the columnNum to the middle column in the Smith-Waterman matrix
		// because mBandwidth is an odd number, everytime the following equation shifts a column (pluses 1).
		columnNum = columnNum - (mBandwidth / 2);
	}

	// lower triangle matrix
	numBlankElements = min(mBandwidth, (s2Length - rowNum));
	columnNum = columnNum - (mBandwidth / 2);
	for(unsigned int i = 0; numBlankElements > 0; i++, rowNum++, numBlankElements--) {

		mBestScores[ mBandwidth - i ] = FLOAT_NEGATIVE_INFINITY;;
		// columnEnd indicates how many columns which should be dealt with
		currentQueryGapScore = FLOAT_NEGATIVE_INFINITY;

		for( unsigned int j = columnNum; j < s1Length; j++){
			float score = CalculateScore(s1, s2, rowNum, columnNum, currentQueryGapScore, rowOffset, columnOffset);
			UpdateBestScore(bestRow, bestColumn, bestScore, rowNum, columnNum, score);
			columnNum++;
		}

		// replace the columnNum to the middle column in the Smith-Waterman matrix
		columnNum = columnNum - mBandwidth + i + 2;
	}

	// =========================================
	// Banded Smith-Waterman backtrace algorithm
	// =========================================

	Traceback(alignment, s1, s2, s2Length, bestRow, bestColumn, rowOffset, columnOffset);
}
// ----------------------------------------------------------------------------
// CSipAcceptContactStrategy::ApplyL
// ----------------------------------------------------------------------------
//
CSIPResponse* CSipAcceptContactStrategy::ApplyL(
    CSIPRequest& aRequest, 
    RArray<TUid>& aUids,
    TBool& aContinueSearch,
    CSIPClientResolver2& aClientResolver2 )
	{
	SIP_CR_LOG("CSipAcceptContactStrategy::ApplyL")
	CSIPResponse* response = NULL;
	// The strategy is applied only for requests that contain Accept-Contact
	if (aRequest.HasHeader(iAcceptContactHeaderName))
        {
        RArray<TSIPClientScore> scores(1);
        CleanupClosePushL(scores);
        RPointerArray<CSIPFeatureSet> requestFeatureSets = 
            CreateFeatureSetsL(aRequest);
        TCleanupItem cleanupItem(DestroyFeatureSets,&requestFeatureSets);
	    CleanupStack::PushL(cleanupItem);
	    for (TInt i=0; i < aUids.Count(); i++)
		    {
		    TUid uid(aUids[i]);
		    MSipClient* client = iSipClients.GetByUID(uid);
		    if (client)
			    {
			    TInt score = CalculateScore(*client,requestFeatureSets);
			    if (score > 0)
			        {
			        TSIPClientScore clientScore(score,uid);
			        // The score is used as a key
			        scores.InsertInSignedKeyOrderAllowRepeatsL(clientScore);
			        }
			    }	
		    }
    	CleanupStack::PopAndDestroy(1); // cleanupItem
    	TInt clientCount = scores.Count();
    	aUids.Reset(); // empties the array
	    if (clientCount > 0)
	        {
	        // The scores are in increasing order. 
	        // The last is the best match. Reverse the order.
	        for (TInt i=scores.Count()-1; i>=0; i--)
	            {
	            // In the resulting array the first is the best match
	            aUids.AppendL(scores[i].iUid);
	            } 
	        if (iNextStrategy && clientCount > 1)
	            {
	            // Apply the next strategy only if 
	            // there are still more than one matching clients.
	            response = iNextStrategy->ApplyL(aRequest,aUids,
	                                             aContinueSearch,
	                                             aClientResolver2);
	            }
	        }
	    else
		    {
		    if ( iNextStrategy2 )
		    	{
		    	response = iNextStrategy2->ApplyL(aRequest,aUids,
		    									  aContinueSearch,
		    									  aClientResolver2);
		    	}
		    else
		    	{
		    	response = CreateResponseL();
		    	}
		    
		    }
		CleanupStack::PopAndDestroy(1); // scores
        }
    else
        {
        if (iNextStrategy)
            {
	        response = iNextStrategy->ApplyL(aRequest,aUids,aContinueSearch,
	        												aClientResolver2);
	        }
        }

    return response;
	}
Пример #15
0
// aligns the query sequence to the anchor using the Smith Waterman Gotoh algorithm
void CBandedSmithWaterman::Align(unsigned int& referenceAl, string& cigarAl, const string& s1, const string& s2, pair< pair<unsigned int, unsigned int>, pair<unsigned int, unsigned int> >& hr) {


	
	unsigned int rowStart = min(hr.first.first, (unsigned int)hr.second.first);
	hr.first.first    -= rowStart;
	hr.second.first   -= rowStart;
	
	//bool isLegalBandWidth = (s2.length() - hr.QueryBegin) > (mBandwidth / 2);
	//     isLegalBandWidth = isLegalBandWidth && ((s1.length() - hr.Begin) > (mBandwidth / 2));



	// check the lengths of the input sequences
	//if( (s1.length() <= 0) || (s2.length() <= 0) || (s1.length() < s2.length()) ) {
	//	printf("ERROR: An unexpected sequence length was encountered during pairwise alignment.\n");
	//	printf("Sequence lengths are listed as following:\n");
	//	printf("1. Reference length: %u\n2. Query length: %u\n", s1.length(), s2.length());
		//printf("3. Hash region in reference:%4u-%4u\n", hr.Begin + rowStart, hr.End);
		//printf("4. Hash region in query:    %4u-%4u\n", hr.QueryBegin + rowStart, hr.QueryEnd);
	//	exit(1);
	//}

	
	// determine the hash region type
	unsigned int rowOffset;
	unsigned int columnOffset;
	PositionType positionType;

	if(hr.first.first == 0) {
		if(hr.second.first == 0) {
			rowOffset    = 1;
			columnOffset = (mBandwidth / 2) + 1;
			positionType = Position_REF_AND_QUERY_ZERO;
		} else {
			rowOffset    = 1 - hr.second.first;
			columnOffset = (mBandwidth / 2) + 1 + hr.second.first;
			positionType = Position_REF_ZERO;
		}
	} else {
		if(hr.second.first == 0) {
			rowOffset    = 1;
			columnOffset = (mBandwidth / 2) + 1 - hr.first.first;
			positionType = Position_QUERY_ZERO;
		} else {
			rowOffset    = 1 - hr.second.first;
			columnOffset = (mBandwidth / 2) + 1 + hr.second.first - hr.first.first;
			positionType = Position_REF_AND_QUERO_NONZERO;
		}
	}

	// =========================
	// Reinitialize the matrices
	// =========================
	
	ReinitializeMatrices(positionType, s1.length(), s2.length(), hr);

	// =======================================
	// Banded Smith-Waterman forward algorithm
	// =======================================

	unsigned int bestColumn	= 0;
	unsigned int bestRow	= 0;
	float bestScore         = FLOAT_NEGATIVE_INFINITY;
	float currentQueryGapScore;

	// rowNum and column indicate the row and column numbers in the Smith-Waterman matrix respectively
	unsigned int rowNum    = hr.second.first;
	unsigned int columnNum = hr.first.first;

	// indicates how many rows including blank elements in the Banded SmithWaterman
	int numBlankElements = (mBandwidth / 2) - columnNum;

	//cout << numBlankElements << endl;
	// upper triangle matrix in Banded Smith-Waterman
	for( ; numBlankElements > 0; numBlankElements--, rowNum++){
		// in the upper triangle matrix, we always start at the 0th column
		columnNum = 0;

		// columnEnd indicates how many columns which should be dealt with in the current row
		unsigned int columnEnd = min((mBandwidth - numBlankElements), ((unsigned int) s1.length() - columnNum + 1) );
		currentQueryGapScore = FLOAT_NEGATIVE_INFINITY;
		for( unsigned int j = 0; j < columnEnd; j++){
			float score = CalculateScore(s1, s2, rowNum, columnNum, currentQueryGapScore, rowOffset, columnOffset);
			//cout << s1[columnNum] << s2[rowNum] << score << endl;
			UpdateBestScore(bestRow, bestColumn, bestScore, rowNum, columnNum, score);
			columnNum++;
		}

		// replace the columnNum to the middle column in the Smith-Waterman matrix
		columnNum = columnNum - (mBandwidth / 2);
	}
	// complete matrix in Banded Smith-Waterman
	unsigned int completeNum = min((s1.length() - columnNum - (mBandwidth / 2)), (s2.length() - rowNum));
	//cout << completeNum << endl;
	for(unsigned int i = 0; i < completeNum; i++, rowNum++){
		columnNum = columnNum - (mBandwidth / 2);

		// there are mBandwidth columns which should be dealt with in each row
		currentQueryGapScore = FLOAT_NEGATIVE_INFINITY;

		for(unsigned int j = 0; j < mBandwidth; j++){
			float score = CalculateScore(s1, s2, rowNum, columnNum, currentQueryGapScore, rowOffset, columnOffset);
			UpdateBestScore(bestRow, bestColumn, bestScore, rowNum, columnNum, score);
			//cout << s1[columnNum] << s2[rowNum] << score << endl;
			columnNum++;
		}

		// replace the columnNum to the middle column in the Smith-Waterman matrix
		// because mBandwidth is an odd number, everytime the following equation shifts a column (pluses 1).
		columnNum = columnNum - (mBandwidth / 2);
	}
	
	// lower triangle matrix
	numBlankElements = min(mBandwidth, ((unsigned int) s2.length() - rowNum));
	columnNum = columnNum - (mBandwidth / 2);
	for(unsigned int i = 0; numBlankElements > 0; i++, rowNum++, numBlankElements--) {

		mBestScores[ mBandwidth - i ] = FLOAT_NEGATIVE_INFINITY;;
		// columnEnd indicates how many columns which should be dealt with
		currentQueryGapScore = FLOAT_NEGATIVE_INFINITY;

		for( unsigned int j = columnNum; j < s1.length(); j++){
			float score = CalculateScore(s1, s2, rowNum, columnNum, currentQueryGapScore, rowOffset, columnOffset);
			UpdateBestScore(bestRow, bestColumn, bestScore, rowNum, columnNum, score);
			//cout << s1[columnNum] << s2[rowNum] << score << endl;
			columnNum++;
		}

		// replace the columnNum to the middle column in the Smith-Waterman matrix
		columnNum = columnNum - mBandwidth + i + 2;
	}

	// =========================================
	// Banded Smith-Waterman backtrace algorithm
	// =========================================

	Traceback(referenceAl, cigarAl, s1, s2, bestRow, bestColumn, rowOffset, columnOffset);

}
Пример #16
0
void Game::Process()
{
   Input& input = Input::GetInstance();
   OpenGL& opengl = OpenGL::GetInstance();
   
   // Check keys
   if (input.QueryAction(Input::PAUSE)) {
      if (state == gsPaused) {
         // Unpause the game
         state = gsInGame;
      }
      else if (state == gsInGame) {
         // Pause the game
         state = gsPaused;
         ship.ThrustOff();
      }
      
      input.ResetAction(Input::PAUSE);
   }

   if (input.QueryResetAction(Input::SCREENSHOT))
      opengl.DeferScreenShot();

   // Do no more game processing in the paused state
   if (state == gsPaused)
      return;

   if (input.QueryAction(Input::THRUST)
       && !fuelmeter.OutOfFuel() && state == gsInGame) {
      // Thrusting
      ship.ThrustOn();
      ship.Thrust(SHIP_SPEED);
      fuelmeter.BurnFuel();
   }
   else
      ship.ThrustOff();
   
   if (input.QueryAction(Input::RIGHT) && state == gsInGame) {
      // Turn clockwise
      ship.Turn(TURN_ANGLE);
   }
   else if (input.QueryAction(Input::LEFT) && state == gsInGame) {
      // Turn anti-clockwise
      ship.Turn(-TURN_ANGLE);
   }
   
   if (input.QueryAction(Input::SKIP) && state == gsExplode) {
      // The player got bored watching the explosion
      EnterDeathWait(lives == 0 ? DEATH_TIMEOUT : 1);
   }

   if (input.QueryAction(Input::ABORT) && state == gsInGame) {
      // Quit to main menu
      ExplodeShip();
      lives = 0;
   }

   if (input.QueryAction(Input::DEBUG)) {
      // Toggle debug mode
      bDebugMode = !bDebugMode;
      input.ResetAction(Input::DEBUG);
   }

   // Move only if not in game over
   if (state == gsInGame || state == gsExplode) {
      ship.ApplyGravity(flGravity);

      // Move the ship (and exhaust and explosion)
      ship.Move();
   }

   ship.ProcessEffects(state == gsPaused, state == gsExplode);

   // Move mines
   for (MineListIt it = mines.begin(); it != mines.end(); ++it)
      (*it).Move();

   // Move or fire missiles
   for (MissileListIt it = missiles.begin(); it != missiles.end(); ++it)
      (*it).Move(ship);
   
   // Calculate view adjusts
   ship.CentreInViewport();

   // Check for collisions with surface
   int padIndex;
   if (surface.CheckCollisions(ship, pads, &padIndex)) {
      bool landed = false;
      if (state == gsInGame) {
         if (padIndex != -1) {
            // Hit a landing pad
            int dAngle = ((int)ship.GetAngle()) % 360;
            if ((dAngle >= 330 || dAngle <= 30)
                && speedmeter.SafeLandingSpeed() && nKeysRemaining == 0) {
               // Landed safely
               state = gsLevelComplete;
               CalculateScore(padIndex);
               countdown_timeout = 70;
               landed = true;
            }
         }
         if (!landed) {
            // Crash landed
            ExplodeShip();
            ship.Bounce();
         }
      }
      else if (state == gsExplode)
         EnterDeathWait();
   }
   
   // Check for collisions with asteroids
   LineSegment l1, l2;
   for (AsteroidListIt it = asteroids_.begin();
        it != asteroids_.end(); ++it) {
      const Asteroid& a = *it;
      
      if (a.ObjectInScreen(&viewport)) {
         if (a.CheckCollision(ship)) {
            // Crashed
            if (state == gsInGame) {
               // Destroy the ship
               ExplodeShip();
               ship.Bounce();
            }
            else if (state == gsExplode)
               EnterDeathWait();
         }
      }
   }

   // Check for collision with gateways
   for (ElectricGateListIt it = gateways.begin(); it != gateways.end(); ++it) {
      if ((*it).CheckCollision(ship)) {
         if (state == gsInGame) {
            // Destroy the ship
            ExplodeShip();
            ship.Bounce();
         }
         else if (state == gsExplode) {
            // Destroy the ship anyway
            EnterDeathWait();
         }
      }
   }

   // Check for collisions with mines
   for (MineListIt it = mines.begin(); it != mines.end(); ++it) {
      if ((*it).CheckCollision(ship)) {
         if (state == gsInGame) {
            // Destroy the ship
            ExplodeShip();
            ship.Bounce();
         }
         else if (state == gsExplode)
            EnterDeathWait();
      }
   }

   // Check for collisons with missiles
   for (MissileListIt it = missiles.begin(); it != missiles.end(); ++it) {
      if ((*it).CheckCollison(ship)) {
         if (state == gsInGame) {
            // Destroy the ship 
            ExplodeShip();
            ship.Bounce();
         }
         else if (state == gsExplode)
            EnterDeathWait();
      }
   }

   // See if the player collected a key
   for (KeyListIt it = keys.begin(); it != keys.end(); ++it) {
      if((*it).CheckCollision(ship)) {
         nKeysRemaining--;
         (*it).Collected();
         objgrid.UnlockSpace((*it).GetX(), (*it).GetY());

         collectSound.Play();
      }
   }

   // Entry / exit states
   if (state == gsDeathWait) {
      if (--death_timeout == 0) {
         // Fade out
         if (lives == 0  || (lives == 1 && life_alpha < LIFE_ALPHA_BASE))
            state = gsFadeToDeath;
         else if (lives > 0) {
            if (life_alpha < LIFE_ALPHA_BASE) {
               life_alpha = LIFE_ALPHA_BASE + 1.0f;
               lives--;
            }

            state = gsFadeToRestart;
         }

         fade.BeginFadeOut();
      }
   }
   else if (state == gsGameOver) {
      if (--death_timeout == 0) {
         // Fade out
         state = gsFadeToDeath;
         fade.BeginFadeOut();
      }
   }
   else if (state == gsFadeIn) {
      // Fade in
      if (fade.Process())
         state = gsInGame;
   }
   else if (state == gsFadeToRestart) {
      // Fade out
      if (fade.Process()) {
         // Restart the level
         StartLevel();
         opengl.SkipDisplay();
      }
   }
   else if (state == gsFadeToDeath) {
      if (fade.Process()) {
         // Return to main menu
         ScreenManager& sm = ScreenManager::GetInstance();
         HighScores* hs = static_cast<HighScores*>(sm.GetScreenById("HIGH SCORES"));
         hs->CheckScore(score);
      }
   }
   else if (state == gsLevelComplete) {
      // Decrease the displayed score
      if (countdown_timeout > 0)
         countdown_timeout--;
      else if (levelcomp_timeout > 0) {
         if (--levelcomp_timeout == 0) {
            level++;
            state = gsFadeToRestart;
            fade.BeginFadeOut();
         }
      }
      else {
         int dec = level * 2;
         
         // Decrease the score
         newscore -= dec;
         score += dec;
         
         if (score > nextnewlife) {
            lives++;
            nextnewlife *= 2;
         }
         
         if (newscore < 0) {
            // Move to the next level (after a 1s pause)
            score -= -newscore;
            levelcomp_timeout = 40;
         }
      }
   }
   
   // Decrease level text timeout
   if (leveltext_timeout > 0)
      leveltext_timeout--;

   // Spin the ship if we're exploding
   if (state == gsExplode)
      ship.Turn(DEATH_SPIN_RATE);
}