Пример #1
0
int KThiefSkill::Cast_Redress(KPlayer * pLaucherPlayer, KPlayer * pTargetPlayer)
{
	_ASSERT(pLaucherPlayer && pTargetPlayer);
	int nTotalMoney = pTargetPlayer->m_ItemList.GetMoney(room_equipment);
	int nLevel1 = Npc[pLaucherPlayer->m_nIndex].m_Level;
	int nLevel2 = Npc[pTargetPlayer->m_nIndex].m_Level;
	int nOdds = (int) (10 - ((int)abs(nLevel1 - nLevel2)) * 0.1);
	int nRand = GetRandomNumber(1, 100);
	char szMsg[100];
	if (nTotalMoney <= 0 ||	nRand < nOdds)
	{
		int nThiefMoney = nTotalMoney * m_nThiefPercent / 100 ;
		pTargetPlayer->Pay(nThiefMoney);
		
		sprintf(szMsg, "%s 从你身上偷到%d两银子捐给前线!", Npc[pLaucherPlayer->m_nIndex].Name, nThiefMoney );
		KPlayerChat::SendSystemInfo(1, pTargetPlayer->GetPlayerIndex(), "被偷成功 ", (char *) szMsg, strlen(szMsg) );
		
		sprintf(szMsg, "你成功的从%s 那里偷到%d两银子捐给前线!", Npc[pTargetPlayer->m_nIndex].Name, nThiefMoney);
		KPlayerChat::SendSystemInfo(1, pLaucherPlayer->GetPlayerIndex(), "偷窃成功 ", (char *) szMsg, strlen(szMsg) );
		return TRUE;
	}
	
	sprintf(szMsg, "%s 试图偷你的钱,但未成功!", Npc[pLaucherPlayer->m_nIndex].Name);
	KPlayerChat::SendSystemInfo(1, pTargetPlayer->GetPlayerIndex(), "被偷未遂", (char *) szMsg, strlen(szMsg) );
	
	sprintf(szMsg, "你偷%s 失败!", Npc[pTargetPlayer->m_nIndex].Name);
	KPlayerChat::SendSystemInfo(1, pLaucherPlayer->GetPlayerIndex(), "偷窃未遂", (char *) szMsg, strlen(szMsg) );
	return TRUE;
}
Пример #2
0
/*!
 * \brief create a single forest at the point specified
 * \param pos Position on the map to start from
 * \param size Radius of the forest to paint.
 */
