Esempio n. 1
0
float SquareMatrix::CalcFutureScore2( WordsBitmap const &bitmap, size_t startPos, size_t endPos ) const
{
  const size_t notInGap= numeric_limits<size_t>::max();
  float futureScore = 0.0f;
  size_t startGap = bitmap.GetFirstGapPos();
  if (startGap == NOT_FOUND) return futureScore; // everything filled

  // start loop at first gap
  size_t startLoop = startGap+1;
  if (startPos == startGap) { // unless covered by phrase
    startGap = notInGap;
    startLoop = endPos+1; // -> postpone start
  }

  size_t lastCovered = bitmap.GetLastPos();
  if (endPos > lastCovered || lastCovered == NOT_FOUND) lastCovered = endPos;

  for(size_t currPos = startLoop; currPos <= lastCovered ; currPos++) {
    // start of a new gap?
    if(startGap == notInGap && bitmap.GetValue(currPos) == false && (currPos < startPos || currPos > endPos)) {
      startGap = currPos;
    }
    // end of a gap?
    else if(startGap != notInGap && (bitmap.GetValue(currPos) == true || (startPos <= currPos && currPos <= endPos))) {
      futureScore += GetScore(startGap, currPos - 1);
      startGap = notInGap;
    }
  }
  // coverage ending with gap?
  if (lastCovered != bitmap.GetSize() - 1) {
    futureScore += GetScore(lastCovered+1, bitmap.GetSize() - 1);
  }

  return futureScore;
}
Esempio n. 2
0
    int FlyGrid::GetScore(EnPlayerColor color, int point, int left_jump, int left_fly) {
        if (Color() != color)
            return Grid::GetScore(color, point, left_jump, left_fly);

        if (0 != point) {
            auto next = GetNextGrid();
            return next->GetScore(color, point - point / abs(point), 0, 0) + Config::GetInstance().AICfg.Move;
        }

        int ret = 0;
        if (NULL != place_plane){
            if (place_plane->Color() == color)
                ret += Config::GetInstance().AICfg.KillFriend;
            else
                ret += Config::GetInstance().AICfg.KillEnermy;
        }

        if (left_fly > 0){
            ret += Config::GetInstance().AICfg.Fly;
            auto jump = GetJumpGrid();
            if (jump)
                ret += jump->GetScore(color, point, left_jump, left_fly - 1);
        }

        return point;
    }
Esempio n. 3
0
/**
 * Get the best move from the minimizing player's point of view
 *
 * @param Board b the current board that is to be analysed
 *
 * @return std::pair<int, std::pair<unsigned int, unsigned int> > a pair of
 * score and the starting move that leads to that score (the move is itself a
 * pair made of the row and column of the move)
 */
std::pair<int, std::pair<unsigned int, unsigned int> > AiPlayer::Min(Board b){
    int best_score = 1;
    int score;
    std::pair<unsigned int, unsigned int> best_move;

    std::vector< std::pair<unsigned int, unsigned int> > moves = b.GetPossibleMoves();
    std::vector< std::pair<unsigned int, unsigned int> >::iterator it;

    // iterate through the child nodes
    for(it = moves.begin(); it != moves.end(); it++){
        b.Update(opponent_id, it->first, it->second);
        int winner = b.GetWinner();

        if(winner != 0){ //the game is over
            score = GetScore(winner);
        }
        else{ // the game continues and it's the maximizing player's turn
            score = Max(b).first;
        }

        // undo the move so we get the same board that was passed as argument
        b.Reset(it->first, it->second);

        // if the score from the current visited children is better, we
        // update both the score and the move to get to the first child
        if(score < best_score){
            best_score = score;
            best_move = std::make_pair(it->first, it->second);
        }
    }

    // after visiting all children return the best score and the move
    // that made the score possible
    return std::make_pair(best_score, best_move);
}
Esempio n. 4
0
	bool			IAndroid::SaveScoreToBanker(INT64 nScore)
	{
		if (US_FREE != m_wStaus)
		{
			CString szMessage;
			szMessage.Format("Robot[%d] request sit up", m_dwUserID);
			CTraceService::TraceString(szMessage,
				TraceLevel_Normal);
			m_ClientSocket->SendData(MDM_GR_USER,SUB_GR_USER_STANDUP_REQ);
		}

		CMD_TOOLBOX_BankTask tb;
		memset(&tb, 0, sizeof(CMD_TOOLBOX_BankTask));

		INT64 nCurScore = GetScore();
		INT64 nLeftScore = nCurScore - nScore;
		nLeftScore = nLeftScore / 100 * 100;
		nScore = nCurScore - nLeftScore;
		
		tb.lMoneyNumber	= nScore;
		tb.lBankTask		= 1;
		CopyMemory(tb.szPassword, m_Password.GetBuffer(), sizeof(tb.szPassword));

		m_ClientSocket->SendData(MDM_TOOLBOX, SUB_TOOLBOX_BANKOPERATING, &tb, sizeof(tb));
		return true;
	}
