示例#1
0
static void
generate_tractors (void)
{
	if (pSolarSysState->pOrbitalDesc->pPrevDesc != &pSolarSysState->PlanetDesc[2]
			|| pSolarSysState->pOrbitalDesc != &pSolarSysState->MoonDesc[1])
		pSolarSysState->CurNode = 0;
	else /* Earth Moon */
	{
		COUNT i, which_node;
		DWORD old_rand, rand_val;

		old_rand = SeedRandom (pSolarSysState->SysInfo.PlanetInfo.ScanSeed[BIOLOGICAL_SCAN]);

		which_node = i = 0;
		do
		{
			rand_val = Random ();
			pSolarSysState->SysInfo.PlanetInfo.CurPt.x =
					(LOBYTE (LOWORD (rand_val)) % (MAP_WIDTH - (8 << 1))) + 8;
			pSolarSysState->SysInfo.PlanetInfo.CurPt.y =
					(HIBYTE (LOWORD (rand_val)) % (MAP_HEIGHT - (8 << 1))) + 8;
			pSolarSysState->SysInfo.PlanetInfo.CurType = NUM_CREATURE_TYPES + 1;
			if (which_node >= pSolarSysState->CurNode
					&& !(pSolarSysState->SysInfo.PlanetInfo.ScanRetrieveMask[BIOLOGICAL_SCAN]
					& (1L << i)))
				break;
			++which_node;
		} while (++i < 10);
		pSolarSysState->CurNode = which_node;

		SeedRandom (old_rand);
	}
}
CMusikPlayer::CMusikPlayer()
	:wxEvtHandler()
        ,m_SndEngine(wxGetApp().Prefs.nSndRate,2,0)
	