static void
CreateForest(UInt32 pos, UInt16 size)
{
	UInt16 x, y, i, j, s;

	x = (UInt16)(pos % getMapWidth());
	y = (UInt16)(pos / getMapWidth());
	zone_lock(lz_world);
	zone_lock(lz_flags);
	i = x - size > 0 ? x - size : 0;
	j = y - size > 0 ? y - size : 0;

	for (; i <= x + size; i++) {
		for (j = y - size; j <= y + size; j++) {
			if (i >= getMapWidth() ||
			    j >= getMapHeight())
				continue;
			if (getWorld(WORLDPOS(i, j)) != Z_DIRT)
				continue;
			s = ((y > j) ? (y - j) : (j - y)) +
			    ((x > i) ? (x - i) : (i - x));
			if (GetRandomNumber(s) < 2) {
				/*!
				 * \todo count_trees or count_real_trees
				 */
				setWorldAndFlag(WORLDPOS(i, j), Z_REALTREE, 0);
				vgame.BuildCount[bc_count_trees]++;
			}
		}
		j = y - size > 0 ? y - size : 0;
	}
	zone_unlock(lz_flags);
	zone_unlock(lz_world);
}
Пример #3
0
// Add by flying on May.30.2003
// Try to get a "Gold Item" if possible.
BOOL KItemGenerator::GetGoldItemByRandom(IN int nCondition, OUT KItem * pItem)
{
	BOOL bResult = FALSE;
	const KBASICPROP_EQUIPMENT_GOLD* pArray[MAX_ITEM];
	int i = 0;
	int j = 0;
	int nIndex = 0;

	::memset(pArray, 0, sizeof(KBASICPROP_EQUIPMENT_GOLD *) * MAX_ITEM);

	for (i = 0; i < MAX_ITEM; i++)
	{
		const KBASICPROP_EQUIPMENT_GOLD* pTemp = m_BPTLib.GetGoldItemRecord(i);
		if (pTemp == 0)
			break;
		if (pTemp->m_nRarity < nCondition)
			pArray[j] = pTemp;
	}

	if (j == 0)
		goto Exit0;			 
	nIndex = GetRandomNumber(0, j);	
	*pItem = *pArray[nIndex];
Exit0:
	return FALSE;
}
Пример #4
0
void CMusikPlayer::_ChooseRandomSongs(int nSongsToAdd,CMusikSongArray &arrSongs)
{
	if(nSongsToAdd <= 0)
		return;
	wxString sQuerySongs = wxString::Format(wxT(" select autodj_songs.songid from autodj_songs ") 
		wxT("where lastplayed = '' or lastplayed < julianday('now','-%d hours');"),(int)wxGetApp().Prefs.nAutoDjDoNotPlaySongPlayedTheLastNHours);	 //(int) cast to make gcc 2.95 happy
	wxArrayInt arrSongIds;
	wxGetApp().Library.Query(sQuerySongs,arrSongIds);
	if(arrSongIds.GetCount() < (size_t)nSongsToAdd )
	{  // not enough songs found, so relax the DoNotPlaySongPlayedTheLastNHours condition to 2 hours
		sQuerySongs = wxString::Format(wxT(" select autodj_songs.songid from autodj_songs ") 
			wxT("where lastplayed = '' or lastplayed < julianday('now','-2 hours');"));	 //(int) cast to make gcc 2.95 happy
		wxGetApp().Library.Query(sQuerySongs,arrSongIds);
	}
	while (arrSongIds.GetCount() && (arrSongs.GetCount() < (size_t)nSongsToAdd))
	{
		int r = (size_t) (arrSongIds.GetCount() * (GetRandomNumber() / (RandomMax + 1.0)));  // random range  [0 , arrSongIds.GetCount()-1] 
		CMusikSong song;
		if(wxGetApp().Library.GetSongFromSongid(arrSongIds[r],&song))
		{
			if(song.MetaData.Filename.FileExists())
			{
				arrSongs.Add(song);
			}
			arrSongIds.RemoveAt(r); //remove index, so songid cannot be chosen again.
		}
	} 
}
Пример #5
0
void CMusikPlayer::_ChooseRandomAlbumSongs(int nAlbumsToAdd,CMusikSongArray &arrAlbumSongs)
{
	if(nAlbumsToAdd <= 0)
		return;
	int nMaxRepeatCount = 30;
	int hours = wxGetApp().Prefs.nAutoDjDoNotPlaySongPlayedTheLastNHours;
	char * count_query = sqlite_mprintf("select count(*) from autodj_albums where most_lastplayed = '' or most_lastplayed < julianday('now','-%d hours');",hours);
	int albums_count = wxGetApp().Library.QueryCount(count_query);
	sqlite_freemem( count_query );
	wxArrayString arrAlbums;
	while ( (nMaxRepeatCount > 0) && ( arrAlbums.GetCount() < (size_t)nAlbumsToAdd ))
	{
		int r = (size_t) (albums_count * (GetRandomNumber() / (RandomMax + 1.0)));  // random range  [0 , albums_count-1] 
		wxString sQueryRandomAlbum = wxString::Format(wxT("select album||'|'||artist from autodj_albums where most_lastplayed = '' or most_lastplayed < julianday('now','-%d hours') limit 1 offset %d;") 
											,nMaxRepeatCount < 5 ? 1 : (int)wxGetApp().Prefs.nAutoDjDoNotPlaySongPlayedTheLastNHours,r);

		wxArrayString newAlbums;
		wxGetApp().Library.Query(sQueryRandomAlbum,newAlbums,false);
		bool repeat = false;
		if(newAlbums.GetCount() > 0)
		{
			//--- check for repeats ---//
			for ( size_t j = 0;  j < arrAlbums.GetCount(); j++ )
			{
				if ( newAlbums[0] == arrAlbums[j] )
				{
					repeat = true; 
					break;
				}
			}
		}
		else
			repeat = true;

		if(!repeat)
			arrAlbums.Add(newAlbums[0]);
		else
			nMaxRepeatCount--;

	} 

	
	
	for(size_t i = 0;i < arrAlbums.GetCount();i++)
	{
		wxString sQuery;
		sQuery.Alloc( 80);
		arrAlbums[i].Replace( wxT( "'" ), wxT( "''" ));
		wxArrayString album_artist;
		DelimitStr(arrAlbums[i],wxT("|"),album_artist);
		sQuery+=wxT("album='");
		sQuery+=album_artist[0];
		sQuery+=wxT("' and artist='");
		sQuery+=album_artist[1];
		sQuery+=wxT("' order by tracknum");
		wxGetApp().Library.QuerySongsWhere(sQuery ,arrAlbumSongs,false,false);	
	}
	

}
Пример #6
0
bool CAttachmentProcessor::GenerateSavePath(const TUploadConf *pUploadConf,const string& strSubfix,vector<string>& vecDbPath,vector<string>& vecFilePath)
{
	if(NULL == pUploadConf)
		return false;
	const vector<TSaveGroupConf>& vecSaveGroupConf = pUploadConf->vecSaveGroupConf;
	if(vecSaveGroupConf.empty())
		return false;

	int size = vecSaveGroupConf.size();
	int index = GetRandomNumber(0, size);
	const TSaveGroupConf& saveGroupConf = vecSaveGroupConf.at(index);

	string timeStr = GetTimeStr();
	string uniqueStr = GetUniqueStr();
	string namePrefix = pUploadConf->strSaveNamePrefix;
	namePrefix = (namePrefix != "") ? (namePrefix+"_") : "";
	string strSubDir = pUploadConf->strSaveSubDir;
	strSubDir = (strSubDir!="")?(strSubDir+"/"):"";

	string saveDir = saveGroupConf.strSaveNodePath + "/" + strSubDir + timeStr;
	Mkdir(saveDir);

	string filePath = saveDir + "/" + namePrefix + uniqueStr + "." + strSubfix;
	string dbPath = saveGroupConf.strGroupName + "/" + strSubDir + timeStr + + "/" + namePrefix + uniqueStr + "." + strSubfix;
	vecDbPath.push_back(dbPath);
	vecFilePath.push_back(filePath);
	return true;
}
Пример #7
0
void CMusikPlayer::_ChooseRandomSongs(int nSongsToAdd,MusikSongIdArray &arrSongs)
{
	if(nSongsToAdd <= 0)
		return;
    MusikSongIdArray arrSongsToPlay;
    GetSongsToPlay(arrSongsToPlay);

    wxString sQueryBase(wxT("select autodj_songs.songid from autodj_songs "));
    wxString sWhereNotSongsToPlay;
    wxString sQuerySum(wxT(" select (sum(duration)/60000) from autodj_songs"));
    if(arrSongsToPlay.GetCount())
    {
        sWhereNotSongsToPlay << wxT(" autodj_songs.songid not in(")
                  << arrSongsToPlay.AsCommaSeparatedString()
                  << wxT(") ");
        sQuerySum << wxT(" where ") << sWhereNotSongsToPlay;

    }
    sQuerySum <<  wxT(";"); 


    int nTotalPlayTimeMinutes = wxGetApp().Library.QueryCount(ConvToUTF8(sQuerySum));
    // we dont want to play songs which have been played the last n minutes.
    // n is a user config option
    // but sometimes our possible songs  have a total playing time which is smaller than n
    // in this case we use the the half of the total playing time of the songlist instead of n

    int nDoNotPlaySongPlayedTheLastNMinutes = wxMin(nTotalPlayTimeMinutes / 2 , (int)wxGetApp().Prefs.nAutoDjDoNotPlaySongPlayedTheLastNHours * 60);

    wxString sWhereNotPlayedTheLastNMinutes;
    sWhereNotPlayedTheLastNMinutes << wxT(" lastplayed = '' or lastplayed < julianday('now','-") << nDoNotPlaySongPlayedTheLastNMinutes << wxT(" minutes') ") ;
    wxString sQuerySongs;
    sQuerySongs << sQueryBase << wxT("where ");
    if(sWhereNotSongsToPlay.IsEmpty())
    {
        sQuerySongs << sWhereNotPlayedTheLastNMinutes;
    }
    else
    {
       sQuerySongs << wxT("(") << sWhereNotSongsToPlay << wxT(") and (") << sWhereNotPlayedTheLastNMinutes << wxT(")");
    }
    sQuerySongs <<  wxT(";"); 

	wxArrayInt arrSongIds;
	wxGetApp().Library.Query(sQuerySongs,arrSongIds);
	while (arrSongIds.GetCount() && (arrSongs.GetCount() < (size_t)nSongsToAdd))
	{
		int r = (size_t) (arrSongIds.GetCount() * (GetRandomNumber() / (RandomMax + 1.0)));  // random range  [0 , arrSongIds.GetCount()-1] 
		CMusikSong song;
		if(wxGetApp().Library.GetSongFromSongid(arrSongIds[r],&song))
		{
			if(song.MetaData.Filename.FileExists())
			{
				arrSongs.Add(MusikSongId(arrSongIds[r]));
			}
			arrSongIds.RemoveAt(r); //remove index, so songid cannot be chosen again.
		}
	} 
}
Пример #8
0
eItem ItemSpawner::GetItemTypeToSpawn()
{
	int numItemTypes = (int)m_vpItemTypeList.size();

	int randomNum = GetRandomNumber(0, numItemTypes-1);

	return m_vpItemTypeList[randomNum];
}
Пример #9
0
eEnemyType EnemySpawner::GetEnemyTypeToSpawn()
{
	int numEnemyTypes = (int)m_vpEnemyTypeList.size();

	int randomNum = GetRandomNumber(0, numEnemyTypes-1);

	return m_vpEnemyTypeList[randomNum];
}
Пример #10
0
void
DoRandomDisaster(void)
{
	UInt32 randomTile;
	Int16 i, type, random;
	UInt16 x, y;
	UInt8 disaster_level;

	disaster_level = getDisasterLevel();
	/* for those who can't handle the game (truth?) */
	if (disaster_level == 0)
		return;

	zone_lock(lz_world);
	zone_lock(lz_flags);

	for (i = 0; i < 100; i++) { /* 100 tries to hit a useful tile */
		randomTile = GetRandomNumber(MapMul());
		type = getWorld(randomTile);
		if (type != Z_DIRT &&
			type != Z_REALWATER &&
			type != Z_CRATER) {
			x = (UInt16)(randomTile % getMapWidth());
			y = (UInt16)(randomTile / getMapHeight());
			/* TODO: should depend on difficulty */
			random = (Int16)GetRandomNumber(1000 / disaster_level);
			WriteLog("Random Disaster: %d\n", (int)random);
			if (random < 10 && vgame.BuildCount[bc_fire] == 0) {
				DoSpecificDisaster(diFireOutbreak, x, y);
			} else if (random < 15 &&
			    game.objects[obj_monster].active == 0) {
				DoSpecificDisaster(diMonster, x, y);
			} else if (random < 17 &&
			    game.objects[obj_dragon].active == 0) {
				DoSpecificDisaster(diDragon, x, y);
			} else if (random < 19) {
				DoSpecificDisaster(diMeteor, x, y);
			}
			/* only one chance for disaster per turn */
			break;
		}
	}
	zone_unlock(lz_flags);
	zone_unlock(lz_world);
}
Пример #11
0
void FBullCowGame::SetHiddenWord(int32 NumberOfLetters) 
/* 
Sets the hidden word as a random word from the dictionary of isograms with that word length
*/
{
	int32 Number = GetRandomNumber(MasterWordList[NumberOfLetters].WordList.size());
	MyHiddenWord = MasterWordList[NumberOfLetters].WordList[Number];
	return;
}; // SetHiddenWord
Пример #12
0
Int16
MeteorDisaster(UInt16 x, UInt16 y)
{
	Int16 k;

	k = (Int16)GetRandomNumber(3) + 1;
	CreateMeteor(x, y, k);
	return (1);
}
Пример #13
0
/*!
 * \brief Check if a monster is surrounded by defensive units.
 * \param i index of monster to check.
 */