const std::vector<std::vector<int> > ribi::PreDickAdvocaTorMainDialog::CreateTeamScores(const int seed)
{
  const std::vector<std::string> team_names { GetTeamNames() };
  const std::size_t sz { team_names.size() };
  std::vector<std::vector<int> > v(sz,std::vector<int>(sz,0));
  std::srand(seed);


  const std::size_t dutch_index
    = std::distance(
      team_names.begin(),
      std::find(team_names.begin(),team_names.end(),std::string("Netherlands"))
    );
  assert(dutch_index < sz);
  assert(GetTeamNames()[dutch_index] == "Netherlands");
  for (std::size_t y = 0; y!=sz; ++y)
  {
    for (std::size_t x = 0; x!=sz; ++x)
    {
      v[y][x] = GetScore();
    }
    //Add known score for The Netherlands
    v[y][dutch_index] = 0;
  }
  //Add known scores for The Netherlands
  v[dutch_index] = std::vector<int>(sz,10);

  return v;
}
Esempio n. 6
0
File: snake.cpp Progetto: qhw/Snake
void DrawUI(HWND hWnd)
{
	if(gameover)
		KillTimer(hWnd,100);
	HDC hdc,hMemDC;
	hdc = GetDC(hWnd);
	hbr = (HBRUSH)GetStockObject(BLACK_BRUSH);
			
			for(i = 0; i < 40; i++)
				for(j =0; j <32; j++)
				{
					rt.left = i * 16;
					rt.top = 24 + j *16;
					switch(Matrix[i][j])
					{
						case 0:
							{
								rt.right = rt.left + 16;
								rt.bottom = rt.top + 16 ;
								FillRect(hdc,&rt,hbr);
							}
							break;
						case 1:
							{
								hBmp  =   LoadBitmap(hInst, MAKEINTRESOURCE(IDB_BITMAP1));
								hMemDC  =  CreateCompatibleDC(hdc);   
								hBmpOld  =   (HBITMAP)SelectObject(hMemDC,hBmp);
								BitBlt(hdc,rt.left,rt.top,16,16,hMemDC,0,0,SRCCOPY);
								SelectObject(hMemDC, hBmpOld);   
								DeleteObject(hBmp);   
								DeleteObject(hMemDC); 
							}
							break;
						case 2:
							{
								hBmp  =   LoadBitmap(hInst, MAKEINTRESOURCE(IDB_BITMAP2));
								hMemDC  =  CreateCompatibleDC(hdc);   
								hBmpOld  =   (HBITMAP)SelectObject(hMemDC,hBmp);
								BitBlt(hdc,rt.left,rt.top,16,16,hMemDC,0,0,SRCCOPY);
								SelectObject(hMemDC, hBmpOld);   
								DeleteObject(hBmp);   
								DeleteObject(hMemDC); 
							}
							break;
					}

				}
				char str[20];
		        memset(str,0,20);
				GetScore();
			level = score / 200 + 1;
			speed = 500 / level;
			wsprintf(str,"%d",level);
			SetWindowText(hedit[0],str);
			wsprintf(str,"%d",score);
			SetWindowText(hedit[2],str);
			ReleaseDC(hWnd,hdc);
			if(gameover)
				SetTimer(hWnd,100,speed,NULL);
}
Esempio n. 7
0
int
Platform::Update ()
{
  if (isAlive ())
  {
    GameObject::Update ();
    //Performing boundry checking
    if (x > g_Game.GetScreen_W () - boundX)
      x = g_Game.GetScreen_W () - boundX;
    else if (x < boundX)
      x = boundX;
    //Updating of animation exists
    if (animation) animation->Animate ();
  }

  if (!GetLives ())
  {
    PlayingState* playing_state = dynamic_cast<PlayingState*> (g_GamePtr->GetState ());
    playing_state->SetChangingStateFlag (true);
    char buffer[BUFSIZ];
    ACE_OS::memset (&buffer, 0, sizeof (buffer));
    char* username = buffer;
#ifdef _MSC_VER
    DWORD buffer_size = sizeof (buffer);
    if (!GetUserName (buffer, &buffer_size))
      ACE_DEBUG ((LM_ERROR,
                  ACE_TEXT ("failed to GetUserName: %d, continuing\n"),
                  GetLastError ()));
#else
    username = ACE_OS::getenv ("USER");
#endif
    playing_state->PushScore (username, GetScore ());
  }
  return 0;
}
Esempio n. 8
0
bool HighScore::operator>=( const HighScore& other ) const
{
	/* Make sure we treat AAAA as higher than AAA, even though the score
 	 * is the same. */
	if( PREFSMAN->m_bPercentageScoring )
	{
		if( GetPercentDP() != other.GetPercentDP() )
			return GetPercentDP() >= other.GetPercentDP();
	}
	else
	{
		if( GetScore() != other.GetScore() )
			return GetScore() >= other.GetScore();
	}

	return GetGrade() >= other.GetGrade();
}
Esempio n. 9
0
static void ReadAllScores(double scores[],int nJudges)
{
  int i;

  for(i=0;i<nJudges;i++){
    scores[i]=GetScore(i);
  }
}
Esempio n. 10
0
    int StraightGrid::GetScore(EnPlayerColor color, int point, int left_jump, int left_fly) {
        int ret = Config::GetInstance().AICfg.Move;
        if (0 != point) {
            auto next = GetNextGrid();
            ret += next->GetScore(color, point - point / abs(point), 0, 0);
        }

        return ret;
    }