{
	m_Playing		= false;
	m_Paused		= false;
	m_Fading		= false;
	m_BeginFade		= false;
	m_StartingNext	= false;
	m_Stopping		= false;
	m_SongIndex		= 0;
	m_CrossfadeType	= 0;
	m_DSP			= NULL;
	m_Playmode = MUSIK_PLAYMODE_NORMAL;
	m_NETSTREAM_read_percent = 0;
	m_NETSTREAM_bitrate = 0;
	m_NETSTREAM_status = -1;
	m_NETSTREAM_flags = 0;
	m_b_NETSTREAM_AbortConnect = false;
	m_p_NETSTREAM_Connecting = NULL;
	//--- initialize random playback ---//
	long RandomSeed = wxGetLocalTime();
	SeedRandom( RandomSeed );
	m_arrHistory.Alloc(wxGetApp().Prefs.nMaxShuffleHistory);
	//set stop watch into pause mode.
	m_bStreamIsWorkingStopWatchIsRunning = false ;
	m_NETSTREAM_last_read_percent = 0;
	m_nLastSongTime = 0;
	m_bSuppressAutomaticSongPicking = false;
	m_bPostPlayRestartInProgress = false;
}
示例#3
0
bool GpxDocument::LoadFile(const wxString &filename)
{
      SeedRandom();
      wxRegEx re; //We try to fix popularily broken GPX files. Unencoded '&' is an illegal character in XML, but seems higly popular amongst users (and perhaps even vendors not aware of what XML is...)
      //The same as above is true for '<' but it would be harder to solve - it's illegal just inside a value, not when it starts a tag
      int re_compile_flags = wxRE_ICASE;
#ifdef wxHAS_REGEX_ADVANCED
      re_compile_flags |= wxRE_ADVANCED;
#endif
      bool b = re.Compile(wxT("&(?!amp;|lt;|gt;|apos;|quot;|#[0-9]{1,};|#x[0-f]{1,};)"), re_compile_flags); //Should find all the non-XML entites to be encoded as text
      wxFFile file(filename);
      wxString s;
      if(file.IsOpened()) {
            file.ReadAll(&s, wxConvUTF8);
            file.Close();
      }
      if(b)
      {
            //CDATA handling makes this task way too complex for regular expressions to handle,
            // so we do nothing and just let the possible damage happen...
            if (!s.Contains(wxT("![CDATA[")))
            {
                  int cnt = re.ReplaceAll(&s, wxT("&amp;"));
                  if (cnt > 0)
                        wxLogMessage(wxString::Format(wxT("File %s seems broken, %i occurences of '&' were replaced with '&amp;' to try to fix it."), filename.c_str(), cnt));
            }
      }
      wxFFile gpxfile;
      wxString gpxfilename = wxFileName::CreateTempFileName(wxT("gpx"), &gpxfile);
      gpxfile.Write(s);
      gpxfile.Close();
      bool res = TiXmlDocument::LoadFile((const char*)gpxfilename.mb_str());
      ::wxRemoveFile(gpxfilename);
      return res;
}
示例#4
0
文件: main.cpp 项目: kolyden/mirror
void Test()
{
	MemoryLimitKb(8000000);
	for(int sz = 0; sz < 2; sz++) {
		for(int pass = 0; pass < 2; pass++) {
			RLOG("--------------------");
			DUMP(sz);
			DUMP(pass);
			{
				NanoStrings ns;
				Vector<dword> ws;
				
				ns.ZeroTerminated(sz);
			
				SeedRandom();
				for(int i = 0; i < 140000000; i++) {
					if(i % 10000000 == 0)
						RLOG("Created " << i);
					String s = pass ? "x" : RandomString(Random(4) ? 5 : 50);
					ws.Add(ns.Add(s));
				}
				
//				ns.DumpProfile();
				RLOG("---- Strings " << MemoryUsedKb() << " KB used -------");
				RLOG(MemoryProfile());
				
				SeedRandom();
				for(int i = 0; i < ws.GetCount(); i++) {	
					if(i % 10000000 == 0)
						RLOG("Tested " << i);
					String s = pass ? "x" : RandomString(Random(4) ? 5 : 50);
					if((sz ? String(ns.GetPtr(ws[i])) : ns.Get(ws[i])) != s) {
						DUMP(i);
						DUMP(ns.Get(ws[i]));
						DUMP(s);
						NEVER();
					}
				}
				RLOG("Test OK");
			}
			RLOG("===== EMPTY " << MemoryUsedKb() << " KB used -------");
			RLOG(MemoryProfile());		
		}
	}
}
示例#5
0
DWORD
SeedRandomNumbers (void)
{
	DWORD cur_time;

	SeedRandom (cur_time = GetTimeCounter ());

	return (cur_time);
}
示例#6
0
void TRI_InitialiseRandom (void) {
  if (Initialised) {
    return;
  }

  TRI_srandom(SeedRandom());

  Initialised = true;
}
示例#7
0
bool GpxDocument::LoadFile(const wxString &filename)
{
      SeedRandom();
      wxRegEx re; //We try to fix popularily broken GPX files. Unencoded '&' is an illegal character in XML, but seems higly popular amongst users (and perhaps even vendors not aware of what XML is...)
      //The same as above is true for '<' but it would be harder to solve - it's illegal just inside a value, not when it starts a tag
      int re_compile_flags = wxRE_ICASE;
#ifdef wxHAS_REGEX_ADVANCED
      re_compile_flags |= wxRE_ADVANCED;
#endif
      bool b = re.Compile(wxT("&(?!amp;|lt;|gt;|apos;|quot;|#[0-9]{1,};|#x[0-f]{1,};)"), re_compile_flags); //Should find all the non-XML entites to be encoded as text
      wxFFile file(filename);
      wxString s;
      if(file.IsOpened()) {
            file.ReadAll(&s, wxConvUTF8);

            //Fallback for not-well formed (non-UTF8) GPX files
            //the "garbage" characters are lost, but the important part of the information should survive...
            if (s == wxEmptyString)
            {
                  file.Seek(0);
                  file.ReadAll(&s, wxConvISO8859_1);
                  wxLogMessage(wxString::Format(wxT("File %s seems not to be well-formed UTF-8 XML, used fallback ASCII format conversion - some text information might have not been imported."), filename.c_str()));
            }

            file.Close();
      }
      if(b)
      {
            //CDATA handling makes this task way too complex for regular expressions to handle,
            // so we do nothing and just let the possible damage happen...
            if (!s.Contains(wxT("![CDATA[")))
            {
                  int cnt = re.ReplaceAll(&s, wxT("&amp;"));
                  if (cnt > 0)
                        wxLogMessage(wxString::Format(wxT("File %s seems broken, %i occurences of '&' were replaced with '&amp;' to try to fix it."), filename.c_str(), cnt));
            }
      }
      wxFFile gpxfile;
      wxString gpxfilename = wxFileName::CreateTempFileName(wxT("gpx"), &gpxfile);
      gpxfile.Write(s);
      gpxfile.Close();
      bool res = TiXmlDocument::LoadFile((const char*)gpxfilename.mb_str());

	  if( ! res ) {
		  wxString msg = _T("Failed to load ");
		  msg << filename;
		  msg << _T(": ");
		  msg << wxString( TiXmlDocument::ErrorDesc(), wxConvUTF8 );
 		  wxLogMessage( msg );
	  }
      ::wxRemoveFile(gpxfilename);
      return res;
}
bool StationaryMixPointIrregular::SimulationBegin()
{
	//Initializations
	SeedRandom();
	Transmitter.x=GetRunVariableInteger("MixPointX");
	Transmitter.y=GetRunVariableInteger("MixPointY");
	Transmitter.Radius=GetRunVariableInteger("ZoneRadius");
	Transmitter.Title="Stationary Mix Point";
	RandDurationMin=GetRunVariableInteger("RandDurationMin");
	RandDurationMax=GetRunVariableInteger("RandDurationMax");
	NextSilentPeriod=0;
	return true;
}
示例#9
0
	std::vector<unsigned int> UniqueRandomIndices(const unsigned int MAX, const unsigned int Number)
	{
		//generate Number unique random indices from 0 to MAX

		SeedRandom();
		assert(Number <= MAX+1); //cannot generate more unique numbers than than the size of the set we are sampling
		
		std::set<unsigned int> S;
		while(S.size() < Number)
			S.insert(RandomInt(MAX));

		std::vector<unsigned int> Indices;
		for(std::set<unsigned int>::iterator iter = S.begin(); iter != S.end(); iter++)
			Indices.push_back(*iter);

		return Indices;
	}