static void
MonsterCheckSurrounded(UInt16 i)
{
	if (GetDefenceValue(game.objects[i].x, game.objects[i].y) >= 11 ||
		GetRandomNumber(50) < 2) {
		game.objects[i].active = 0; /* kill the sucker */
		WriteLog("killing a monster\n");
	}
}
Пример #14
0
size_t CMusikPlayer::GetShuffledSong()
{
	size_t r = 0;

	if( m_Playlist.GetCount() == 0 )
		return 0;

	
	bool repeat = false;
	int nMaxRepeatCount = 30;
	do {
		repeat = false;
		
		r = (size_t) (m_Playlist.GetCount() * (GetRandomNumber() / (RandomMax + 1.0)));  // random range  [0 , m_Playlist.GetCount()-1] 

		if(m_arrHistory.GetCount() == m_Playlist.GetCount())
		{	// history is as large as the playlist
			// clear half of the history 
			for(size_t i = 0; i < m_arrHistory.GetCount()/2;i++)
			{
				m_arrHistory.RemoveAt(0);
			}
			break;
		}
		if(nMaxRepeatCount--) // only check for repeats nMaxRepeatCount times, to prevent endless do loop
		{
			if(m_Playlist.Item( r ).Song()->MetaData.Filename.FileExists())
			{
				//--- check for repeats ---//
				for ( size_t j = 0;  j < m_arrHistory.GetCount(); j++ )
				{
					if ( r == (size_t)m_arrHistory[j] )
					{
						repeat = true; 
						break;
					}
				}
			}
			else
			{
				repeat = true; 
			}
		}
	} while ( repeat );

	if( m_arrHistory.GetCount() >= (size_t)wxGetApp().Prefs.nMaxShuffleHistory )
	{
	//--- rotate history ---//
		m_arrHistory.RemoveAt(0);
	}
	m_arrHistory.Add(r);
	wxLogDebug(wxT("songindex %d\n"),r);
	return r;
}
Пример #15
0
void GenerateNextArrival()
{
    double       x, log(), ceil();
    struct event *evptr;

    /* x is uniform on [0,2*AveTimeBetweenMsgs ] 
       having mean of AveTimeBetweenMsgs */
    x = AveTimeBetweenMsgs *GetRandomNumber()*2; 
    if ( TraceLevel >= 4)
        printf("\tGenerateNextArrival: Creating new arrival at %f from now\n",  x);

    evptr = (struct event *)malloc(sizeof(struct event));
    evptr->evtime =  CurrentSimTime + x;
    evptr->evtype =  FROM_LAYER5;
    if (Bidirectional && (GetRandomNumber()>0.5) )
        evptr->eventity = BEntity;
    else
        evptr->eventity = AEntity;
    InsertEvent(evptr);
} 
Пример #16
0
void
Algorithm<T>::ExtractParents()
{
	m_parentsIndex.clear();
	std::vector<double> lVector = GetRandomNumber(m_countOfChromosomes);
	for (int i = 0; i < m_countOfChromosomes; i++) {
		if (lVector[i] < CROSSOVER_RATE) {
			m_parentsIndex.push_back(i);
		}
	}
}
Пример #17
0
void CPuzzle::Setup()
/***********************************************************************/
{
	int i, iPieces, iPiecesInPlace;

	// get the total number of pieces
	iPieces = m_iCols * m_iRows;

	// clear the map
	for (i = 0; i < iPieces; ++i)
		m_iMap[i] = -1;

	// create the random location map
	// upper-left is 0, lower-right is (iPieces-1)  
	iPiecesInPlace = 0;
	for (i = 0; i < iPieces; ++i)
	{
		// gotta fill every entry somehow
		while (TRUE)
		{
			// get random number to use
			int random = GetRandomNumber(iPieces);

			// see if we already used this random number
			for (int j = 0; j < i; ++j)
			{
				if (m_iMap[j] == random)
					break;
			}
			// if it hasn't been used then use it
			if (j == i)
			{
				// make the user move at least have the pieces
				if ( (i != random) || (iPiecesInPlace < (iPieces/2)) )
				{
					m_iMap[i] = random;
					if (i == random)
						++iPiecesInPlace;
					break;
				}
				//else
				//{
				//	OutputDebugString("Piece Location Rejected\n");
				//}
			}
		}
	}
	// window resizing is necessary, because we want all the tiles
	// to be exactly the same size, so we may not use some on
	// the right and bottom sides
	Resize();
	InvalidateRect(m_hWnd, NULL, TRUE);
}
Пример #18
0
static void StuffCrack( LPCRACK lpCrack, POINT pt1, BOOL bxpos, BOOL bypos,
						BOOL bxlty, int iMaxLen )