Esempio n. 11
0
bool RBTourTracker::Completed(int c)
{
	RBCourseEntry *course = GetCourseData(c);
	
	if(GetScore(c) > course->m_completionScore)
		return false;
	else
		return true;
	
}
Esempio n. 12
0
//	Determine the optimal scoring category of a given roll.
Category GetSuggestion(const Roll& roll)
{
	//	Initialize maxes.
	unsigned int maxScore = GetScore(Category::Ones, roll);
	Category maxScoreCategory = Category::Ones;
	
	//	Loop through the category list, checking for higher score values.
	unsigned int scoreForThisCategory;
	for (unsigned int curCategory = Category::Twos; curCategory < Category::MAXVALUE; ++curCategory)
	{
		scoreForThisCategory = GetScore(static_cast<Category>(curCategory), roll);
		if (scoreForThisCategory >= maxScore)
		{
			maxScore = scoreForThisCategory;
			maxScoreCategory = static_cast<Category>(curCategory);
		}
	}

	return maxScoreCategory;
}
Esempio n. 13
0
void Enemy::Damage( int damage, bool magic, Player* source ) {
    _hp -= std::max( damage, 0 );
    if ( damage > 0 )
        PlaySoundRandom( Lib::SOUND_ENEMY_HIT );

    if ( _hp <= 0 && !IsDestroyed() ) {
        PlaySoundRandom( _destroySound );
        if ( source && GetScore() > 0 )
            source->AddScore( GetScore() );
        if ( _explodeOnDestroy )
            Explosion();
        else
            Explosion( 0, 4, true, Vec2f( GetPosition() ) );
        OnDestroy( damage >= Player::BOMB_DAMAGE );
        Destroy();
    } else if ( !IsDestroyed() ) {
        if ( damage > 0 )
            PlaySoundRandom( Lib::SOUND_ENEMY_HIT );
        _damaged = damage >= Player::BOMB_DAMAGE ? 25 : 1;
    }
}
Esempio n. 14
0
	void BroadcastReceiver::WriteRecentEndpoints(const std::string& filename, uint8_t threshold) const
	{
		std::ofstream outFile;
		if(filename.compare("") == 0)
			outFile.open(mRecentFilename, std::ios::trunc);
		else
			outFile.open(filename, std::ios::trunc);

		if(!outFile.is_open()) {
			Trace(ZONE_ERROR, "Open file to write recent endpoints failed\n");
			return;
		}
		// write to file
		for(auto it = mIpTable.begin(); it != mIpTable.end(); it++) {
			const auto currentEndpoint = it->second;
			if(currentEndpoint.GetScore() >= threshold) {
				//TODO refactor this but then we have to change the CLI implementation
				outFile << (int)(currentEndpoint.GetScore()) << ' ' << std::hex << currentEndpoint.GetIp() << ' ' << std::dec << currentEndpoint.GetPort() << ' ' << currentEndpoint.GetDeviceId() << '\n';
			}
		}
		outFile.close();
	}
Esempio n. 15
0
float SquareMatrix::CalcFutureScore( WordsBitmap const &bitmap ) const
{
  const size_t notInGap= numeric_limits<size_t>::max();
  size_t startGap = notInGap;
  float futureScore = 0.0f;
  for(size_t currPos = 0 ; currPos < bitmap.GetSize() ; currPos++) {
    // start of a new gap?
    if(bitmap.GetValue(currPos) == false && startGap == notInGap) {
      startGap = currPos;
    }
    // end of a gap?
    else if(bitmap.GetValue(currPos) == true && startGap != notInGap) {
      futureScore += GetScore(startGap, currPos - 1);
      startGap = notInGap;
    }
  }
  // coverage ending with gap?
  if (startGap != notInGap) {
    futureScore += GetScore(startGap, bitmap.GetSize() - 1);
  }

  return futureScore;
}
Esempio n. 16
0
void SearchDialog::AddAnimeToList(int anime_id) {
  auto anime_item = AnimeDatabase.FindItem(anime_id);

  if (anime_item) {
    int i = list_.GetItemCount();
    list_.InsertItem(i, anime_item->IsInList() ? 1 : 0,
                     StatusToIcon(anime_item->GetAiringStatus()), 0, nullptr,
                     anime_item->GetTitle().c_str(),
                     static_cast<LPARAM>(anime_item->GetId()));
    list_.SetItem(i, 1, anime::TranslateType(anime_item->GetType()).c_str());
    list_.SetItem(i, 2, anime::TranslateNumber(anime_item->GetEpisodeCount()).c_str());
    list_.SetItem(i, 3, anime::TranslateScore(anime_item->GetScore()).c_str());
    list_.SetItem(i, 4, anime::TranslateDateToSeasonString(anime_item->GetDateStart()).c_str());
  }
}
Esempio n. 17
0
/* comefrom: SpecialInit Simulate */
CityEvaluation(void)
{
  EvalValid = 0;
  if (TotalPop) {
    GetAssValue();
    DoPopNum();
    DoProblems();
    GetScore();
    DoVotes();
    ChangeEval();
  } else {
    EvalInit();
    ChangeEval();
  }
  EvalValid = 1;
}
Esempio n. 18
0
	bool			IAndroid::GetScoreFromBanker(INT64 nScore)
	{
		CMD_TOOLBOX_BankTask tb;
		memset(&tb, 0, sizeof(CMD_TOOLBOX_BankTask));

		INT64 nCurScore = GetScore();
		INT64 nAfterScore = nCurScore + nScore;
		nAfterScore = nAfterScore / 100 * 100;
		nScore = nAfterScore - nCurScore;

		tb.lMoneyNumber	= nScore;
		tb.lBankTask		= 2;
		CopyMemory(tb.szPassword, m_Password.GetBuffer(), sizeof(tb.szPassword));

		m_ClientSocket->SendData(MDM_TOOLBOX, SUB_TOOLBOX_BANKOPERATING, &tb, sizeof(tb));

		return true;
	}