示例#10
0
//Function set new game GameArray
void Fifteen::SetGameArray()
{
	if (!usedSolution)
	{
		points = 0;
		result.SetData(points);
		time = 0;
		timeresult.SetData(time);
		SeedRandom(GetSysTime().Get());
		endOfGame = false;
		usedSolution = false;
		RandomGameArray(GameArray);
	
		//Saving GameArray for solution finder
		CopyTGameArray(GameStartArray, GameArray);
	}
	else
	{
		PromptOK(SOLUTIONMSG);	
	}
}
示例#11
0
bool DummyEventProtocol::SimulationBegin()
{
	PreSimulationVariableCheck("SilentPeriod");
	PreSimulationVariableCheck("MaxVehiclesInSet");
	PreSimulationVariableCheck("VehicleTransmissionRadius");
	SeedRandom();
	SilentPeriod=GetRunVariableInteger("SilentPeriod");
	MaxVehiclesInSet=GetRunVariableInteger("MaxVehiclesInSet");
	AnnouncerRadius=GetRunVariableInteger("VehicleTransmissionRadius");
	int MinRandomDuration=0;
	int MaxRandomDuration=0;
	if(!OnTheFly)
	{
		PreSimulationVariableCheck("MixPointX");
		PreSimulationVariableCheck("MixPointY");
		MainTransmitter.x=GetRunVariableInteger("MixPointX");
		MainTransmitter.y=GetRunVariableInteger("MixPointY");
	}
	else
	{
		for(int i=0;i<VehicleMax;i++){Vehicles[i]->TransmissionRadius=AnnouncerRadius;}
	}
	if(Irregular)
	{
		PreSimulationVariableCheck("MinRandomDuration");
		PreSimulationVariableCheck("MaxRandomDuration");
		MinRandomDuration=GetRunVariableInteger("MinRandomDuration");
		MaxRandomDuration=GetRunVariableInteger("MaxRandomDuration");
	}
	MainTransmitter.TransmissionRadius=AnnouncerRadius;
	for(int i=0;i<TimeMax;i+=(Irregular?RandInt(MinRandomDuration,MaxRandomDuration):SilentPeriod))
	{
		AnonymitySet* CurrentSet=new AnonymitySet(MainTransmitter.x,MainTransmitter.y,AnnouncerRadius,i,i,i+SilentPeriod,&MainTransmitter);
		AnonymitySets.PushObj(CurrentSet);
	}
	return true;
}
示例#12
0
GpxDocument::GpxDocument()
{
      PopulateEmptyDocument(_T("OpenCPN"));
      AddCustomNamespace(_T("xmlns:opencpn"), _T("http://www.opencpn.org"));
      SeedRandom();
}
示例#13
0
void
GenerateSOL (BYTE control)
{
	COUNT i;
	DWORD rand_val;
	PPLANET_DESC pCurDesc;

	switch (control)
	{
		case INIT_NPCS:
			init_probe ();
			break;
		case REINIT_NPCS:
			if (GET_GAME_STATE (CHMMR_BOMB_STATE) != 3)
				GenerateRandomIP (REINIT_NPCS);
			else
			{
				GLOBAL (BattleGroupRef) = 0;
				ReinitQueue (&GLOBAL (npc_built_ship_q));
			}
			break;
		case GENERATE_ENERGY:
			generate_energy_nodes ();
			break;
		case GENERATE_LIFE:
			generate_tractors ();
			break;
		case GENERATE_ORBITAL:
			generate_orbital ();
			break;
		case GENERATE_NAME:
			i = pSolarSysState->pBaseDesc - pSolarSysState->PlanetDesc;
			wstrcpy (GLOBAL_SIS (PlanetName), GAME_STRING (PLANET_NUMBER_BASE + i));
			SET_GAME_STATE (BATTLE_PLANET,
					pSolarSysState->PlanetDesc[i].data_index);
			break;
		case GENERATE_MOONS:
		{
			GenerateRandomIP (GENERATE_MOONS);

			i = pSolarSysState->pBaseDesc - pSolarSysState->PlanetDesc;
			switch (i)
			{
				case 2: /* moons of EARTH */
				{
					COUNT angle;

					pSolarSysState->MoonDesc[0].data_index = (BYTE)~0;
					pSolarSysState->MoonDesc[0].radius = MIN_MOON_RADIUS;
					angle = HALF_CIRCLE + QUADRANT;
					pSolarSysState->MoonDesc[0].location.x =
							COSINE (angle, pSolarSysState->MoonDesc[0].radius);
					pSolarSysState->MoonDesc[0].location.y =
							SINE (angle, pSolarSysState->MoonDesc[0].radius);

					pSolarSysState->MoonDesc[1].data_index = SELENIC_WORLD;
					pSolarSysState->MoonDesc[1].radius = MIN_MOON_RADIUS
							+ (MAX_MOONS - 1) * MOON_DELTA;
					rand_val = Random ();
					angle = NORMALIZE_ANGLE (LOWORD (rand_val));
					pSolarSysState->MoonDesc[1].location.x =
							COSINE (angle, pSolarSysState->MoonDesc[1].radius);
					pSolarSysState->MoonDesc[1].location.y =
							SINE (angle, pSolarSysState->MoonDesc[1].radius);
					break;
				}
				case 4: /* moons of JUPITER */
					pSolarSysState->MoonDesc[0].data_index = RADIOACTIVE_WORLD;
					pSolarSysState->MoonDesc[1].data_index = HALIDE_WORLD;
					pSolarSysState->MoonDesc[2].data_index = CYANIC_WORLD;
					pSolarSysState->MoonDesc[3].data_index = PELLUCID_WORLD;
					break;
				case 5: /* moons of SATURN */
					pSolarSysState->MoonDesc[0].data_index = ALKALI_WORLD;
					break;
				case 7: /* moons of NEPTUNE */
					pSolarSysState->MoonDesc[0].data_index = VINYLOGOUS_WORLD;
					break;
			}
			break;
		}
		case GENERATE_PLANETS:
		{
#define SOL_SEED 334241042L
			SeedRandom (SOL_SEED);

			pSolarSysState->SunDesc[0].NumPlanets = 9;
			for (i = 0, pCurDesc = pSolarSysState->PlanetDesc; i < 9; ++i, ++pCurDesc)
			{
				COUNT angle;
				UWORD word_val;

				pCurDesc->rand_seed = rand_val = Random ();
				word_val = LOWORD (rand_val);
				angle = NORMALIZE_ANGLE ((COUNT)HIBYTE (word_val));

				switch (i)
				{
					case 0: /* MERCURY */
						pCurDesc->data_index = METAL_WORLD;
						pCurDesc->radius = EARTH_RADIUS * 39L / 100;
						pCurDesc->NumPlanets = 0;
						break;
					case 1: /* VENUS */
						pCurDesc->data_index = PRIMORDIAL_WORLD;
						pCurDesc->radius = EARTH_RADIUS * 72L / 100;
						pCurDesc->NumPlanets = 0;
						angle = NORMALIZE_ANGLE (FULL_CIRCLE - angle);
						break;
					case 2: /* EARTH */
						pCurDesc->data_index = WATER_WORLD | PLANET_SHIELDED;
						pCurDesc->radius = EARTH_RADIUS;
						pCurDesc->NumPlanets = 2;
						break;
					case 3: /* MARS */
						pCurDesc->data_index = DUST_WORLD;
						pCurDesc->radius = EARTH_RADIUS * 152L / 100;
						pCurDesc->NumPlanets = 0;
						break;
					case 4: /* JUPITER */
						pCurDesc->data_index = RED_GAS_GIANT;
						pCurDesc->radius = EARTH_RADIUS * 500L /* 520L */ / 100;
						pCurDesc->NumPlanets = 4;
						break;
					case 5: /* SATURN */
						pCurDesc->data_index = ORA_GAS_GIANT;
						pCurDesc->radius = EARTH_RADIUS * 750L /* 952L */ / 100;
						pCurDesc->NumPlanets = 1;
						break;
					case 6: /* URANUS */
						pCurDesc->data_index = GRN_GAS_GIANT;
						pCurDesc->radius = EARTH_RADIUS * 1000L /* 1916L */ / 100;
						pCurDesc->NumPlanets = 0;
						break;
					case 7: /* NEPTUNE */
						pCurDesc->data_index = BLU_GAS_GIANT;
						pCurDesc->radius = EARTH_RADIUS * 1250L /* 2999L */ / 100;
						pCurDesc->NumPlanets = 1;
						break;
					case 8: /* PLUTO */
						pCurDesc->data_index = PELLUCID_WORLD;
						pCurDesc->radius = EARTH_RADIUS * 1550L /* 3937L */ / 100;
						pCurDesc->NumPlanets = 0;
						angle = FULL_CIRCLE - OCTANT;
						break;
				}

				pCurDesc->location.x =
						COSINE (angle, pCurDesc->radius);
				pCurDesc->location.y =
						SINE (angle, pCurDesc->radius);
			}
			break;
		}
		default:
			GenerateRandomIP (control);
			break;
	}
}
示例#14
0
void
GeneratePkunk (BYTE control)
{
	switch (control)
	{
		case GENERATE_ENERGY:
			if (pSolarSysState->pOrbitalDesc == &pSolarSysState->PlanetDesc[0])
			{
				COUNT i, which_node;
				DWORD rand_val, old_rand;

				old_rand = SeedRandom (
						pSolarSysState->SysInfo.PlanetInfo.ScanSeed[ENERGY_SCAN]
						);

				which_node = i = 0;
				do
				{
					rand_val = Random ();
					pSolarSysState->SysInfo.PlanetInfo.CurPt.x =
							(LOBYTE (LOWORD (rand_val)) % (MAP_WIDTH - (8 << 1))) + 8;
					pSolarSysState->SysInfo.PlanetInfo.CurPt.y =
							(HIBYTE (LOWORD (rand_val)) % (MAP_HEIGHT - (8 << 1))) + 8;
					if (!GET_GAME_STATE (CLEAR_SPINDLE))
						pSolarSysState->SysInfo.PlanetInfo.CurType = 0;
					else
						pSolarSysState->SysInfo.PlanetInfo.CurType = 1;
					pSolarSysState->SysInfo.PlanetInfo.CurDensity = 0;
					if (pSolarSysState->SysInfo.PlanetInfo.ScanRetrieveMask[ENERGY_SCAN]
							& (1L << i))
					{
						pSolarSysState->SysInfo.PlanetInfo.ScanRetrieveMask[ENERGY_SCAN]
								&= ~(1L << i);

						if (!GET_GAME_STATE (CLEAR_SPINDLE))
						{
							((PPLANETSIDE_DESC)pMenuState->ModuleFrame)->InTransit = TRUE;

							SET_GAME_STATE (CLEAR_SPINDLE, 1);
							SET_GAME_STATE (CLEAR_SPINDLE_ON_SHIP, 1);
						}
					}
					if (which_node >= pSolarSysState->CurNode
							&& !(pSolarSysState->SysInfo.PlanetInfo.ScanRetrieveMask[ENERGY_SCAN]
							& (1L << i)))
						break;
					++which_node;
				} while (++i < 16);
				pSolarSysState->CurNode = which_node;

				SeedRandom (old_rand);
				break;
			}
			pSolarSysState->CurNode = 0;
			break;
		case GENERATE_PLANETS:
		{
			COUNT angle;

			GenerateRandomIP (GENERATE_PLANETS);
			pSolarSysState->PlanetDesc[0].data_index = WATER_WORLD;
			pSolarSysState->PlanetDesc[0].NumPlanets = 1;
			pSolarSysState->PlanetDesc[0].radius = EARTH_RADIUS * 104L / 100;
			angle = ARCTAN (
					pSolarSysState->PlanetDesc[0].location.x,
					pSolarSysState->PlanetDesc[0].location.y
					);
			pSolarSysState->PlanetDesc[0].location.x =
					COSINE (angle, pSolarSysState->PlanetDesc[0].radius);
			pSolarSysState->PlanetDesc[0].location.y =
					SINE (angle, pSolarSysState->PlanetDesc[0].radius);
			break;
		}
		case GENERATE_ORBITAL:
			if (pSolarSysState->pOrbitalDesc == &pSolarSysState->PlanetDesc[0])
			{
				if (ActivateStarShip (PKUNK_SHIP, SPHERE_TRACKING))
				{
					NotifyOthers (PKUNK_SHIP, (BYTE)~0);
					PutGroupInfo (0L, (BYTE)~0);
					ReinitQueue (&GLOBAL (npc_built_ship_q));

					CloneShipFragment (PKUNK_SHIP,
							&GLOBAL (npc_built_ship_q), (BYTE)~0);

					pSolarSysState->MenuState.Initialized += 2;
					GLOBAL (CurrentActivity) |= START_INTERPLANETARY;
					SET_GAME_STATE (GLOBAL_FLAGS_AND_DATA, 1 << 7);
					InitCommunication (PKUNK_CONVERSATION);
					pSolarSysState->MenuState.Initialized -= 2;

					if (!(GLOBAL (CurrentActivity) & (CHECK_ABORT | CHECK_LOAD)))
					{
						GLOBAL (CurrentActivity) &= ~START_INTERPLANETARY;
						ReinitQueue (&GLOBAL (npc_built_ship_q));
						GetGroupInfo (0L, 0);
					}
					break;
				}
				else
				{
					pSolarSysState->SysInfo.PlanetInfo.LanderFont =
							CaptureFont (
									LoadGraphic (LANDER_FONT)
									);
					pSolarSysState->PlanetSideFrame[1] =
							CaptureDrawable (
							LoadGraphic (RUINS_MASK_PMAP_ANIM)
							);
					pSolarSysState->SysInfo.PlanetInfo.DiscoveryString =
							CaptureStringTable (
									LoadStringTable (PKUNK_RUINS_STRTAB)
									);
					if (GET_GAME_STATE (CLEAR_SPINDLE))
						pSolarSysState->SysInfo.PlanetInfo.DiscoveryString =
								SetAbsStringTableIndex (
								pSolarSysState->SysInfo.PlanetInfo.DiscoveryString,
								1
								);
				}
			}
		default:
			GenerateRandomIP (control);
			break;
	}
}
示例#15
0
int main()
{
	SeedRandom();	// Seeds random values for entire program.
	// Create weapon shops and load inventory.
	WeaponShop staveShop;
	std::ifstream staveInputFile("staves.txt");
	staveShop.InitializeShop(staveInputFile);
	WeaponShop swordShop;
	std::ifstream swordInputFile("swords.txt");
	swordShop.InitializeShop(swordInputFile);
	WeaponShop bowShop;
	std::ifstream bowInputFile("bows.txt");
	bowShop.InitializeShop(bowInputFile);


	// Get user input to create a player character.
	std::cout << "\n----------------------------------" << std::endl;
	std::cout << "Welcome to Scott's Text Adventure!" << std::endl;
	std::cout << "----------------------------------" << std::endl;
	std::cout << "Enter your character's name: ";
	std::string characterName;
	getline(std::cin, characterName);
	std::cout << "\nChoose your class:" << std::endl;
	std::cout << "[1] Warrior -- High HP & high defense, low damage output" << std::endl
			  << "[2] Mage    -- Low HP & low defense, high damage output. " << std::endl
			  << "[3] Archer  -- Medium HP & medium defense, medium damage output." << std::endl;
	std::size_t jobChoicesCount = 3;
	int jobChoice = 0;
	std::cout << ">>";
	// While input is valid and isn't out of range for the options.
	while(!(std::cin >> jobChoice) || 0 > jobChoice || jobChoice > jobChoicesCount)
	{
		HandleInvalidInput(std::cin);
	}

	// Use input to create the player character.
	Handle<PlayerCharacterBase> playerHandle(CreatePlayerCharacter(characterName, jobChoice));
	//playerHandle->GainExp(3000);
	std::cout << "\nCharacter Information:" << std::endl;
	playerHandle->DisplayStats();
	std::cout << "\nPress enter to begin the game!" << std::endl;
	std::cin.get();
	std::cin.get();

	// Create Battle object.
	Battle battleSystem;

	// Run main program loop while player isn't dead.
	while(!playerHandle->PlayerIsDead())
	{
		if(playerHandle->ReturnLevel() % 3 == 0)
		{
			battleSystem.BossBattle(playerHandle);
		}
		else
		{
			battleSystem.RandomBattle(playerHandle);
		}
		if(!playerHandle->PlayerIsDead())
		{
			enum MenuOptions {NextBattle = 1, 
							  WeaponShop = 2, 
							  DisplayStats = 3,
							  QuitGame = 4};
			int menuChoicesTotal = 4;
			int menuChoice = 0;
			while(menuChoice != NextBattle)
			{
				std::cout << "Menu: " << std::endl;
				std::cout << "[1] Next Battle" << std::endl;
				std::cout << "[2] Weapon Shop" << std::endl;
				std::cout << "[3] Display Stats" << std::endl;
				std::cout << "[4] Quit Game" << std::endl;
				std::cout << ">> ";
				// Take user input for menu choice, check for invalid input.
				while(!(std::cin >> menuChoice) || menuChoice < 0 || menuChoicesTotal < menuChoice)
				{
					// Clear std::cin and remove extra characters from istream.
					HandleInvalidInput(std::cin);
				}
				if(menuChoice == WeaponShop)
				{
					// Check the job type of the player. This is used to 
					// determine which store the player needs to visit. 
					std::string jobType = playerHandle->JobType();
					if(jobType == "warrior")
					{
						swordShop.DisplayInventory();
						swordShop.ProcessTransaction(playerHandle);

					}
					else if(jobType == "mage")
					{
						staveShop.DisplayInventory();
						staveShop.ProcessTransaction(playerHandle);
					}
					else if(jobType == "archer")
					{
						bowShop.DisplayInventory();
						bowShop.ProcessTransaction(playerHandle);
					}
				}
				else if(menuChoice == DisplayStats)
				{
					playerHandle->DisplayStats();
					std::cout << "Press enter to continue.";
					std::cin.get();
					std::cin.get();
				}
				else if(menuChoice == QuitGame)
				{
					std::cout << "This isn't programmed yet." << std::endl;
				}
			std::cout << std::endl;
			}
		}
	}
	return 0;
}
示例#16
0
文件: main.cpp 项目: andyfriesen/ika
// TODO: Make a nice happy GUI thingie for making a user.cfg
// This is ugly. :(
void Engine::Startup(std::string& pathname) {
    CDEBUG("Startup");
    std::string gamePathName;
    std::string cfgPathName;
    std::string logPathName;

    // Load game.ika-game.
    std::ifstream file;
    if(!pathname.empty()) {
        IkaPath::_game = pathname + "/";
    }
    gamePathName = IkaPath::_game + "game.ika-game"; 
    cfgPathName = IkaPath::_game + "user.cfg";
    logPathName = IkaPath::_game + "ika.log";

    file.open(gamePathName.c_str());
    if (!file.is_open()) {
        // We should have a function for concatenating multiple char arrays.
        std::string fileError = "Game Startup: "; 
        fileError += gamePathName;
        fileError += " does not exist.\n";
        Sys_Error(fileError.c_str());
		return;
    }

    aries::DataNode* document;
    file >> document;
    file.close();

    std::string title;
	std::string currentNodeName = "<?>";
    uint xres = 0;
    uint yres = 0;

	try {
		aries::DataNode* rootNode = document->getChild("ika-game");
		currentNodeName = "ika-game";

		// Load information node.
		{
			aries::DataNode* infoNode = rootNode->getChild("information");
			currentNodeName = "information";

			title = infoNode->getChild("title")->getString();
		}

		// Load video node.
		{
			aries::DataNode* videoNode = rootNode->getChild("video");
			currentNodeName = "video";

			xres = (uint)std::atoi(videoNode->getChild("xres")->getString().c_str());
			yres = (uint)std::atoi(videoNode->getChild("yres")->getString().c_str());
		}

		// Load resources node (optional).
		{
			if(rootNode->hasChild("resources")) {
				aries::DataNode* resNode = rootNode->getChild("resources");
				currentNodeName = "resources";

				// Set map path.
				if(resNode->hasChild("maps")) IkaPath::_map = resNode->getChild("maps")->getString();
                if(!IkaPath::_map.empty()) IkaPath::_map +=  "/";
			}
		}
	}
	catch (std::runtime_error error) {
		std::string msg = "Game Startup: Error in game.ika-game, inside node '";
		msg += currentNodeName + "': ";
		msg += error.what();
		Sys_Error(msg.c_str());
		return;
	}

    CConfigFile cfg(cfgPathName.c_str());

    // init a few values
    _showFramerate  = cfg.Int("showfps") != 0;
    _frameSkip      = min(1, cfg.Int("frameskip"));

    // Now the tricky stuff.
    try {
        if (cfg.Int("log")) {
            Log::Init(logPathName.c_str());
        }

        Log::Write("ika %s startup", IKA_VERSION);
        Log::Write("Built on " __DATE__);
        Log::Write("--------------------------");

        Log::Write("Initializing SDL");
        SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_JOYSTICK
#ifndef _DEBUG
            | SDL_INIT_NOPARACHUTE
#endif
            );

        atexit(SDL_Quit);


#if (!defined _DEBUG)
        SDL_WM_SetCaption(title.c_str(), 0);
#else
        SDL_WM_SetCaption(va("%s (debug)", title), 0);
#endif

        Log::Write("Initializing Video");
        std::string driver = toLower(cfg["videodriver"]);

#if 0
        // disabled because it's unstable and scary. 
        if (driver == "soft" || driver == "sdl") {
            Log::Write("Starting SDL video driver");
            video = new Soft32::Driver(
                xres, 
                yres, 
                cfg.Int("bitdepth"), 
                cfg.Int("fullscreen") != 0);
        }
        else if (driver == "opengl")
#endif
        {
            Log::Write("Starting OpenGL video driver");
            video = new OpenGL::Driver(
                xres, 
                yres, 
                cfg.Int("bitdepth"), 
                cfg.Int("fullscreen") != 0,
                cfg.Int("doublesize") != 0,
                cfg.Long("filter") != 0);
        }

#ifdef WIN32
        {
            SDL_SysWMinfo info;
            SDL_VERSION(&info.version);
            HWND hWnd = SDL_GetWMInfo(&info) ? info.window : 0;
            if (hWnd)
                SetClassLong(hWnd, GCL_HICON, (long)LoadIcon(GetModuleHandle(0), "AppIcon"));
        }
#endif

        Log::Write("Initializing Input");
        SDL_JoystickEventState(SDL_ENABLE);
        Input::getInstance(); // force creation of the singleton instance.

        Log::Write("Initializing sound");
        Sound::Init(cfg.Int("nosound") != 0);
    } catch (Video::Exception) {
        video = 0;
        Sys_Error("Unable to set the video mode.\nAre you sure your hardware can handle the chosen settings?");
    } catch (Sound::Exception) {
        Log::Write("Sound initialization failed.  Disabling audio.");
    } catch (...) {
        Sys_Error("An unknown error occurred during initialization.");
    }

    SeedRandom();

    Log::Write("Initing Python");
    script.Init(this);
    Log::Write("Executing system.py");
    bool result = script.LoadSystemScripts(pathname);

    if (!result) {
        Script_Error();
    }

    if (!_isMapLoaded) {
        Sys_Error("");
    }

    Log::Write("Startup complete");
}
示例#17
0
void
GenerateUrquanWreck (BYTE control)
{
	switch (control)
	{
		case GENERATE_ENERGY:
			if (pSolarSysState->pOrbitalDesc == &pSolarSysState->PlanetDesc[6])
			{
				DWORD rand_val, old_rand;

				old_rand = SeedRandom (
						pSolarSysState->SysInfo.PlanetInfo.ScanSeed[ENERGY_SCAN]
						);

				rand_val = Random ();
				pSolarSysState->SysInfo.PlanetInfo.CurPt.x =
						(LOBYTE (LOWORD (rand_val)) % (MAP_WIDTH - (8 << 1))) + 8;
				pSolarSysState->SysInfo.PlanetInfo.CurPt.y =
						(HIBYTE (LOWORD (rand_val)) % (MAP_HEIGHT - (8 << 1))) + 8;
				pSolarSysState->SysInfo.PlanetInfo.CurDensity = 0;
				if (!GET_GAME_STATE (PORTAL_KEY))
					pSolarSysState->SysInfo.PlanetInfo.CurType = 0;
				else
					pSolarSysState->SysInfo.PlanetInfo.CurType = 1;
				pSolarSysState->CurNode = 1;
				if (pSolarSysState->SysInfo.PlanetInfo.ScanRetrieveMask[ENERGY_SCAN]
						& (1L << 0))
				{
					pSolarSysState->SysInfo.PlanetInfo.ScanRetrieveMask[ENERGY_SCAN]
							&= ~(1L << 0);

					if (!GET_GAME_STATE (PORTAL_KEY))
					{
						((PPLANETSIDE_DESC)pMenuState->ModuleFrame)->InTransit = TRUE;

						SET_GAME_STATE (PORTAL_KEY, 1);
						SET_GAME_STATE (PORTAL_KEY_ON_SHIP, 1);
					}
				}

				SeedRandom (old_rand);
				break;
			}
			pSolarSysState->CurNode = 0;
			break;
		case GENERATE_ORBITAL:
			if (pSolarSysState->pOrbitalDesc == &pSolarSysState->PlanetDesc[6])
			{
				pSolarSysState->SysInfo.PlanetInfo.LanderFont =
						CaptureFont (
								LoadGraphic (LANDER_FONT)
								);
				pSolarSysState->PlanetSideFrame[1] =
						CaptureDrawable (
								LoadGraphic (WRECK_MASK_PMAP_ANIM)
								);
				pSolarSysState->SysInfo.PlanetInfo.DiscoveryString =
						CaptureStringTable (
								LoadStringTable (WRECK_STRTAB)
								);
				if (GET_GAME_STATE (PORTAL_KEY))
					pSolarSysState->SysInfo.PlanetInfo.DiscoveryString =
							SetAbsStringTableIndex (
							pSolarSysState->SysInfo.PlanetInfo.DiscoveryString,
							1
							);
			}
		default:
			GenerateRandomIP (control);
			break;
	}
}