/***********************************************************************/
{
	if ( !lpCrack )
		return;

	lpCrack->pt1 = pt1;
	lpCrack->bxpos = bxpos;
	lpCrack->bypos = bypos;
	lpCrack->bxlty = bxlty;
	lpCrack->lpNext = NULL;
	int rx = GetRandomNumber( iMaxLen );
	int ry = GetRandomNumber( iMaxLen );
	int r;
	if ( bxlty != (rx < ry) ) { r = rx; rx = ry; ry = r; }
	lpCrack->pt2.x = pt1.x + ( bxpos ? rx : -rx );
	lpCrack->pt2.y = pt1.y + ( bypos ? ry : -ry );
	lpCrack->iMaxLen = iMaxLen-1;
//	r = min( rx, ry );
//	lpCrack->iMaxLen = r;
}
Пример #19
0
void
DoCommitmentNasties(void)
{
	int i;

	zone_lock(lz_world);
	for (i = 0; i < 60 - getTax(); i++) {
		UInt32 loc = GetRandomNumber(MapMul());
		welem_t world = getWorld(GetRandomNumber(MapMul()));
		int x = loc % getMapWidth();
		int y = loc % getMapHeight();

		if ((IsTransport(world)) &&
		    (GetRandomNumber(100) > getUpkeep(ue_traffic)))
			Build_Destroy(x, y);
		if ((IsWaterPipe(world) || IsPowerLine(world) ||
			    IsPowerWater(world)) &&
		    (GetRandomNumber(100) > getUpkeep(ue_power)))
			Build_Destroy(x, y);
	}
	zone_unlock(lz_world);
}
Пример #20
0
//************************************************************************
BOOL CNutDropScene::OnInitDialog (HWND hWnd, HWND hWndControl, LPARAM lParam)
//************************************************************************
{
	CGBScene::OnInitDialog (hWnd, hWndControl, lParam);
	
	m_pSound = new CSound (TRUE);
	if (m_pSound)
		m_pSound->Open (NULL);

	// Keyboard keys that we want
	App.SetKeyMapEntry (m_hWnd, VK_UP);
	App.SetKeyMapEntry (m_hWnd, VK_DOWN);
	App.SetKeyMapEntry (m_hWnd, VK_RIGHT);
	App.SetKeyMapEntry (m_hWnd, VK_LEFT);
	
	if (m_pAnimator)
	{
		HGLOBAL hData;
		LPSTR lpTableData;

		if (GetToon())
			GetToon()->SetSendMouseMode (TRUE);

		// Read in the game table information
		lpTableData = GetResourceData (m_nSceneNo, "gametbl", &hData);
		if (lpTableData)
		{
			CNutDropParser parser (lpTableData);
			parser.ParseTable ((DWORD)this);
		}
		if (hData)
		{
			UnlockResource (hData);
			FreeResource (hData);
		}

		m_pAnimator->SetClipRect (&m_rGameArea);
	}

	if (m_nSceneNo == IDD_NUTDROPI || m_nSceneNo == IDD_NUTDROP1)
		m_iLevel = 0;
	else if (m_nSceneNo == IDD_NUTDROP2)
		m_iLevel = 1;
	else if (m_nSceneNo == IDD_NUTDROP3)
		m_iLevel = 2;

	// Seed the random number generator
	wRandomSeed = GetRandomNumber (MAX_PIECES);

	return (TRUE);
}
bool SimpleContextSourceThread::ProcessEvent()
{
	LOGI("SimpleContextSourceThread::ProcessEvent- Publishing item");
	Item item;
    item.value = GetRandomNumber();
    item.dataSet = m_dataSet;
    if(m_publisher) 
	{
		m_publisher->PublishContextUpdate( m_dataSet, item );
		LOGI("SimpleContextSourceThread::ProcessEvent - Published");
	}
	return true;

}
Пример #22
0
//--------------------------------------------------------------------------------
GFSDK::SSAO::RandomTexture::RandomTexture()
    : m_pTexture(NULL)
{
    ZERO_ARRAY(m_pSRVs);

    UINT RandomNumberIndex = 0;
    for (UINT i = 0; i < ARRAYSIZE(m_JittersFP32x4); ++i)
    {
        float Rand1 = GetRandomNumber(RandomNumberIndex++);
        float Rand2 = GetRandomNumber(RandomNumberIndex++);
        float Rand3 = GetRandomNumber(RandomNumberIndex++);

        // Use random rotation angles in [0,2PI/NUM_DIRECTIONS)
        float Angle = 2.f * D3DX_PI * Rand1 / NUM_DIRECTIONS;
        m_JittersFP32x4[i].x = cosf(Angle);
        m_JittersFP32x4[i].y = sinf(Angle);
        m_JittersFP32x4[i].z = Rand2;
        m_JittersFP32x4[i].w = Rand3;

        // Convert from R32G32B32A32_FLOAT to R16G16B16A16_SNORM
        m_JittersINT16x4[i] = int16x4(m_JittersFP32x4[i]);
    }
}
Пример #23
0
void
Algorithm<T>::Selection()
{
	std::vector<double> lVector = GetRandomNumber(m_countOfChromosomes);
	std::vector<std::vector<T>> lChromosomes;
	for (int i = 0; i < lVector.size(); i++) {
		int index = 0;
		while (lVector[i] > m_cumulativeProbability[index]) {
			index++;
		}
		lChromosomes.push_back(m_chromosomes[index]);			
	}
	m_chromosomes = lChromosomes;
}
Пример #24
0
/*!
 * \brief Create a waste zone for the meteor.
 * \param x horizontal position
 * \param y vertical position
 * \param size size of the meteor
 */