//
// AICTPGameGameMode::RegisterActorDeath
//
void AICTPGameGameMode::RegisterActorDeath( float DamageAmount, AActor* DamagedActor, AActor* DamageCauser )
{
	OnActorDeath.Broadcast( DamageAmount, DamagedActor, DamageCauser );

	auto DamagerPlayerController = Cast<ARobotPlayerController>( DamageCauser->GetInstigatorController() );
	if( DamagerPlayerController == nullptr )
	{
		return;
	}

	auto ScoreComponent = DamagedActor->FindComponentByClass<UScoreComponent>();
	if( ScoreComponent == nullptr )
	{
		return;
	}

	DamagerPlayerController->AddScore( ScoreComponent->GetScore() );
}
Esempio n. 20
0
int Platform::Update(){
    if(isAlive()){
        GameObject::Update();
        //Performing boundry checking
        if( x > g_Game.GetScreen_W() - boundX)
            x = g_Game.GetScreen_W() - boundX;
        else if ( x < boundX)
            x = boundX ;
        //Updating of animation exists
        if(animation) animation->Animate();
    }
    
    if(!GetLives()){
        PlayingState* playing_state = dynamic_cast<PlayingState*>(g_GamePtr->GetState());
        playing_state->SetChangingStateFlag(true);
        playing_state->PushScore(getenv("USER"), GetScore());
    }
    return 0;
}
Esempio n. 21
0
int main(int argc, const char * argv[]) {
    // insert code here...
    std::cout << "We are the champion!\n";

    InputLoader loader;
    loader.LoadServersFromFile("dc.in");

    vector<UnavailableSlot> unSlots = loader.unavailableSlots;

    // sort by rowsIndex, then by slotIndex
    //std::sort(unSlots.begin(), unSlots.end());

    DataCenter dc;
    dc.SetUnavailableSlots(unSlots);

    //shared_ptr<ServerDistributer> distributer(new RandomServerDistributer);
    shared_ptr<ServerDistributer> distributer(new CapacityPerSizeDistributer);


    distributer->Reset(dc, loader.servers);
    distributer->Distribute(dc, loader.servers);

    int score = GetScore(loader.servers);
    cout <<"score is :" << score << endl;
	OutputWriter::WriteOutput(loader.servers, R"(C:\Users\U0137572\test\hashcode2015\Debug\dc.out)");

    //int bestScore = 0;
    //for(int i = 0; i< 10000; ++i)
    //{
    //    distributer->Reset(dc, loader.servers);
    //    distributer->Distribute(dc, loader.servers);
    //    int score = GetScore(loader.servers);
    //    cout <<"score is :" << score << endl;
    //    bestScore = max(bestScore, score);
    //}

    //cout << "best score is :" << bestScore << endl;


    return 0;
}
Esempio n. 22
0
// operates in terms of GetScore() (which is recursive for factories)
const UnitDef* CUnitTable::GetUnitByScore(int builderID, UnitCategory cat) {
	if (cat == CAT_LAST) {
		return NULL;
	}

	const UnitDef* builderDef  = ai->cb->GetUnitDef(builderID);
	const UnitDef* tempUnitDef = NULL;

	const std::vector<int>& defs = categoryData.GetDefsForUnitCat(cat);
	float tempScore = 0.0f;
	float bestScore = 0.0f;

	// if we are a builder on side i, then templist must have
	// at least i + 1 elements (templist[0], ..., templist[i])
	// but if a mod is not symmetric (eg. no builders for side
	// 1) this assumption fails; enabling this breaks PURE 0.6
	// however

	// iterate over all types in defs (eg. Core groundDefenses)
	for (unsigned int i = 0; i != defs.size(); i++) {
		int tempUnitDefID = defs[i];

		// if our builder can build the i-th unit
		if (CanBuildUnit(builderDef->id, tempUnitDefID)) {
			// get the unit's heuristic score (based on current income)
			tempScore = GetScore(unitTypes[tempUnitDefID].def, cat);

			if (tempScore > bestScore) {
				bestScore = tempScore;
				tempUnitDef = unitTypes[tempUnitDefID].def;
			}
		}
	}


	// if we didn't find a unit to build with score > 0 (ie.
	// if builder has no build-option matching this category)
	// then return NULL instead of first option on build menu
	// (to prevent radar farms and other bizarro side-effects)
	return ((bestScore > 0.0f)? tempUnitDef: NULL);
}
Esempio n. 23
0
// Display the computer's name and card backs
void Computer::Show() const
{

	Console::ForegroundColor(GetColor());
	Console::SetCursorPosition(0, GetLine() - 1);
	cout << "\b\b" << Player::GetName();
	Console::SetCursorPosition(30, Player::GetLine() - 1);
	cout << "Score: " << GetScore() << endl;

	bool temp = false;
	if (IsCheatActive(0))
	{
		int intArr[50] = { 1, };
		temp = intArr[rand() % 50];
	}

	for (int i = 0; i < Player::GetNumCards(); i++)
	{
		Console::ForegroundColor(Black);
		Console::BackgroundColor(White);

		if (temp || IsCheatActive(4))
		{
			Card temp;
			GetCard(i, temp);
			cout << temp;
		}
		else
			cout << "\xB2\xB2\xB2";
		Console::BackgroundColor(Black);
		cout << " ";
	}



	cout << '\t';
	Console::ResetColor();


}
Esempio n. 24
0
void PLAYER::CollectPowerUp(enum POWERUP_TYPE type, int count)
{
	char* msg = new char[64];
	switch(type)
	{
	case pwrHealth:
		SetHealth(GetHealth() + count);
		sprintf(msg, "Health collected (+%u)\0", count);
		break;
	case pwrAmmo:
		SetAmmo(GetAmmo() + count);
		sprintf(msg, "Ammo collected (+%u)\0", count);
		break;
	case pwrScore:
		SetScore(GetScore() + count);
		sprintf(msg, "Score collected (+%u)\0", count);
		break;
	}

			
	gui->LogOnScreen(msg);
}
Esempio n. 25
0
// Add score
void AddScore( int val )
{
	SetScore( GetScore() + val );
}
double ImageSharpnessScorer::GetScore(ImgBuffer & buffer)
{
	buffer_.Copy(buffer);
	return GetScore();

}
Esempio n. 27
0
void ScoreKeeperMAX2::AddScore( TapNoteScore score )
{
	int &iScore = m_pPlayerStageStats->iScore;
	int &iCurMaxScore = m_pPlayerStageStats->iCurMaxScore;
/*
  Regular scoring:

  Let p = score multiplier (Perfect = 10, Great = 5, other = 0)
  
  Note on NONSTOP Mode scoring

  Let p = score multiplier (Marvelous = 10, Perfect = 9, Great = 5, other = 0)

  N = total number of steps and freeze steps
  S = The sum of all integers from 1 to N (the total number of steps/freeze steps) 
  n = number of the current step or freeze step (varies from 1 to N)
  B = Base value of the song (1,000,000 X the number of feet difficulty) - All edit data is rated as 5 feet
  So, the score for one step is: 
  one_step_score = p * (B/S) * n 
  
  *IMPORTANT* : Double steps (U+L, D+R, etc.) count as two steps instead of one *for your combo count only*, 
  so if you get a double L+R on the 112th step of a song, you score is calculated for only one step, not two, 
  as the combo counter might otherwise imply.  
	
  Now, through simple algebraic manipulation:
  S = 1+...+N = (1+N)*N/2 (1 through N added together) 

  Okay, time for an example.  Suppose we wanted to calculate the step score of a "Great" on the 57th step of 
  a 441 step, 8-foot difficulty song (I'm just making this one up): 
  
  S = (1 + 441)*441 / 2
  = 194,222 / 2
  = 97,461
  StepScore = p * (B/S) * n
  = 5 * (8,000,000 / 97,461) * 57
  = 5 * (82) * 57 (The 82 is rounded down from 82.08411...)
  = 23,370
  
  Remember this is just the score for the step, not the cumulative score up to the 57th step. Also, please note that 
  I am currently checking into rounding errors with the system and if there are any, how they are resolved in the system. 
  
  Note: if you got all Perfect on this song, you would get (p=10)*B, which is 80,000,000. In fact, the maximum possible 
  score for any song is the number of feet difficulty X 10,000,000. 
*/
	int p = 0;	// score multiplier 

	switch( score )
	{
	case TNS_MARVELOUS:	p = 10;		break;
	case TNS_PERFECT:	p = GAMESTATE->ShowMarvelous()? 9:10; break;
	case TNS_GREAT:		p = 5;		break;
	default:			p = 0;		break;
	}

	m_iTapNotesHit++;

	const int N = m_iNumTapsAndHolds;
	const int sum = (N * (N + 1)) / 2;
	const int B = m_iMaxPossiblePoints/10;

	// Don't use a multiplier if the player has failed
	if( m_pPlayerStageStats->bFailedEarlier )
	{
		iScore += p;
		// make score evenly divisible by 5
		// only update this on the next step, to make it less *obvious*
		/* Round to the nearest 5, instead of always rounding down, so a base score
		 * of 9 will round to 10, not 5. */
		if (p > 0)
			iScore = ((iScore+2) / 5) * 5;
	}
	else
	{
		iScore += GetScore(p, B, sum, m_iTapNotesHit);
		const int &iCurrentCombo = m_pPlayerStageStats->iCurCombo;
		m_pPlayerStageStats->iBonus += m_ComboBonusFactor[score] * iCurrentCombo;
	}

	/* Subtract the maximum this step could have been worth from the bonus. */
	m_iPointBonus -= GetScore(10, B, sum, m_iTapNotesHit);
	/* And add the maximum this step could have been worth to the max score up to now. */
	iCurMaxScore += GetScore(10, B, sum, m_iTapNotesHit);

	if ( m_iTapNotesHit == m_iNumTapsAndHolds && score >= TNS_PERFECT )
	{
		if (!m_pPlayerStageStats->bFailedEarlier)
			iScore += m_iPointBonus;
		if ( m_bIsLastSongInCourse )
		{
			iScore += 100000000 - m_iMaxScoreSoFar;
			iCurMaxScore += 100000000 - m_iMaxScoreSoFar;

			/* If we're in Endless mode, we'll come around here again, so reset
			 * the bonus counter. */
			m_iMaxScoreSoFar = 0;
		}
		iCurMaxScore += m_iPointBonus;
	}

	ASSERT( iScore >= 0 );

	/* Undo rounding from the last tap, and re-round. */
	iScore += m_iScoreRemainder;
	m_iScoreRemainder = (iScore % m_iRoundTo);
	iScore = iScore - m_iScoreRemainder;
	
	ASSERT( iScore >= 0 );

	// LOG->Trace( "score: %i", iScore );
}
Esempio n. 28
0
void ScoreKeeperNormal::AddScoreInternal( TapNoteScore score )
{
	if( m_UseInternalScoring )
	{
		
		unsigned int &iScore = m_pPlayerStageStats->m_iScore;
		unsigned int &iCurMaxScore = m_pPlayerStageStats->m_iCurMaxScore;

		// See Aaron In Japan for more details about the scoring formulas.
		// Note: this assumes no custom scoring systems are in use.
		int p = 0;	// score multiplier

		switch( score )
		{
		case TNS_W1:	p = 10;	break;
		case TNS_W2:	p = GAMESTATE->ShowW1()? 9:10; break;
		case TNS_W3:	p = 5;	break;
		default:		p = 0;	break;
		}

		m_iTapNotesHit++;

		const int64_t N = uint64_t(m_iNumTapsAndHolds);
		const int64_t sum = (N * (N + 1)) / 2;
		const int Z = m_iMaxPossiblePoints/10;

		// Don't use a multiplier if the player has failed
		if( m_pPlayerStageStats->m_bFailed )
		{
			iScore += p;
			// make score evenly divisible by 5
			// only update this on the next step, to make it less *obvious*
			/* Round to the nearest 5, instead of always rounding down, so a base score
			* of 9 will round to 10, not 5. */
			if (p > 0)
			iScore = ((iScore+2) / 5) * 5;
		}
		else
		{
			iScore += GetScore(p, Z, sum, m_iTapNotesHit);
			const int &iCurrentCombo = m_pPlayerStageStats->m_iCurCombo;
			iScore += m_ComboBonusFactor[score] * iCurrentCombo;
		}

		// Subtract the maximum this step could have been worth from the bonus.
		m_iPointBonus -= GetScore(10, Z, sum, m_iTapNotesHit);
		// And add the maximum this step could have been worth to the max score up to now.
		iCurMaxScore += GetScore(10, Z, sum, m_iTapNotesHit);

		if ( m_iTapNotesHit == m_iNumTapsAndHolds && score >= TNS_W2 )
		{
			if( !m_pPlayerStageStats->m_bFailed )
				iScore += m_iPointBonus;
			if ( m_bIsLastSongInCourse )
			{
				iScore += 100000000 - m_iMaxScoreSoFar;
				iCurMaxScore += 100000000 - m_iMaxScoreSoFar;

				/* If we're in Endless mode, we'll come around here again, so reset
				* the bonus counter. */
				m_iMaxScoreSoFar = 0;
			}
			iCurMaxScore += m_iPointBonus;
		}

		// Undo rounding from the last tap, and re-round.
		iScore += m_iScoreRemainder;
		m_iScoreRemainder = (iScore % m_iRoundTo);
		iScore = iScore - m_iScoreRemainder;

		// LOG->Trace( "score: %i", iScore );
	}
}
Esempio n. 29
0
float CUnitTable::GetScore(const UnitDef* udef, UnitCategory cat) {
	const int m = (ai->uh->AllUnitsByType[udef->id]).size();
	const int n = udef->maxThisUnit;

	if (m >= n) {
		// if we've hit the build-limit for this
		// type of unit, make sure GetUnitByScore()
		// won't pick it for construction anyway
		return 0.0f;
	}

	if (udef->minWaterDepth > 0) {
		// we can't swim yet
		return 0.0f;
	}

	const int frame = ai->cb->GetCurrentFrame();
	const float cost =
		((udef->metalCost * METAL2ENERGY) +
		udef->energyCost) + 0.1f;
	const float currentIncome =
		INCOMEMULTIPLIER *
		(ai->cb->GetEnergyIncome() + (ai->cb->GetMetalIncome() * METAL2ENERGY)) +
		frame / 2;
	const float Hitpoints = udef->health;
	const float buildTime = udef->buildTime + 0.1f;
	const float RandNum = ai->math->RandNormal(4, 3, 1) + 1;

	float benefit = 0.0f;
	float aoe = 0.0f;
	float dps = 0.0f;
	int unitcounter = 0;
	bool candevelop = false;

	switch (cat) {
		case CAT_ENERGY: {
			// KLOOTNOTE: factor build-time into this as well?
			// (so benefit values generally lie closer together)
			float baseBenefit = udef->energyMake - udef->energyUpkeep;

			if (udef->windGenerator > 0.0f) {
				const float minWind = ai->cb->GetMinWind();
				const float maxWind = ai->cb->GetMaxWind();
				const float avgWind = (minWind + maxWind) * 0.5f;
				const float avgEffi = std::min(avgWind / udef->windGenerator, 1.0f);

				if (avgEffi >= 0.4f) {
					baseBenefit += avgWind;
				}
			}
			if (udef->tidalGenerator > 0.0f) {
				baseBenefit += ai->cb->GetTidalStrength();
			}

			// filter geothermals
			if (udef->needGeo) {
				baseBenefit = 0.0f;
			}

			// KLOOTNOTE: dividing by cost here as well means
			// benefit is inversely proportional to square of
			// cost, so expensive generators are quadratically
			// less likely to be built if original calculation
			// of score is used
			// benefit /= cost;
			benefit = (baseBenefit / buildTime) * float((rand() % 2) + 1);
		} break;

		case CAT_MEX: {
			benefit = pow(udef->extractsMetal, 4.0f);
		} break;
		case CAT_MMAKER: {
			// benefit = ((udef->metalMake - udef->metalUpkeep) / udef->energyUpkeep) + 0.01f;
			benefit = (udef->metalMake - udef->metalUpkeep) / (udef->energyUpkeep + 0.01f);
		} break;

		case CAT_G_ATTACK: {
			dps = GetCurrentDamageScore(udef);
			aoe = ((udef->weapons.size())? ((udef->weapons.front()).def)->areaOfEffect: 0.0f);

			if (udef->canfly && !udef->hoverAttack) {
				// TODO: improve to set reload-time to the bomber's
				// turnspeed vs. movespeed (eg. time taken for a run)
				dps /= 6;
			}

			benefit =
				pow((aoe + 80), 1.5f) *
				pow(GetMaxRange(udef) + 200, 1.5f) *
				pow(dps, 1.0f) *
				pow(udef->speed + 40, 1.0f) *
				pow(Hitpoints, 1.0f) *
				pow(RandNum, 2.5f) *
				pow(cost, -0.5f);

			if (udef->canfly || udef->canhover) {
				// general hack: reduce feasibility of aircraft for 20 mins
				// and that of hovercraft permanently, should mostly prefer
				// real L2 units to hovers
				benefit = (udef->canfly && frame >= (30 * 60 * 20))? benefit: benefit * 0.01f;
			}
		} break;

		case CAT_DEFENCE: {
			aoe = ((udef->weapons.size())? ((udef->weapons.front()).def)->areaOfEffect: 0.0f);
			benefit =
				pow((aoe + 80), 1.5f) *
				pow(GetMaxRange(udef), 2.0f) *
				pow(GetCurrentDamageScore(udef), 1.5f) *
				pow(Hitpoints, 0.5f) *
				pow(RandNum, 2.5f) *
				pow(cost, -1.0f);
		} break;

		case CAT_BUILDER: {
			for (unsigned int i = 0; i != unitTypes[udef->id].canBuildList.size(); i++) {
				if (unitTypes[unitTypes[udef->id].canBuildList[i]].category == CAT_FACTORY) {
					candevelop = true;
				}
			}

			// builder units that cannot construct any
			// factories are worthless, prevent them
			// from being chosen via GetUnitByScore()
			// (they might have other uses though, eg.
			// nano-towers)
			if (!candevelop) {
				benefit = 0.0f;
			} else {
				benefit =
					pow(udef->buildSpeed, 1.0f) *
					pow(udef->speed, 0.5f) *
					pow(Hitpoints, 0.3f) *
					pow(RandNum, 0.4f);
			}
		} break;

		case CAT_FACTORY: {
			// benefit of a factory is dependant on the kind of
			// offensive units it can build, but EE-hubs are only
			// capable of building other buildings
			for (unsigned int i = 0; i != unitTypes[udef->id].canBuildList.size(); i++) {
				const int          buildOpt    = unitTypes[udef->id].canBuildList[i];
				const UnitCategory buildOptCat = unitTypes[buildOpt].category;

				if (buildOptCat == CAT_G_ATTACK || buildOptCat == CAT_FACTORY) {
					if (unitTypes[buildOpt].def != udef) {
						// KLOOTNOTE: guard against infinite recursion (BuildTowers in
						// PURE trigger this since they are able to build themselves)
						benefit += GetScore(unitTypes[buildOpt].def, buildOptCat);
						unitcounter++;
					}
				}
			}

			if (unitcounter > 0) {
				benefit /= (unitcounter * pow(float(ai->uh->AllUnitsByType[udef->id].size() + 1), 3.0f));
				benefit /= ((m > 0)? (m * 2.0f): 1.0f);
			} else {
				benefit = 0.0f;
			}
		} break;

		case CAT_MSTOR: {
			benefit = pow((udef->metalStorage), 1.0f) * pow(Hitpoints, 1.0f);
		} break;
		case CAT_ESTOR: {
			benefit = pow((udef->energyStorage), 1.0f) * pow(Hitpoints, 1.0f);
		} break;
		case CAT_NUKE: {
			// KLOOTNOTE: should factor damage into this as well
			float metalCost = udef->stockpileWeaponDef->metalcost;
			float energyCost = udef->stockpileWeaponDef->energycost;
			float supplyCost = udef->stockpileWeaponDef->supplycost;
			float denom = metalCost + energyCost + supplyCost + 1.0f;
			float range = udef->stockpileWeaponDef->range;
			benefit = (udef->stockpileWeaponDef->areaOfEffect + range) / denom;
		} break;
		/*
		case CAT_ANTINUKE: {
			benefit = udef->stockpileWeaponDef->coverageRange;
		} break;
		case CAT_SHIELD: {
			benefit = udef->shieldWeaponDef->shieldRadius;
		} break;
		*/
		default:
			benefit = 0.0f;
	}

	benefit *= unitTypes[udef->id].costMultiplier;
	// return (benefit / (currentIncome + cost));
	// return ((benefit / cost) * currentIncome);
	return ((currentIncome / cost) * benefit);
}
Esempio n. 30
0
void nGame::Process()
{
	static float absoluteTime = 0.0f;
	static float absoluteTime2 = 0.0f;

	// Check for pause key
	if(nGetInstance()->GetInput()->GetKeyboard()->GetNewKey(DIK_PAUSE) || nGetInstance()->GetInput()->GetKeyboard()->GetNewKey(DIK_P))
		SetPause(!GetPause());

	// Don't process further if paused
	if(m_Pause)
		return;

	absoluteTime += nGetInstance()->GetElapsedTime();
	absoluteTime2 += nGetInstance()->GetElapsedTime();

	// Create enemy missle if enough time passed
	if(absoluteTime > m_MissleTime)
	{
		// Reset the timer
		absoluteTime = 0.0f;
		
		if(m_MissleTime > 1.0f)
			m_MissleTime -= (double)nGetInstance()->GetElapsedTime() / 4.0f;

		// Create a missle at a random top position going to a random bottom position
		AddMissle(nVector2(randf(0.0f,nGetInstance()->GetGraphics()->GetDisplaySize().cx),0.0f),nVector2(randf(0.0f,nGetInstance()->GetGraphics()->GetDisplaySize().cx),nGetInstance()->GetGraphics()->GetDisplaySize().cy),1.0f,80.0f,GAME_ENEMY_COLOR,false,true);
	}

	// Create child enemy missle if enough time passed
	if(absoluteTime2 > 100.0f)
	{
		// Reset the timer
		absoluteTime2 = 0.0f;

		if(m_Missles.size())
		{
			// Create a missle at a random trail of a nother missle
			unsigned long count = 1 + rand() % 3;

			Missle* missle = &m_Missles[rand() % m_Missles.size()];

			// Find a live enemy missle
			while(missle->frendly || missle->dead > 0.0f)
				missle = &m_Missles[rand() % m_Missles.size()];

			nVector2 dir = missle->position - missle->source;
			float length = dir.Length();
			dir.Normalize();

			nVector2 source = missle->source + dir * randf(0.0f,length);

			for(unsigned long i = 0; i < count; i++)
				AddMissle(source,nVector2(randf(0.0f,nGetInstance()->GetGraphics()->GetDisplaySize().cx),nGetInstance()->GetGraphics()->GetDisplaySize().cy),1.0f,80.0f,GAME_ENEMY_COLOR,false,true);
		}
	}

	// Check left missle silo launch
	if(nGetInstance()->GetInput()->GetMouse()->GetNewButton(nMouse::ButtonLeft))
		FireSilo(m_Silos[0],nGetInstance()->GetInput()->GetMouse()->GetPosition(),20.0f,80.0f,true);
	
	// Check right missle silo launch
	if(nGetInstance()->GetInput()->GetMouse()->GetButton(nMouse::ButtonRight))
	{
		// Get a random vector in a sphere domain
		nVector2 miss(randf(-1.0f,1.0f),randf(-1.0f,1.0f));
		miss.Normalize();
		miss *= randf(0.0f,50.0f);

		FireSilo(m_Silos[1],nGetInstance()->GetInput()->GetMouse()->GetPosition() + miss,30.0f,20.0f,false);
	}

	// Remove silo fire time
	for(unsigned long i = 0; i < m_Silos.size(); i++)
	{
		Silo* silo = &m_Silos[i];

		// Remove some fire time
		silo->time -= nGetInstance()->GetElapsedTime();

		// Check if all/too much fire time was removed
		if(silo->time < 0.0f)
			silo->time = 0.0f;
	}

	// Move missles and remove dead ones
	for(unsigned long i = 0; i < m_Missles.size(); i++)
	{
		Missle* missle = &m_Missles[i];

		if(missle->position == missle->destination || missle->dead > 0.0f)
		{
			if(missle->position == missle->destination && !missle->frendly && missle->dead == 0.0f)
			{
				// Players base got hit	
				SetHealth(GetHealth() - 10);

				// Check if player dead
				if(!GetHealth())
				{
					// Game over
					AddHiScore(m_Score);
					RestartGame();

					return;
				}
			}

			if(missle->dead > 10.0f)
			{
				// Remove missle
				RemoveMissle(i--);
				continue;
			}

			if(missle->dead == 0.0f)
			{
				// Explode
				AddExplosion(missle->position,missle->blast,4.0f,nColor(1.0f,0.1f,1.0f));
			}

			missle->dead += nGetInstance()->GetElapsedTime();
			continue;
		}

		if(missle->target > 0.0f)
			missle->target -= nGetInstance()->GetElapsedTime() / 10.0f;
		else if(missle->target < 0.0f)
			missle->target = 0.0f;

		nVector2 velocity = missle->destination - missle->source;
		velocity.Normalize();

		velocity *= missle->speed * nGetInstance()->GetElapsedTime();

		if(velocity.x > 0.0f && missle->position.x + velocity.x > missle->destination.x)
			missle->position.x = missle->destination.x;
		else if(velocity.x < 0.0f && missle->position.x + velocity.x < missle->destination.x)
			missle->position.x = missle->destination.x;
		else
			missle->position.x += velocity.x;

		if(velocity.y > 0.0f && missle->position.y + velocity.y > missle->destination.y)
			missle->position.y = missle->destination.y;
		else if(velocity.y < 0.0f && missle->position.y + velocity.y < missle->destination.y)
			missle->position.y = missle->destination.y;
		else
			missle->position.y += velocity.y;
	}

	// Expand explosions and remove dead ones
	for(unsigned long i = 0; i < m_Explosions.size(); i++)
	{
		Explosion* explosion = &m_Explosions[i];

		if(explosion->size == explosion->power)
		{
			// Remove it
			RemoveExplosion(i--);
			continue;
		}

		float expansion = explosion->speed * nGetInstance()->GetElapsedTime();

		if(explosion->size + expansion > explosion->power)
			explosion->size = explosion->power;
		else
			explosion->size += expansion;

		// Check if the explosion destroyed any missles
		for(unsigned long j = 0; j < m_Missles.size(); j++)
		{
			Missle* missle = &m_Missles[j];

			// Skip frendly or already dead missles
			if(missle->frendly || missle->dead > 0.0f)
				continue;

			nVector2 dir = missle->position - explosion->position;

			unsigned long points = 0;

			if(dir.Length() < explosion->size)
			{
				// Set death time
				missle->dead += nGetInstance()->GetElapsedTime();

				// Create some particles
				for(unsigned long k = 0; k < 50; k++)
				{
					// Get a random vector in a sphere domain
					nVector2 velocity(randf(-1.0f,1.0f),randf(-1.0f,1.0f));
					velocity.Normalize();
					velocity *= randf(0.0f,5.0f);

					AddParticle(missle->position,velocity,nVector2(0.0f,0.1f),10.0f,GAME_COLOR_PARTICLES);
				}

				// Add player points
				points++;
			}

			// Add score
			if(points > 1)
				SetScore(GetScore() + points + points / 2);
			else
				SetScore(GetScore() + points);
		}
	}

	// Move and remove particles
	for(unsigned long i = 0; i < m_Particles.size(); i++)
	{
		Particle* particle = &m_Particles[i];

		// Remove the particle if it's dead
		if(particle->lived >= particle->life)
		{
			// Remove it
			RemoveParticle(i--);
			continue;
		}

		particle->lived += nGetInstance()->GetElapsedTime();

		particle->velocity += particle->force * nGetInstance()->GetElapsedTime();
		particle->position += particle->velocity * nGetInstance()->GetElapsedTime();
	}
}