static void
CreateMeteor(UInt16 x, UInt16 y, Int16 size)
{
	UInt16 j;
	UInt16 i =  (Int16)(x - size) < 0 ? 0 : (UInt16)(x - size);

	zone_lock(lz_world);
	zone_lock(lz_flags);
	UILockScreen();
	for (; i <= x + size; i++) {
		j = (Int16)(y - size) < 0 ? 0 : (UInt16)(y - size);
		for (; j <= y + size; j++) {
			if (i < getMapWidth() &&
			    j < getMapHeight()) {
				if (GetRandomNumber(5) < 2) {
					if (getWorld(WORLDPOS(i, j)) !=
					    Z_REALWATER) {
						CreateWaste(i, j);
					}
				} else if (GetRandomNumber(5) < 4) {
					if (getWorld(WORLDPOS(i, j)) !=
					    Z_REALWATER &&
					    getWorld(WORLDPOS(i, j)) !=
					    Z_FAKEWATER) {
						BurnField(i, j, 1);
					}
				}
			}
		}
	}
	Build_Destroy(x, y);
	setWorldAndFlag(WORLDPOS(x, y), Z_CRATER, 0);
	zone_unlock(lz_flags);
	zone_unlock(lz_world);
	UIUnlockScreen();
	RedrawAllFields();
}
Пример #25
0
int main() {
    std::vector<unsigned> ignored;
    ignored.push_back(2);
    ignored.push_back(4);
    ignored.push_back(6);
    unsigned dist[6] = {};
    for(int i=0; i<100000; ++i) {
        unsigned v = GetRandomNumber(1,6,ignored);
        dist[v]++;
        std::cout << v;
    }
    for(int i=0; i<6; ++i)
        std::cout << '\n' << +dist[i];
    return 0;
}
Пример #26
0
//************************************************************************
void CNutDropScene::PlayLevelSuccessWave()
//************************************************************************
{
	// Get the sound to play based on the level
	int iCount = 0;
	for (int i = 0 ; i < MAX_SUCCESSWAVES ; i++)
	{
		if (m_szSuccessLevel[i][0] != '\0')
			iCount++;
	}

	LPSTR lpWave;
	if (iCount <= 0)
	{
		lpWave = m_szSuccessLevel[0];
	}
	else
	{
		i = GetRandomNumber (iCount);
		lpWave = m_szSuccessLevel[i];
	}

	if (*lpWave != '\0')
	{
		FNAME szFileName;
		if (GetSound() )
		{
			m_SoundPlaying = SuccessPlaying;
			GetSound()->StopChannel(NORMAL_CHANNEL);
			if (m_nSceneNo == IDD_NUTDROPI)
			{ // Play this wave without wavemix
				LPSOUND lpSound = new CSound;
				if ( lpSound )
				{
					GetSound()->Activate (FALSE);
					lpSound->StartFile( GetPathName(szFileName, lpWave),
						NO/*bLoop*/, NORMAL_CHANNEL/*iChannel*/, TRUE/*bWait*/, m_hWnd);
					delete lpSound;
					GetSound()->Activate (TRUE);
					FORWARD_WM_COMMAND (m_hWnd, IDC_NEXT, NULL, m_nNextSceneNo, PostMessage);
				}
			}
			else
				GetSound()->StartFile(GetPathName (szFileName, lpWave), NO/*bLoop*/, NORMAL_CHANNEL/*iChannel*/, FALSE/*bWait*/, m_hWnd);
		}
	}
}
Пример #27
0
CSocket* CTransferSocket::CreateSocketServer()
{
	if (!m_pEngine->GetOptions()->GetOptionVal(OPTION_LIMITPORTS))
	{
		// Ask the systen for a port
		CSocket* pServer = CreateSocketServer(0);
		return pServer;
	}

	// Try out all ports in the port range.
	// Upon first call, we try to use a random port fist, after that
	// increase the port step by step

	// Windows only: I think there's a bug in the socket implementation of
	// Windows: Even if using SO_REUSEADDR, using the same local address
	// twice will fail unless there are a couple of minutes between the
	// connection attempts. This may cause problems if transferring lots of
	// files with a narrow port range.

	static int start = 0;

	int low = m_pEngine->GetOptions()->GetOptionVal(OPTION_LIMITPORTS_LOW);
	int high = m_pEngine->GetOptions()->GetOptionVal(OPTION_LIMITPORTS_HIGH);
	if (low > high)
		low = high;

	if (start < low || start > high)
	{
		start = GetRandomNumber(low, high);
		wxASSERT(start >= low && start <= high);
	}

	CSocket* pServer = 0;

	int count = high - low + 1;
	while (count--)
	{
		pServer = CreateSocketServer(start++);
		if (pServer)
			break;
		if (start > high)
			start = low;
	}

	return pServer;
}
Пример #28
0
// Updating
void ItemSpawner::Update(float dt)
{
	m_canSpawn = (m_numSpawnedItems < m_maxNumItemsToHaveActive);

	// Update timers
	UpdateTimers(dt);

	if(m_spawning && m_canSpawn)
	{
		if(m_spawnCountdownTimer <= 0.0f)
		{
			vec3 spawnPos;
			bool spawnGood = GetSpawnPosition(&spawnPos);

			if (spawnGood)
			{
				vec3 toPlayer = spawnPos - m_pPlayer->GetCenter();
				if (length(toPlayer) > m_minDistanceFromPlayer)
				{
					eItem itemType = GetItemTypeToSpawn();
					string itemFilename = GetItemFilenameForType(itemType);

					Item* pItem = m_pItemManager->CreateItem(spawnPos, vec3(0.0f, 0.0f, 0.0f), vec3(0.0f, 0.0f, 0.0f), itemFilename.c_str(), itemType, "SpawnedItem", true, false, m_spawnScale);
					pItem->SetItemSpawner(this);
					
					if (itemType == eItem_CopperVein || itemType == eItem_IronVein || itemType == eItem_SilverVein || itemType == eItem_GoldVein)
					{
						pItem->SetMaxtInteractCount(4);
					}
					pItem->SetRotation(vec3(0.0f, GetRandomNumber(0, 360, 2), 0.0f));

					m_numSpawnedItems += 1;

					m_spawnCountdownTimer = m_spawnTime;
				}
			}
			else
			{
				// Can't spawn an item at a good position, wait a while before we try again
				m_spawnCountdownTimer = 0.5f;
			}
		}
	}
}
Пример #29
0
Int16
UpdateDisasters(void)
{
	/* return false if no disasters are found */
	UInt16 i, j;
	welem_t type;
	int retval = 0;

	zone_lock(lz_world);
	zone_lock(lz_flags);
	clearScratch(SCRATCHDISASTER);
	for (i = 0; i < getMapHeight(); i++) {
		for (j = 0; j < getMapWidth(); j++) {
			type = getWorld(WORLDPOS(i, j));
			/* already looked at this one? */
			if (getWorldFlags(WORLDPOS(i, j)) & SCRATCHDISASTER) {
				if (type == Z_FIRE2) {
					retval = 1;
					if (GetRandomNumber(5) != 0) {
						/* are there any defences */
						if (GetDefenceValue(i, j) < 3) {
							FireSpread(i, j);
						}
						setWorldAndFlag(WORLDPOS(i, j),
						    Z_FIRE3, 0);
					} else {
						CreateWaste(i, j);
					}
				} else if (type == Z_FIRE1) {
					retval = 1;
					setWorldAndFlag(WORLDPOS(i, j),
					    Z_FIRE2, 0);
				} else if (type == Z_FIRE3) {
					retval = 1;
					CreateWaste(i, j);
				}
			}
		}
	}
	zone_unlock(lz_flags);
	zone_unlock(lz_world);
	return (retval);
}
//***********************************************************************************
LOCAL_C TInt Execute()
	{
	TInt err = KErrNoMemory;
	CTrapCleanup* cleanup=CTrapCleanup::New();	//can fail
	if (cleanup)
		{
		_LIT(KPlatSecTestName, "PlatSectTaskHandlerTest");
		RTest theTest(KPlatSecTestName);
		theTest.Start(KPlatSecTestName);
		theTest.Title();

		RFile file;

		// Adopt the task file from the Task Scheduler
		err = file.AdoptFromCreator(TScheduledTaskFile::FsHandleIndex(),
									TScheduledTaskFile::FileHandleIndex());
		if (err != KErrNone)
			return err;
		
		// The aParam is the name of a file where the relevant CTaskExCmdLine is
		// do the executing 
		theTest.Next(_L(" @SYMTestCaseID:SYSLIB-SCHSVR-CT-1345 "));
		TRAPD(err, ConstructConsoleL(file, theTest));
		if(err == KErrNone)
			{
			// Sometimes we want to return a bogus error value, 
			// sometimes we don't.
			TTime now;
			now.HomeTime();
			TInt64 seed = now.Int64();
			err = GetRandomNumber(-50, 200, seed); //20% chance of error being returned
			}
		
		file.Close();// Close the file
		
		theTest.End();
		theTest.Close();
				
		delete cleanup;
		}
	SignalTestExe();		
	return err;
	}