Esempio n. 1
0
void WorldInit()
{
	TimeSeedGenerator();
	DisplayInit();
	InitGame();
	LoadGame("Scenarios\\default.xml");
}
bool CCheckpointSystem::LoadLastCheckpoint()
{
	if(!g_lastSavedCheckpoint.empty())
		return LoadGame(g_lastSavedCheckpoint.c_str());
	CryWarning(VALIDATOR_MODULE_GAME, VALIDATOR_WARNING, "Can't load latest checkpoint : no recent checkpoint found!");
	return false;
}
Esempio n. 3
0
// Main Function
int main()
{
    //Local Variables
    int gameMode = -1; //declaration
    
    //Print Welcome
    printf("Welcome...Would you like to play a game? (use 0 - 9))\n");
    
    //Select Game mode
    while (gameMode != 0)
    {
        //Input Game to play
        scanf("%d",&gameMode);
        if(gameMode != 0){
            
            printf("There is only 1 game right now... Please type 0 to play the game...\n\n");
            
        }
    }
    
    //Load Game
    LoadGame(gameMode);
    
    //Begin Playing
    Play();
    
    return 0;
    
}
void start_menu()
{
	printf("Menu:\n");
	printf("1. New Game\n");
	printf("2. Load Game\n");
	printf("Pilihan: ");
	int pilihan;
	read_with_limit(1, 2, &pilihan);
	if (pilihan == 1)
	{
		printf("Num of Player? ");
		read_with_limit(1, PLAYER_MAX, &pilihan);
		NewGame(pilihan);
		gamesystem_start();
	}
	else
	{
		Kata input;
		do
		{
			printf("Masukan kata kunci yang dipakai saat save game : "); BacaKata(&input);
			LoadGame(input);

		}while (FirstPetak(global.listOfPetak) == Nil);
		
		gamesystem_start();
	}
}
Esempio n. 5
0
static int GetInput(int *vb, int *no)
{
	char buf[256];
	char verb[10],noun[10];
	int vc,nc;
	int num;

	do
	{
		do
		{
			Output("\nTell me what to do ? ");
			LineInput(buf, sizeof buf);
			num=sscanf(buf,"%9s %9s",verb,noun);
		}
		while(num==0||*buf=='\n');
		if(xstrcasecmp(verb, "restore") == 0)
		{
			LoadGame();
			return -1;
		}
		if(num==1)
			*noun=0;
		if(*noun==0 && strlen(verb)==1)
		{
			switch(isupper(*verb)?tolower(*verb):*verb)
			{
				case 'n':strcpy(verb,"NORTH");break;
				case 'e':strcpy(verb,"EAST");break;
				case 's':strcpy(verb,"SOUTH");break;
				case 'w':strcpy(verb,"WEST");break;
				case 'u':strcpy(verb,"UP");break;
				case 'd':strcpy(verb,"DOWN");break;
				/* Brian Howarth interpreter also supports this */
				case 'i':strcpy(verb,"INVENTORY");break;
			}
		}
		nc=WhichWord(verb,Nouns);
		/* The Scott Adams system has a hack to avoid typing 'go' */
		if(nc>=1 && nc <=6)
		{
			vc=1;
		}
		else
		{
			vc=WhichWord(verb,Verbs);
			nc=WhichWord(noun,Nouns);
		}
		*vb=vc;
		*no=nc;
		if(vc==-1)
		{
			Output("You use word(s) I don't know! ");
		}
	}
	while(vc==-1);
	strcpy(NounText,noun);	/* Needed by GET/DROP hack */

	return 0;
}
Esempio n. 6
0
void RunGame( int load) {
    game g = NULL;
    if(load) {
        g = LoadGame();
    } else {
        g = NewGame();
    }
    if(g==NULL) {
        return;
    }
    wrefresh(g->arena);
    wrefresh(g->status);
    if(g!=NULL) {
        if(g->pc) g->print(g->pc);
        creature G = CreateCreature(g);
        G = g->ZombieListHead;
        while(G) {
            g->print(G->Character);
            G = G->Next;
        }
        PrintAllBuildings(g->gameMap, g->pc->pos);
        PlayLoop(g);
        if(G) {
            PurgeCreatureNode(G);
            DESTROY(G);
        }
        PurgeGame(g);
        DESTROY(g);
    }
}
Esempio n. 7
0
///=====================================================
/// 
///=====================================================
void Game::UpdateMainMenuState(OpenGLRenderer* renderer){
	if (s_theInputSystem->GetKeyWentDown('Q') || s_theInputSystem->GetKeyWentDown(VK_ESCAPE)){
		m_isRunning = false;
	}
	else if (s_theInputSystem->GetKeyWentDown('N')){ //go to Quest
		SetState(Quest);
		m_titleRenderer.ClearText();
		m_titleRenderer.PrintText("Quests");

		if (m_autoGenerateMap)
			m_bottomMessageRenderer.PrintText("AutoGenerate: ON", RGBAchars::GREEN);
		else
			m_bottomMessageRenderer.PrintText("AutoGenerate: OFF", RGBAchars::RED);

		m_menuRenderer.ToggleRenderFromCenter();
		m_menuRenderer.ClearText();

		const MapGeneratorRegistry* registry = MapGeneratorRegistration::GetGeneratorRegistry();
		char firstQuestLetter = 'A';

		for (MapGeneratorRegistry::const_iterator registryIter = registry->cbegin(); registryIter != registry->cend(); ++registryIter){
			std::string temp = ") ";
			temp = firstQuestLetter + temp;
			m_menuRenderer.PrintText(temp + registryIter->first);
			++firstQuestLetter;
		}
	}
	else if (s_theInputSystem->GetKeyWentDown('L')){ //load game
		LoadGame(renderer);

		m_titleRenderer.ClearText();
		m_titleRenderer.PrintText("Playing");

		m_menuRenderer.ToggleRenderFromCenter();
		m_menuRenderer.ClearText();

		if (m_autoGenerateMap){
			m_bottomMessageRenderer.PrintText("AutoGenerate: ON", RGBAchars::GREEN);
		}
		else{
			m_bottomMessageRenderer.PrintText("AutoGenerate: OFF", RGBAchars::RED);
		}

		char firstQuestLetter = 'A';
		const MapGeneratorRegistry* registry = MapGeneratorRegistration::GetGeneratorRegistry();

		for (MapGeneratorRegistry::const_iterator registryIter = registry->cbegin(); registryIter != registry->cend(); ++registryIter){
			std::string temp = ") ";
			temp = firstQuestLetter + temp;
			m_menuRenderer.PrintText(temp + registryIter->first);
			++firstQuestLetter;
		}

		m_messageBar.m_isWaitingForPlayer = false;
		m_messageBar.m_text.clear();
	}
}
Esempio n. 8
0
void CTileEngine::AdditionalInit()
{
	SetTitle( "TileEngine - Loading..." );
	g_pGame = new CGame;
    LoadGame( "Media/TestTile.xml" );
    g_pGame->SetViewPoint(36,19);
    g_pGame->SetViewSize(3 * tileSizeX, 16 * tileSizeY);
	SetTitle( "TileEngine" );
}
Esempio n. 9
0
void GameDatabase::InitializeDatabase()
{
	// Reset the array of game IDs
	mGames.clear();
	mOffsets.clear();
	
	// Make sure the database exists.
	wxString path = FilePath::Data(DataFileGameKeys);
	if(FALSE == wxFileExists(path))
	{
		return;
	}

	// Read in keys.
	wxFile keydb;
	keydb.Open(path);
	wxFileInputStream y(keydb);
	wxDataInputStream keys(y);

	//sanity
	if(false == keydb.IsOpened())
	{
		return;
	}

	// Calculate how many games there are.
	size_t size = keydb.Length() / sizeof(size_t);

	mOffsets.resize(size);

	// Read them in.
	for(size_t i = 0; i < size; i++)
	{
		keys >> mOffsets[i];
	}

	struct FakeSerialize : public ISerialize
	{
		void load(wxDataInputStream &stream) {}
		void save(wxDataOutputStream &stream) const {}
	};

	FakeSerialize serialize;

	// Now actually read all the game IDs.
	for(size_t i = 0; i < size; i++)
	{
		Game game;

		LoadGame(i, game, GameObjectEnginePtr(), serialize);
		
		mGames.push_back(game.read<wxInt32>(shID));
	}
}
Esempio n. 10
0
void StartSavedGame(const std::string &filename)
{
	std::string path;

	SaveGameLoading = true;
	CleanPlayers();
	ExpandPath(path, filename);
	LoadGame(path);

	StartMap(filename, false);
	//SetDefaultTextColors(nc, rc);
}
Esempio n. 11
0
static void
GL_Button (int n)
{
    int index;
    n = gamesOptions[n].value; // use marker in option rather than n itself, for more easy adding/deletng of buttons
    if (n == 6) { // close
	PopDown(GameListDlg);
	return;
    }
    if (n == 3) { // thresholds
	LoadOptionsPopUp(GameListDlg);
	return;
    }
    if (n == 9) { // tags
	GameListOptionsPopUp(GameListDlg);
	return;
    }
    index = SelectedListBoxItem(&gamesOptions[0]);
    if (n == 7) { // load
	if (index < 0) {
	    DisplayError(_("No game selected"), 0);
	    return;
	}
    } else if (n == 5) { // next
	index++;
	if (index >= listLength || !list[index]) {
	    DisplayError(_("Can't go forward any further"), 0);
	    return;
	}
	HighlightWithScroll(&gamesOptions[0], index, listEnd);
    } else if (n == 8) { // prev
	index--;
	if (index < 0) {
	    DisplayError(_("Can't back up any further"), 0);
	    return;
	}
	HighlightWithScroll(&gamesOptions[0], index, listEnd);
    } else if (n == 2 || // narrow
               n == 4) { // find position
	char *text;
	GetWidgetText(&gamesOptions[1], &text);
        safeStrCpy(filterString, text, sizeof(filterString)/sizeof(filterString[0]));
        GameListPrepare(True, n == 2); GameListReplace(0);
        return;
    }

    index = atoi(list[index])-1; // [HGM] filter: read true index from sequence nr of line
    if (cmailMsgLoaded) {
	CmailLoadGame(glc->fp, index + 1, glc->filename, True);
    } else {
	LoadGame(glc->fp, index + 1, glc->filename, True);
    }
}
Esempio n. 12
0
File: he.c Progetto: 0branch/hugor
int he_main(int argc, char *argv[])
#endif
{
	time_t seed;

	my_argv = argv;

	if (!strcmp(program_path, "") && argv) MakeProgramPath(argv[0]);

	/* Seed the random number generator */
#if !defined (RANDOM)
	srand((unsigned int)time((time_t *)&seed));
#else
	SRANDOM((unsigned int)time((time_t *)&seed));
#endif

#if !defined (GLK)	/* no command line under Glk */
	ParseCommandLine(argc, argv);
#endif

	hugo_init_screen();

#if defined (DEBUGGER)
	debug_getinvocationpath(argv[0]);
	SwitchtoGame();
#endif
	SetupDisplay();

	strcpy(pbuffer, "");

	gameseg = 0;

	LoadGame();

#if defined (DEBUGGER)
	LoadDebuggableFile();
	StartDebugger();
#endif

	RunGame();

	hugo_cleanup_screen();

	hugo_blockfree(mem);
	mem = NULL;
	hugo_closefiles();

	return 0;
}
/*
==============
idSessionLocal::HandleRestartMenuCommands

Executes any commands returned by the gui
==============
*/
void idSessionLocal::HandleRestartMenuCommands(const char *menuCommand)
{
	// execute the command from the menu
	int icmd;
	idCmdArgs args;

	args.TokenizeString(menuCommand, false);

	for (icmd = 0; icmd < args.Argc();) {
		const char *cmd = args.Argv(icmd++);

		if (HandleSaveGameMenuCommand(args, icmd)) {
			continue;
		}

		if (!idStr::Icmp(cmd, "restart")) {
			if (!LoadGame(GetAutoSaveName(mapSpawnData.serverInfo.GetString("si_map")))) {
				// If we can't load the autosave then just restart the map
				MoveToNewMap(mapSpawnData.serverInfo.GetString("si_map"));
			}

			continue;
		}

		if (!idStr::Icmp(cmd, "quit")) {
			ExitMenu();
			common->Quit();
			return;
		}

		if (!idStr::Icmp(cmd, "exec")) {
			cmdSystem->BufferCommandText(CMD_EXEC_APPEND, args.Argv(icmd++));
			continue;
		}

		if (!idStr::Icmp(cmd, "play")) {
			if (args.Argc() - icmd >= 1) {
				idStr snd = args.Argv(icmd++);
				sw->PlayShaderDirectly(snd);
			}

			continue;
		}
	}
}
Esempio n. 14
0
int main(int argc, char **argv)
{
	printf("Level 9 Interpreter\n\n");
	if (argc != 2)
	{
		printf("Use: %s <gamefile>\n",argv[0]);
		return 0;
	}
	if (!LoadGame(argv[1],NULL))
	{
		printf("Error: Unable to open game file\n");
		return 0;
	}
	while (RunGame());
	StopGame();
	FreeMemory();
	return 0;
}
Esempio n. 15
0
static int
LoadGamePopUp (FILE *f, int gameNumber, char *title)
{
    cmailMsgLoaded = FALSE;
    if (gameNumber == 0) {
	int error = GameListBuild(f);
	if (error) {
	    DisplayError(_("Cannot build game list"), error);
	} else if (!ListEmpty(&gameList) &&
		   ((ListGame *) gameList.tailPred)->number > 1) {
	    GameListPopUp(f, title);
	    return TRUE;
	}
	GameListDestroy();
	gameNumber = 1;
    }
    return LoadGame(f, gameNumber, title, FALSE);
}
Esempio n. 16
0
//Program waits for the user to press one of the following keys
void MainMenuKey()
{
	while (true)
	{
		if (_kbhit())
		{
			char mainMenuKey = _getch();
			switch (mainMenuKey)
			{
				case NEW_GAME_CHAR:
					PicksDwarfProperties();
					break;
				case LOAD_CHAR:
					LoadGame();
					break;
				case OPTIONS_CHAR:
					Options();
					break;
				case FAME_CHAR:
					HallOfFame();
					break;
				case CREDITS_CONTINUE_CHAR:
					Credits();
					break;
				case INSTRUCTIONS_CHAR:
					Instructions();
					break;
				case QUIT_CHAR:
					quit = true;
					break;
				default:
					toBreak = false;
			}
			if (toBreak)
			{
				break;
			}
			else
			{
				toBreak = true;
			}
		}
	}
}
Esempio n. 17
0
void Game::UpdateTitle(float dt) {
  _titleScreen->Update(dt);

  if(!_titleScreen->IsAlive()) {
    switch(_titleScreen->GetResult()) {
    case TitleScreen::NEW_GAME:
      NewGame();
      break;

    case TitleScreen::LOAD_GAME:
      LoadGame();
      break;

    case TitleScreen::QUIT:
      Quit();
      break;
    }
  }
}
Esempio n. 18
0
void		Engine::play()
{
  while (mode != QUIT && engine->hasScreen())
    switch (mode)
      {
      case START:
	Animation();
	break;
      case MENU:
	Menu();
	break;
      case GAME:
	Game();
	break;
      case MENU_GAME:
	MenuInGame();
	break;
      case LOAD:
	LoadSave();
	break;
      case SAVE:
	SaveGame();
	break;
      case NEW_GAME:
	LoadGame();
	break;
      case LAUNCH_GAME:
	NewGame();
	break;
      case OPTION_MENU:
	OptionMenu();
	break;
      case OPTION_GAME:
	MenuInGame();
	break;
      case HIGHSCORE:
	Highscore();
	break;
      default:
	mode = QUIT;
      }
}
void SinglePlayerBattle::SendHostInfo(HostInfo update)
{
	if ((update & HI_StartType) != 0)
		m_sptab.UpdateMinimap();
	if ((update & HI_Restrictions) != 0)
		m_sptab.ReloadRestrictions();
	if ((update & HI_Map_Changed) != 0) {
		LoadMap();
		m_sptab.ReloadMapOptContrls();
	}
	if ((update & HI_Game_Changed) != 0) {
		RemoveUnfittingBots();
		LoadGame();
		wxString presetname = sett().GetModDefaultPresetName(TowxString(GetHostGameName()));
		if (!presetname.IsEmpty()) {
			LoadOptionsPreset(STD_STRING(presetname));
			SendHostInfo(HI_Send_All_opts);
		}
		m_sptab.ReloadModOptContrls();
	}
}
Esempio n. 20
0
// Main menu commands
static int load_rom() {
	const char *types[] = { ".nes", ".fds", ".zip", ".fcm", ".fm2", ".nsf",
			NULL };
	char filename[128], romname[128];
	int error;

	#ifdef DINGUX_ON_WIN32
	if (!RunFileBrowser("d:\\", filename, types)) {
	#else
	if (!RunFileBrowser(NULL, filename, types)) {
	#endif
		CloseGame();
		SDL_Quit();
		exit(-1);
	}

	//  TODO - Must close game here?
	CloseGame();

	// Is this a movie?
	if (!(error = FCEUD_LoadMovie(filename, romname)))
		error = LoadGame(filename);

	if (error != 1) {
		CloseGame();
		SDL_Quit();
		exit(-1);
	}

	return 1;
}

static int reset_nes() {
	FCEUI_ResetNES();
	return 1;
}
Esempio n. 21
0
bool MainPanel::OnList(ListPop *list, int index, gedString &text, int listId)
{
	if(listEditBox) 
	{
		delete listEditBox;
		listEditBox = NULL;
	}

	switch(listId)
	{
	case LS_FILE:
		{			
			if(text == "New Game")
			{
				/*<Odilon>
				  Verifica se nao foi feito nada, ainda, para
				  pedir confirmacao apenas se necessario.
				*/
				
				if (GameControl::Get()->Modified())
				{
					//<Odilon> Pequena correcao de Ingles...
					PanelQuestion *panel = new PanelQuestion("This will discard the current game.\nProceed anyway?");
					///PanelQuestion *panel = new PanelQuestion("This action will erase the current game.\nTo proceed?");
					
					if(panel->Wait() == OK_BUTTON)
					{
						GameControl::Get()->NewGame();
						UndoControl::Get()->Clear();
						lastScripts.Clear();

						
						ExportGame::ClearExportName();
						
						/*Close actor dialog*/
						ActorProperty::Destroy();
					}
					
					delete panel;
					
				}
				else  //nao eh necessario confirmar; nada foi feito.
				{
					/* Aqui estou repetindo o mesmo codigo acima,...
					   talvez seja melhor encontrar outra maneira de fazer isso,
					   ou talvez nao... */
			
					GameControl::Get()->NewGame();
					UndoControl::Get()->Clear();
					lastScripts.Clear();

					/*Close actor dialog*/
					ActorProperty::Destroy();
				}
				
			}
			else if(text == "Load")
			{
				new LoadSaveGame(LOAD_GAME);

				ExportGame::ClearExportName();
				
			}
			else if(text == "Merge")
			{
				new LoadSaveGame(MERGE_GAME);
			}
#ifdef USE_SYSTEM_FILE_DIALOG
			else if(text == "Save As...")
			{
				new LoadSaveGame(SAVE_GAME);
				ExportGame::ClearExportName();
			}
			else if(text == "Save")
			{
				if(Tutorial::IsOff())
				{
					gedString gamePath(GameControl::Get()->getGamePath());

					if(!gamePath.empty())
					{
						LoadSaveGame::Save(gamePath + DIR_SEP + GameControl::Get()->getGameName());
					}
					else
					{
						new LoadSaveGame(SAVE_GAME);
					}
				}
				else
				{
					new LoadSaveGame(SAVE_GAME);
				}
			}
#else
			else if(text == "Save")
			{
				new LoadSaveGame(SAVE_GAME);
			}
#endif			
			else if(text == "Export")
			{
				#ifdef GAME_EDITOR_PROFESSIONAL

				if(GenericScript::ParserAll())
				{
					new ExportGame();
				}
				else
				{
					new PanelInfo(GenericScript::GetError(), "Error", ALIGN_LEFT);
				}
				
				#else 
				new PanelInfo(GAME_EDITOR_VERSION_ERROR);
				#endif
			}
			else if(text == "Exit")
			{
				//Exit
				SDL_Event event;
				memset(&event, 0, sizeof(SDL_Event));
				event.quit.type = SDL_QUIT;
				SDL_PushEvent(&event);
			}
			else
			{
				//Recent file list
				gedString *sFile = (gedString *)listFile->GetItemData(index);
				if(sFile)
				{
					LoadGame(*sFile, true);
				}
			}		
		}
		break;
	case LS_SETTINGS:
		{
			if(text == "Game Properties")
			{
				new GameSettings();
			}
			else if(text == "Preferences")
			{
				new Preferences();
			}
			else if(text == "Disable Tool Tips")
			{
				Config::Get()->setEnableToolTips(false);
				
				gedString *pEnableDisableToolTips = listConfig->GetTextPtr("Disable Tool Tips");
				if(pEnableDisableToolTips)
				{
					*pEnableDisableToolTips = "Enable Tool Tips";
				}
			}
			else if(text == "Enable Tool Tips")
			{
				Config::Get()->setEnableToolTips(true);
				
				gedString *pEnableDisableToolTips = listConfig->GetTextPtr("Enable Tool Tips");
				if(pEnableDisableToolTips)
				{
					*pEnableDisableToolTips = "Disable Tool Tips";
				}
			}
		}
		break;
	case LS_REGIONS:
		{
			switch(index)
			{
			case 0: //Add Activation Region
#if !defined(GAME_EDITOR_HOME_EDITION)
				new RegionLoad();	
#else
				new PanelInfo(GAME_EDITOR_VERSION_ERROR);
				return true;
#endif
				break;
			case 1: //show/hide
				
				if(RegionLoad::getShowRegions())
				{
					*pShowHideRegions = "Show Regions";
				}
				else
				{
					*pShowHideRegions = "Hide Regions";
				}

				RegionLoad::ToggleVisibility();
				Actor::RegionActorToggleVisibility();
				break;
			}
		}
		break;
	case LS_HELP:
		{
			if(text == "Documentation")
			{
				EditorDirectory editDir;
				
				//Firefox don't open "Docs/index.html" in windows
				//So, use \ on windows and / on linux
			
				openUrl((
#if defined(__MACOSX__)
		gedString("file://")+	GameControl::Get()->getHomePath()+gedString("/")+		 
#endif
						 
						 gedString("Docs") + DIR_SEP + "index.html").c_str());
			}
			else if(text == "About...")
			{
				new AboutDlg();
			}
			else if(text == "User Forums...")
			{
				openUrl("http://game-editor.com/forum");
			}	
#if !defined(__MACOSX__)
			else if(text == "Get Newest Tutorials...")
			{
				TutorialUpdateDlg::Call();
			}
			else if(text == "Check for Updates...")
			{
				UpdateCheck();
			}
#endif // No check for updates outside MACOSX appstore due to apple guidelines
			else if(text == "Game Demos...")
			{
				openUrl("http://game-editor.com/demos.html");				
			}
			else
			{
				//Tutorials
				if(chdir((GameControl::getEditorPath() + DIR_SEP + "Tutorials" + DIR_SEP + text).c_str()) == 0)
				{				
					listTutorialDir->RemoveAll();
					listTutorialDir->getImage()->SetVisible(true);				
					PostMessage(this, 0);
				}
			}
		}
		break;
	case LS_TUTORIALDIR:
		{		
			PanelQuestion *panel = new PanelQuestion("This will discard the current game.\nProceed anyway?", "Tutorial Execution");
			if(panel->Wait() == OK_BUTTON)
			{
				PostMessage(this, 1);					
			}

			delete panel;	
			
		}
		break;

	case LS_EDIT_MENU:
		{
			switch(index)
			{
			case 0:
				editBoxWidget->Cut();
				break;

			case 1:
				editBoxWidget->Copy();
				break;

			case 2:
				editBoxWidget->Paste();
				break;
			}			
		}
		break;

	case LS_SCRIPT:
		{
			if(text == "Global code")
			{
				new ScriptGlobals();
			}
			else
			{
				stAction *action = (stAction *)list->GetItemData(index);
				gedString actorName(text.substr(0, text.find(' ')));

				Actor *actor = GameControl::Get()->GetActor(actorName);								

				if(actor && action)
				{
					AddLastScript(text);
					Action::ShowActionDialog(action, actor);			
				}
			}
		}
		break;
	}

	return true;
}
Esempio n. 22
0
/**
 * The main loop for the SDL.
 */
int main(int argc, char *argv[])
{
  // this is a hackish check for the --help arguemnts
  // these are normally processed by the config parser, but SDL_Init
  // must be run before the config parser: so if even SDL_Init fails,
  // these six lines will still print the help output
	if(argc > 1)
	{
		if(!strcmp(argv[1], "--help") || !strcmp(argv[1],"-h"))
		{
            ShowUsage(argv[0]);
			return 0;
		}
	}

	int error, frameskip;

	FCEUD_Message("Starting " FCEU_NAME_AND_VERSION "...\n");

#ifdef WIN32
	/* Taken from win32 sdl_main.c */
	SDL_SetModuleHandle(GetModuleHandle(NULL));
#endif

	/* SDL_INIT_VIDEO Needed for (joystick config) event processing? */
	if(SDL_Init(SDL_INIT_VIDEO)) {
		printf("Could not initialize SDL: %s.\n", SDL_GetError());
		return(-1);
	}

#ifdef OPENGL
	SDL_GL_LoadLibrary(0);
#endif

	// Initialize the configuration system
	g_config = InitConfig();
		
	if(!g_config) {
		SDL_Quit();
		return -1;
	}

	// initialize the infrastructure
	error = FCEUI_Initialize();
	if(error != 1) {
		ShowUsage(argv[0]);
		SDL_Quit();
		return -1;
	}
	
	// check for --help or -h and display usage; also check for --nogui
	for(int i=0; i<argc;i++)
	{
		if(strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0)
		{
			ShowUsage(argv[0]);
			SDL_Quit();
			return 0;
		}
#ifdef _GTK
		else if(strcmp(argv[i], "--nogui") == 0)
		{
			noGui = 1;
			argv[i] = "";
		}
#endif
	}
	int romIndex = g_config->parse(argc, argv);

	// This is here so that a default fceux.cfg will be created on first
	// run, even without a valid ROM to play.
	// Unless, of course, there's actually --no-config given
	// mbg 8/23/2008 - this is also here so that the inputcfg routines can have 
    // a chance to dump the new inputcfg to the fceux.cfg  in case you didnt 
    // specify a rom  filename
	g_config->getOption("SDL.NoConfig", &noconfig);
	if (!noconfig)
		g_config->save();
	
	std::string s;

	g_config->getOption("SDL.InputCfg", &s);
	if(s.size() != 0)
	{
	InitVideo(GameInfo);
	InputCfg(s);
	}
	// set the FAMICOM PAD 2 Mic thing 
	{
	int t;
	g_config->getOption("SDL.Input.FamicomPad2.EnableMic", &t);
		if(t)
			replaceP2StartWithMicrophone = t;
	}

    // update the input devices
	UpdateInput(g_config);

	// check for a .fcm file to convert to .fm2
	g_config->getOption ("SDL.FCMConvert", &s);
	g_config->setOption ("SDL.FCMConvert", "");
	if (!s.empty())
	{
		int okcount = 0;
		std::string infname = s.c_str();
		// produce output filename
		std::string outname;
		size_t dot = infname.find_last_of (".");
		if (dot == std::string::npos)
			outname = infname + ".fm2";
		else
			outname = infname.substr(0,dot) + ".fm2";
	  
		MovieData md;
		EFCM_CONVERTRESULT result = convert_fcm (md, infname);

		if (result == FCM_CONVERTRESULT_SUCCESS) {
			okcount++;
        // *outf = new EMUFILE;
		EMUFILE_FILE* outf = FCEUD_UTF8_fstream (outname, "wb");
		md.dump (outf,false);
		delete outf;
		FCEUD_Message ("Your file has been converted to FM2.\n");
	}
	else {
		FCEUD_Message ("Something went wrong while converting your file...\n");
	}
	  
	DriverKill();
	  SDL_Quit();
	  return 0;
	}

	// If x/y res set to 0, store current display res in SDL.LastX/YRes
	int yres, xres;
	g_config->getOption("SDL.XResolution", &xres);
	g_config->getOption("SDL.YResolution", &yres);
#if SDL_VERSION_ATLEAST(2, 0, 0)
	// TODO _ SDL 2.0
#else
	const SDL_VideoInfo* vid_info = SDL_GetVideoInfo();
	if(xres == 0) 
    {
        if(vid_info != NULL)
        {
			g_config->setOption("SDL.LastXRes", vid_info->current_w);
        }
        else
        {
			g_config->setOption("SDL.LastXRes", 512);
        }
    }
	else
	{
		g_config->setOption("SDL.LastXRes", xres);
	}	
    if(yres == 0)
    {
        if(vid_info != NULL)
        {
			g_config->setOption("SDL.LastYRes", vid_info->current_h);
        }
        else
        {
			g_config->setOption("SDL.LastYRes", 448);
        }
    } 
	else
	{
		g_config->setOption("SDL.LastYRes", yres);
	}
#endif
	
	int autoResume;
	g_config->getOption("SDL.AutoResume", &autoResume);
	if(autoResume)
	{
		AutoResumePlay = true;
	}
	else
	{
		AutoResumePlay = false;
	}
	// check to see if recording HUD to AVI is enabled
	int rh;
	g_config->getOption("SDL.RecordHUD", &rh);
	if( rh == 0)
		FCEUI_SetAviEnableHUDrecording(true);
	else
		FCEUI_SetAviEnableHUDrecording(false);

	// check to see if movie messages are disabled
	int mm;
	g_config->getOption("SDL.MovieMsg", &mm);
	if( mm == 0)
		FCEUI_SetAviDisableMovieMessages(true);
	else
		FCEUI_SetAviDisableMovieMessages(false);
	
	
	// check for a .fm2 file to rip the subtitles
	g_config->getOption("SDL.RipSubs", &s);
	g_config->setOption("SDL.RipSubs", "");
	if (!s.empty())
	{
		MovieData md;
		std::string infname;
		infname = s.c_str();
		FCEUFILE *fp = FCEU_fopen(s.c_str(), 0, "rb", 0);
		
		// load the movie and and subtitles
		extern bool LoadFM2(MovieData&, EMUFILE*, int, bool);
		LoadFM2(md, fp->stream, INT_MAX, false);
		LoadSubtitles(md); // fill subtitleFrames and subtitleMessages
		delete fp;
		
		// produce .srt file's name and open it for writing
		std::string outname;
		size_t dot = infname.find_last_of (".");
		if (dot == std::string::npos)
			outname = infname + ".srt";
		else
			outname = infname.substr(0,dot) + ".srt";
		FILE *srtfile;
		srtfile = fopen(outname.c_str(), "w");
		
		if (srtfile != NULL)
		{
			extern std::vector<int> subtitleFrames;
			extern std::vector<std::string> subtitleMessages;
			float fps = (md.palFlag == 0 ? 60.0988 : 50.0069); // NTSC vs PAL
			float subduration = 3; // seconds for the subtitles to be displayed
			for (int i = 0; i < subtitleFrames.size(); i++)
			{
				fprintf(srtfile, "%i\n", i+1); // starts with 1, not 0
				double seconds, ms, endseconds, endms;
				seconds = subtitleFrames[i]/fps;
				if (i+1 < subtitleFrames.size()) // there's another subtitle coming after this one
				{
					if (subtitleFrames[i+1]-subtitleFrames[i] < subduration*fps) // avoid two subtitles at the same time
					{
						endseconds = (subtitleFrames[i+1]-1)/fps; // frame x: subtitle1; frame x+1 subtitle2
					} else {
						endseconds = seconds+subduration;
							}
				} else {
					endseconds = seconds+subduration;
				}
				ms = modf(seconds, &seconds);
				endms = modf(endseconds, &endseconds);
				// this is just beyond ugly, don't show it to your kids
				fprintf(srtfile,
				"%02.0f:%02d:%02d,%03d --> %02.0f:%02d:%02d,%03d\n", // hh:mm:ss,ms --> hh:mm:ss,ms
				floor(seconds/3600),	(int)floor(seconds/60   ) % 60, (int)floor(seconds)	% 60, (int)(ms*1000),
				floor(endseconds/3600), (int)floor(endseconds/60) % 60, (int)floor(endseconds) % 60, (int)(endms*1000));
				fprintf(srtfile, "%s\n\n", subtitleMessages[i].c_str()); // new line for every subtitle
			}
		fclose(srtfile);
		printf("%d subtitles have been ripped.\n", (int)subtitleFrames.size());
		} else {
		FCEUD_Message("Couldn't create output srt file...\n");
		}
	  
		DriverKill();
		SDL_Quit();
		return 0;
	}
   

	// if we're not compiling w/ the gui, exit if a rom isn't specified
#ifndef _GTK
	if(romIndex <= 0) {
		
		ShowUsage(argv[0]);
		FCEUD_Message("\nError parsing command line arguments\n");
		SDL_Quit();
		return -1;
	}
#endif
	

	// update the emu core
	UpdateEMUCore(g_config);

	
	#ifdef CREATE_AVI
	g_config->getOption("SDL.VideoLog", &s);
	g_config->setOption("SDL.VideoLog", "");
	if(!s.empty())
	{
		NESVideoSetVideoCmd(s.c_str());
		LoggingEnabled = 1;
		g_config->getOption("SDL.MuteCapture", &mutecapture);
	} else {
		mutecapture = 0;
	}
	#endif

	{
		int id;
		g_config->getOption("SDL.InputDisplay", &id);
		extern int input_display;
		input_display = id;
		// not exactly an id as an true/false switch; still better than creating another int for that
		g_config->getOption("SDL.SubtitleDisplay", &id); 
		extern int movieSubtitles;
		movieSubtitles = id;
	}
	
	// load the hotkeys from the config life
	setHotKeys();

#ifdef _GTK
	if(noGui == 0)
	{
		gtk_init(&argc, &argv);
		InitGTKSubsystem(argc, argv);
		while(gtk_events_pending())
			gtk_main_iteration_do(FALSE);
	}
#endif

  if(romIndex >= 0)
	{
		// load the specified game
		error = LoadGame(argv[romIndex]);
		if(error != 1) {
			DriverKill();
			SDL_Quit();
			return -1;
		}
		g_config->setOption("SDL.LastOpenFile", argv[romIndex]);
		g_config->save();

	}
	
	// movie playback
	g_config->getOption("SDL.Movie", &s);
	g_config->setOption("SDL.Movie", "");
	if (s != "")
	{
		if(s.find(".fm2") != std::string::npos || s.find(".fm3") != std::string::npos)
		{
			static int pauseframe;
			g_config->getOption("SDL.PauseFrame", &pauseframe);
			g_config->setOption("SDL.PauseFrame", 0);
			FCEUI_printf("Playing back movie located at %s\n", s.c_str());
			FCEUI_LoadMovie(s.c_str(), false, pauseframe ? pauseframe : false);
		}
		else
		{
		  FCEUI_printf("Sorry, I don't know how to play back %s\n", s.c_str());
		}
	}
	
    int periodic_saves;
    int save_state;
    g_config->getOption("SDL.PeriodicSaves", &periodic_saves);
    g_config->getOption("SDL.AutoSaveState", &save_state);
    if(periodic_saves && save_state < 10 && save_state >= 0){
        FCEUI_SelectState(save_state, 0);
    } else {
        periodic_saves = 0;
    }
	
#ifdef _S9XLUA_H
	// load lua script if option passed
	g_config->getOption("SDL.LuaScript", &s);
	g_config->setOption("SDL.LuaScript", "");
	if (s != "")
	{
		FCEU_LoadLuaCode(s.c_str());
	}
#endif
	
	{
		int id;
		g_config->getOption("SDL.NewPPU", &id);
		if (id)
			newppu = 1;
	}

	g_config->getOption("SDL.Frameskip", &frameskip);
	// loop playing the game
#ifdef _GTK
	if(noGui == 0)
	{
		while(1)
		{
			if(GameInfo)
				DoFun(frameskip, periodic_saves);
			else
				SDL_Delay(1);
			while(gtk_events_pending())
			gtk_main_iteration_do(FALSE);
		}
	}
	else
	{
		while(GameInfo)
			DoFun(frameskip, periodic_saves);
	}
#else
	while(GameInfo)
	{
		DoFun(frameskip, periodic_saves);
	}
#endif
	CloseGame();

	// exit the infrastructure
	FCEUI_Kill();
	SDL_Quit();
	return 0;
}
Esempio n. 23
0
LRESULT CALLBACK WndProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	switch(Message)
	{
	case WM_INITMENU:
		recentromsmenu = LoadMenu(g_hInstance, "RECENTROMS");
		GetRecentRoms();
		break;
	case WM_KEYDOWN:
		if(wParam != VK_PAUSE)
			break;
		// case WM_SYSKEYDOWN:
	case WM_CUSTKEYDOWN:
		{
			int modifiers = GetModifiers(wParam);
			if(!HandleKeyMessage(wParam,lParam, modifiers))
				return 0;
			break;
		}
	case WM_KEYUP:
		if(wParam != VK_PAUSE)
			break;
	case WM_SYSKEYUP:
	case WM_CUSTKEYUP:
		{
			int modifiers = GetModifiers(wParam);
			HandleKeyUp(wParam, lParam, modifiers);
		}
		break;
	case WM_SIZE:
		switch(wParam)
		{
		case SIZE_MINIMIZED:
			break;
		case SIZE_MAXIMIZED:
			pcejin.maximized = true;
			break;
		case SIZE_RESTORED:
			pcejin.maximized = false;
			break;
		default:
			break;
		}
		return 0;
	case WM_MOVE:
		RECT rect;
		GetWindowRect(hWnd,&rect);
		WndX = rect.left;
		WndY = rect.top;
		return 0;
	case WM_DROPFILES:
		{
			char filename[MAX_PATH] = "";
			DragQueryFile((HDROP)wParam,0,filename,MAX_PATH);
			DragFinish((HDROP)wParam);
			
			std::string fileDropped = filename;
			//-------------------------------------------------------
			//Check if Movie file
			//-------------------------------------------------------
			if (!(fileDropped.find(".mc2") == std::string::npos) && (fileDropped.find(".mc2") == fileDropped.length()-4))
			{
				if (!pcejin.romLoaded)	//If no ROM is loaded, prompt for one
				{
					soundDriver->pause();
					LoadGame();
					pcejin.tempUnPause();
				}	
				if (pcejin.romLoaded && !(fileDropped.find(".mc2") == std::string::npos))	
					FCEUI_LoadMovie(fileDropped.c_str(), 1, false, false);		 
			}
			
			//-------------------------------------------------------
			//Check if Savestate file
			//-------------------------------------------------------
			else if (!(fileDropped.find(".mc") == std::string::npos))	//Note: potential clash, mc2 will be loaded a movie file first
			{
				if (fileDropped.find(".mc") == fileDropped.length()-4)
				{
					if ((fileDropped[fileDropped.length()-1] >= '0' && fileDropped[fileDropped.length()-1] <= '9'))
					{
						extern int MDFNSS_Load(const char *fname, const char *suffix);
						MDFNSS_Load(filename, NULL);
						ClearDirectDrawOutput();
						UpdateToolWindows();
					}
				}
			}
			
			//-------------------------------------------------------
			//Check if Lua script file
			//-------------------------------------------------------
			else if (!(fileDropped.find(".lua") == std::string::npos) && (fileDropped.find(".lua") == fileDropped.length()-4))	 //ROM is already loaded and .dsm in filename
			{
				if(LuaScriptHWnds.size() < 16)
				{
					char temp [1024];
					strcpy(temp, fileDropped.c_str());
					HWND IsScriptFileOpen(const char* Path);
					if(!IsScriptFileOpen(temp))
					{
						HWND hDlg = CreateDialog(g_hInstance, MAKEINTRESOURCE(IDD_LUA), hWnd, (DLGPROC) LuaScriptProc);
						SendDlgItemMessage(hDlg,IDC_EDIT_LUAPATH,WM_SETTEXT,0,(LPARAM)temp);
					}
				}
			}
			
			//-------------------------------------------------------
			//Check if watchlist file
			//-------------------------------------------------------
			else if (!(fileDropped.find(".wch") == std::string::npos) && (fileDropped.find(".wch") == fileDropped.length()-4))	 //ROM is already loaded and .dsm in filename
			{
				if(!RamWatchHWnd)
				{
					RamWatchHWnd = CreateDialog(g_hInstance, MAKEINTRESOURCE(IDD_RAMWATCH), hWnd, (DLGPROC) RamWatchProc);
				}
				else
					SetForegroundWindow(RamWatchHWnd);
				Load_Watches(true, fileDropped.c_str());
			}
			
			//-------------------------------------------------------
			//Else load it as a ROM
			//-------------------------------------------------------
			else if(MDFNI_LoadGame(NULL,filename))
			{
				pcejin.romLoaded = true;
				pcejin.started = true;
				//TODO: adelikat: This code is copied directly from the LoadGame() function, it should be come a separate function and called in both places
				////////////////////////////////
				if (AutoRWLoad)
				{
					//Open Ram Watch if its auto-load setting is checked
					OpenRWRecentFile(0);
					RamWatchHWnd = CreateDialog(winClass.hInstance, MAKEINTRESOURCE(IDD_RAMWATCH), g_hWnd, (DLGPROC) RamWatchProc);
				}
				UpdateRecentRoms(filename);
				////////////////////////////////
			}
		}
		return 0;
	case WM_ENTERMENULOOP:
		soundDriver->pause();
		EnableMenuItem(GetMenu(hWnd), IDM_RECORD_MOVIE, MF_BYCOMMAND | (movieMode == MOVIEMODE_INACTIVE && pcejin.romLoaded) ? MF_ENABLED : MF_GRAYED);
		EnableMenuItem(GetMenu(hWnd), ID_RAM_WATCH, MF_BYCOMMAND | (movieMode == MOVIEMODE_INACTIVE && pcejin.romLoaded) ? MF_ENABLED : MF_GRAYED);
		EnableMenuItem(GetMenu(hWnd), ID_RAM_SEARCH, MF_BYCOMMAND | (movieMode == MOVIEMODE_INACTIVE && pcejin.romLoaded) ? MF_ENABLED : MF_GRAYED);
		EnableMenuItem(GetMenu(hWnd), IDM_MEMORY, MF_BYCOMMAND | (movieMode == MOVIEMODE_INACTIVE && pcejin.romLoaded) ? MF_ENABLED : MF_GRAYED);
		EnableMenuItem(GetMenu(hWnd), IDM_PLAY_MOVIE, MF_BYCOMMAND | (movieMode == MOVIEMODE_INACTIVE && pcejin.romLoaded) ? MF_ENABLED : MF_GRAYED);
		EnableMenuItem(GetMenu(hWnd), IDM_STOPMOVIE, MF_BYCOMMAND | (movieMode != MOVIEMODE_INACTIVE) ? MF_ENABLED : MF_GRAYED);
		EnableMenuItem(GetMenu(hWnd), IDM_FILE_STOPAVI, MF_BYCOMMAND | (DRV_AviIsRecording()) ? MF_ENABLED : MF_GRAYED);
		EnableMenuItem(GetMenu(hWnd), IDM_FILE_RECORDAVI, MF_BYCOMMAND | (!DRV_AviIsRecording()) ? MF_ENABLED : MF_GRAYED);
		EnableMenuItem(GetMenu(hWnd), IDM_FILE_STOPWAV, MF_BYCOMMAND | (DRV_WaveRecordActive()) ? MF_ENABLED : MF_GRAYED);
		EnableMenuItem(GetMenu(hWnd), IDM_FILE_RECORDWAV, MF_BYCOMMAND | (!DRV_WaveRecordActive()) ? MF_ENABLED : MF_GRAYED);

		//Window Size
		checkMenu(IDC_WINDOW1X,  ((pcejin.windowSize==1)));
		checkMenu(IDC_WINDOW15X, ((pcejin.windowSize==65535)));
		checkMenu(IDC_WINDOW2X,  ((pcejin.windowSize==2)));
		checkMenu(IDC_WINDOW25X, ((pcejin.windowSize==65534)));
		checkMenu(IDC_WINDOW3X,  ((pcejin.windowSize==3)));
		checkMenu(IDC_WINDOW4X,  ((pcejin.windowSize==4)));
		checkMenu(IDC_ASPECT, ((pcejin.aspectRatio)));
		checkMenu(ID_VIEW_MIXLEFTRIGHT,MixVideoOutput);
		checkMenu(ID_COLOR_MODE_REDBLUE, ((MDFN_IEN_VB::GetColorMode()==0)));
		checkMenu(ID_COLOR_MODE_REDCYAN, ((MDFN_IEN_VB::GetColorMode()==1)));
		checkMenu(ID_COLOR_MODE_REDELECTRICCYAN, ((MDFN_IEN_VB::GetColorMode()==2)));
		checkMenu(ID_COLOR_MODE_REDGREEN, ((MDFN_IEN_VB::GetColorMode()==3)));
		checkMenu(ID_COLOR_MODE_GREENMAGENTA, ((MDFN_IEN_VB::GetColorMode()==4)));
		checkMenu(ID_COLOR_MODE_YELLOWBLUE, ((MDFN_IEN_VB::GetColorMode()==5)));
		checkMenu(ID_COLOR_MODE_GREYSCALE, ((MDFN_IEN_VB::GetColorMode()==6)));
		checkMenu(ID_SPLIT_MODE_ANAGLYPH, ((MDFN_IEN_VB::GetSplitMode()==MDFN_IEN_VB::VB3DMODE_ANAGLYPH)));
		checkMenu(ID_SPLIT_MODE_CSCOPE, ((MDFN_IEN_VB::GetSplitMode()==MDFN_IEN_VB::VB3DMODE_CSCOPE)));
		checkMenu(ID_SPLIT_MODE_SIDEBYSIDE, ((MDFN_IEN_VB::GetSplitMode()==MDFN_IEN_VB::VB3DMODE_SIDEBYSIDE)));
		checkMenu(ID_SPLIT_MODE_PBARRIER, ((MDFN_IEN_VB::GetSplitMode()==MDFN_IEN_VB::VB3DMODE_PBARRIER)));
		checkMenu(ID_VIEW_DISP_BOTH, ((DisplayLeftRightOutput==0)));
		checkMenu(ID_VIEW_DISP_LEFT, ((DisplayLeftRightOutput==1)));
		checkMenu(ID_VIEW_DISP_RIGHT, ((DisplayLeftRightOutput==2)));
		checkMenu(ID_VIEW_DISP_DISABLE, ((DisplayLeftRightOutput==3)));
		checkMenu(ID_VIEW_FRAMECOUNTER,Hud.FrameCounterDisplay);
		checkMenu(ID_VIEW_DISPLAYINPUT,Hud.ShowInputDisplay);
		checkMenu(ID_VIEW_OPENCONSOLE,OpenConsoleWindow);
		checkMenu(ID_VIEW_DISPLAYSTATESLOTS,Hud.DisplayStateSlots);
		checkMenu(ID_VIEW_DISPLAYLAG,Hud.ShowLagFrameCounter);
		checkMenu(IDM_MUTE,soundDriver->userMute);
		break;
	case WM_EXITMENULOOP:
		pcejin.tempUnPause();
		break;

	case WM_CLOSE:
		{
			SaveIniSettings();
			PostQuitMessage(0);
		}

	case WM_DESTROY:
		{
			PostQuitMessage(0);
		}
		// HANDLE_MSG(hWnd, WM_DESTROY, OnDestroy);
		// HANDLE_MSG(hWnd, WM_PAINT, OnPaint);
		// HANDLE_MSG(hwnd, WM_COMMAND, OnCommand);
	case WM_COMMAND:
		if(wParam >= baseid && wParam <= baseid + MAX_RECENT_ROMS - 1)
			{
				int x = wParam - baseid;
				soundDriver->resume();
				OpenRecentROM(x);

			}
			else if(wParam == clearid)
			{
				/* Clear all the recent ROMs */
				if(IDOK == MessageBox(g_hWnd, "OK to clear recent ROMs list?","VBJin",MB_OKCANCEL))
					ClearRecentRoms();
			}
		wmId = LOWORD(wParam);
		wmEvent = HIWORD(wParam);
		// Parse the menu selections:
		switch (wmId)
		{
		case IDC_WINDOW1X:
			pcejin.windowSize=1;
			ScaleScreen((float)pcejin.windowSize);
			break;
		case IDC_WINDOW15X:
			pcejin.windowSize=65535;
			ScaleScreen((float)pcejin.windowSize);
			break;
		case IDC_WINDOW2X:
			pcejin.windowSize=2;
			ScaleScreen((float)pcejin.windowSize);
			break;
		case IDC_WINDOW25X:
			pcejin.windowSize=65534;
			ScaleScreen((float)pcejin.windowSize);
			break;
		case IDC_WINDOW3X:
			pcejin.windowSize=3;
			ScaleScreen((float)pcejin.windowSize);
			break;
		case IDC_WINDOW4X:
			pcejin.windowSize=4;
			ScaleScreen((float)pcejin.windowSize);
			break;
		case IDC_ASPECT:
			pcejin.aspectRatio ^= 1;
			ScaleScreen((float)pcejin.windowSize);
			break;
		case IDM_EXIT:
			SaveIniSettings();
			PostQuitMessage(0);
			break;
		case IDM_RESET:
//NEWTODO			PCE_Power();
			OpenRecentROM(0);
			break;
		case IDM_OPEN_ROM:
			soundDriver->pause();
			LoadGame();
			pcejin.tempUnPause();
			break;
		case IDM_RECORD_MOVIE:
			soundDriver->pause();
			MovieRecordTo();
			pcejin.tempUnPause();
			return 0;
		case IDM_PLAY_MOVIE:
			soundDriver->pause();
			Replay_LoadMovie();
			pcejin.tempUnPause();
			return 0;
		case IDM_INPUT_CONFIG:
			soundDriver->pause();
			DialogBox(g_hInstance, MAKEINTRESOURCE(IDD_INPUTCONFIG), hWnd, DlgInputConfig);
			pcejin.tempUnPause();
			// RunInputConfig();
			break;
		case IDM_HOTKEY_CONFIG:
			{
				soundDriver->pause();

				DialogBox(g_hInstance, MAKEINTRESOURCE(IDD_KEYCUSTOM), hWnd, DlgHotkeyConfig);
				pcejin.tempUnPause();

			}
			break;

		case ID_VIEW_MIXLEFTRIGHT:
			MixVideoOutput ^= true;
			MDFN_IEN_VB::SetMixVideoOutput(MixVideoOutput);
			WritePrivateProfileBool("Display", "MixLeftRight", MixVideoOutput, IniName);
			return 0;

		case ID_SPLIT_MODE_ANAGLYPH:
			MDFN_IEN_VB::SetSplitMode(MDFN_IEN_VB::VB3DMODE_ANAGLYPH);
			WritePrivateProfileInt("Display", "SplitMode", MDFN_IEN_VB::VB3DMODE_ANAGLYPH, IniName);
			break;
		case ID_SPLIT_MODE_CSCOPE:
			MDFN_IEN_VB::SetSplitMode(MDFN_IEN_VB::VB3DMODE_CSCOPE);
			WritePrivateProfileInt("Display", "SplitMode", MDFN_IEN_VB::VB3DMODE_CSCOPE, IniName);
			//Clear the DirectDraw buffers
			ClearDirectDrawOutput();
			break;
		case ID_SPLIT_MODE_SIDEBYSIDE:
			MDFN_IEN_VB::SetSplitMode(MDFN_IEN_VB::VB3DMODE_SIDEBYSIDE);
			WritePrivateProfileInt("Display", "SplitMode", MDFN_IEN_VB::VB3DMODE_SIDEBYSIDE, IniName);
			//Clear the DirectDraw buffers
			ClearDirectDrawOutput();
			break;
		case ID_SPLIT_MODE_PBARRIER:
			MDFN_IEN_VB::SetSplitMode(MDFN_IEN_VB::VB3DMODE_PBARRIER);
			WritePrivateProfileInt("Display", "SplitMode", MDFN_IEN_VB::VB3DMODE_PBARRIER, IniName);
			break;
		case ID_PIXEL_SEP_16:
			SideBySidePixels = 16;
			MDFN_IEN_VB::SetSideBySidePixels(SideBySidePixels);
			ClearDirectDrawOutput();
			WritePrivateProfileInt("Display", "SideBySidePixels", SideBySidePixels, IniName);
			break;
		case ID_PIXEL_SEP_32:
			SideBySidePixels = 32;
			MDFN_IEN_VB::SetSideBySidePixels(SideBySidePixels);
			ClearDirectDrawOutput();
			WritePrivateProfileInt("Display", "SideBySidePixels", SideBySidePixels, IniName);
			break;
		case ID_PIXEL_SEP_48:
			SideBySidePixels = 48;
			MDFN_IEN_VB::SetSideBySidePixels(SideBySidePixels);
			ClearDirectDrawOutput();
			WritePrivateProfileInt("Display", "SideBySidePixels", SideBySidePixels, IniName);
			break;
		case ID_PIXEL_SEP_64:
			SideBySidePixels = 64;
			MDFN_IEN_VB::SetSideBySidePixels(SideBySidePixels);
			ClearDirectDrawOutput();
			WritePrivateProfileInt("Display", "SideBySidePixels", SideBySidePixels, IniName);
			break;
		case ID_PIXEL_SEP_80:
			SideBySidePixels = 80;
			MDFN_IEN_VB::SetSideBySidePixels(SideBySidePixels);
			ClearDirectDrawOutput();
			WritePrivateProfileInt("Display", "SideBySidePixels", SideBySidePixels, IniName);
			break;
		case ID_PIXEL_SEP_96:
			SideBySidePixels = 96;
			MDFN_IEN_VB::SetSideBySidePixels(SideBySidePixels);
			ClearDirectDrawOutput();
			WritePrivateProfileInt("Display", "SideBySidePixels", SideBySidePixels, IniName);
			break;
		case ID_COLOR_MODE_REDBLUE:
			MDFN_IEN_VB::SetColorMode(0);
			WritePrivateProfileInt("Display", "ColorMode", 0, IniName);
			break;
		case ID_COLOR_MODE_REDCYAN:
			MDFN_IEN_VB::SetColorMode(1);
			WritePrivateProfileInt("Display", "ColorMode", 1, IniName);
			break;
		case ID_COLOR_MODE_REDELECTRICCYAN:
			MDFN_IEN_VB::SetColorMode(2);
			WritePrivateProfileInt("Display", "ColorMode", 2, IniName);
			break;
		case ID_COLOR_MODE_REDGREEN:
			MDFN_IEN_VB::SetColorMode(3);
			WritePrivateProfileInt("Display", "ColorMode", 3, IniName);
			break;
		case ID_COLOR_MODE_GREENMAGENTA:
			MDFN_IEN_VB::SetColorMode(4);
			WritePrivateProfileInt("Display", "ColorMode", 4, IniName);
			break;
		case ID_COLOR_MODE_YELLOWBLUE:
			MDFN_IEN_VB::SetColorMode(5);
			WritePrivateProfileInt("Display", "ColorMode", 5, IniName);
			break;
		case ID_COLOR_MODE_GREYSCALE:
			MDFN_IEN_VB::SetColorMode(6);
			WritePrivateProfileInt("Display", "ColorMode", 6, IniName);
			break;
		case ID_VIEW_DISP_BOTH:
			DisplayLeftRightOutput = 0;
			MDFN_IEN_VB::SetViewDisp(DisplayLeftRightOutput);
			WritePrivateProfileInt("Display", "ViewDisplay", DisplayLeftRightOutput, IniName);
			return 0;

		case ID_VIEW_DISP_LEFT:
			DisplayLeftRightOutput = 1;
			MDFN_IEN_VB::SetViewDisp(DisplayLeftRightOutput);
			WritePrivateProfileInt("Display", "ViewDisplay", DisplayLeftRightOutput, IniName);
			return 0;

		case ID_VIEW_DISP_RIGHT:
			DisplayLeftRightOutput = 2;
			MDFN_IEN_VB::SetViewDisp(DisplayLeftRightOutput);
			WritePrivateProfileInt("Display", "ViewDisplay", DisplayLeftRightOutput, IniName);
			return 0;

		case ID_VIEW_DISP_DISABLE:
			DisplayLeftRightOutput = 3;
			MDFN_IEN_VB::SetViewDisp(DisplayLeftRightOutput);
			// We're not saving this. Too many people would set it and forget it, then compain.
			// Someone can still set it manually in the ini file though.
			return 0;

		case ID_VIEW_FRAMECOUNTER:
			Hud.FrameCounterDisplay ^= true;
			WritePrivateProfileBool("Display", "FrameCounter", Hud.FrameCounterDisplay, IniName);
			return 0;

		case ID_VIEW_DISPLAYINPUT:
			Hud.ShowInputDisplay ^= true;
			WritePrivateProfileBool("Display", "Display Input", Hud.ShowInputDisplay, IniName);
			osd->clear();
			return 0;

		case ID_VIEW_OPENCONSOLE:
			OpenConsoleWindow ^= true;
			WritePrivateProfileBool("Display", "OpenConsoleWindow", OpenConsoleWindow, IniName);
			return 0;

		case ID_VIEW_DISPLAYSTATESLOTS:
			Hud.DisplayStateSlots ^= true;
			WritePrivateProfileBool("Display", "Display State Slots", Hud.DisplayStateSlots, IniName);
			osd->clear();
			return 0;

		case ID_VIEW_DISPLAYLAG:
			Hud.ShowLagFrameCounter ^= true;
			WritePrivateProfileBool("Display", "Display Lag Counter", Hud.ShowLagFrameCounter, IniName);
			osd->clear();
			return 0;
		case IDC_NEW_LUA_SCRIPT:
			if(LuaScriptHWnds.size() < 16)
			{
				CreateDialog(g_hInstance, MAKEINTRESOURCE(IDD_LUA), g_hWnd, (DLGPROC) LuaScriptProc);
			}
			break;

			break;
		case IDM_MUTE:
			soundDriver->doUserMute();
			break;
		case IDM_STOPMOVIE:
			FCEUI_StopMovie();
			return 0;
			break;
		case ID_RAM_SEARCH:
			if(!RamSearchHWnd)
			{
				if (pcejin.romLoaded)
				{
					InitRamSearch(false);
					RamSearchHWnd = CreateDialog(winClass.hInstance, MAKEINTRESOURCE(IDD_RAMSEARCH), hWnd, (DLGPROC) RamSearchProc);
				}
			}
			else
				SetForegroundWindow(RamSearchHWnd);
			break;

		case ID_RAM_WATCH:
			if(!RamWatchHWnd)
			{
				if(pcejin.romLoaded)
					RamWatchHWnd = CreateDialog(winClass.hInstance, MAKEINTRESOURCE(IDD_RAMWATCH), hWnd, (DLGPROC) RamWatchProc);
			}
			else
				SetForegroundWindow(RamWatchHWnd);
			return 0;
		case IDM_MEMORY:
			if (!RegWndClass("MemView_ViewBox", MemView_ViewBoxProc, 0, sizeof(CMemView*)))
				return 0;

			OpenToolWindow(new CMemView());
			return 0;
		case IDM_ABOUT:
			soundDriver->pause();

			DialogBox(winClass.hInstance, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
			pcejin.tempUnPause();
			break;
		case IDM_FILE_RECORDAVI:
			soundDriver->pause();
			RecordAvi();
			pcejin.tempUnPause();
			break;
		case IDM_FILE_STOPAVI:
			StopAvi();
			break;
		case IDM_FILE_RECORDWAV:
			soundDriver->pause();
			CreateSoundSave();
			pcejin.tempUnPause();
			break;
		case IDM_FILE_STOPWAV:
			DRV_EndWaveRecord();
			break;
		}
		break;
	}
	return DefWindowProc(hWnd, Message, wParam, lParam);
}
/*
========================
idMenuScreen_Shell_Load::HandleAction h
========================
*/
bool idMenuScreen_Shell_Load::HandleAction( idWidgetAction& action, const idWidgetEvent& event, idMenuWidget* widget, bool forceHandled )
{

	if( menuData != NULL )
	{
		if( menuData->ActiveScreen() != SHELL_AREA_LOAD )
		{
			return false;
		}
	}
	
	widgetAction_t actionType = action.GetType();
	const idSWFParmList& parms = action.GetParms();
	switch( actionType )
	{
		case WIDGET_ACTION_JOY4_ON_PRESS:
		{
			return true;
		}
		case WIDGET_ACTION_JOY3_ON_PRESS:
		{
			if( options == NULL )
			{
				return true;
			}
			
			int selectionIndex = options->GetViewIndex();
			DeleteGame( selectionIndex );
			return true;
		}
		case WIDGET_ACTION_GO_BACK:
		{
			if( menuData != NULL )
			{
				if( game->IsInGame() )
				{
					menuData->SetNextScreen( SHELL_AREA_ROOT, MENU_TRANSITION_SIMPLE );
				}
				else
				{
					menuData->SetNextScreen( SHELL_AREA_CAMPAIGN, MENU_TRANSITION_SIMPLE );
				}
			}
			return true;
		}
		case WIDGET_ACTION_PRESS_FOCUSED:
		{
			if( options == NULL )
			{
				return true;
			}
			
			if( sortedSaves.Num() == 0 )
			{
				return true;
			}
			
			int selectionIndex = options->GetViewIndex();
			if( parms.Num() == 1 )
			{
				selectionIndex = parms[0].ToInteger();
				
				if( selectionIndex != options->GetFocusIndex() )
				{
					options->SetViewIndex( options->GetViewOffset() + selectionIndex );
					options->SetFocusIndex( selectionIndex );
				}
				else
				{
					LoadGame( options->GetViewOffset() + selectionIndex );
				}
			}
			else
			{
				LoadGame( options->GetViewIndex() );
			}
			
			return true;
		}
		case WIDGET_ACTION_SCROLL_VERTICAL:
		{
			return true;
		}
	}
	
	return idMenuWidget::HandleAction( action, event, widget, forceHandled );
}
Esempio n. 25
0
GameMode MainMenu::ChooseGameMode()
{
    Font.loadFromFile("Graphics/papyrus.ttf");
    float ArrowY = 300;
    int Command = 1;
    sf::Text
        NewGame("New Game", Font),
        LoadGame("Load Game", Font),
        Exit("Exit", Font);
    
    NewGame.setPosition(400, 300);
    LoadGame.setPosition(400, 335);
    Exit.setPosition(400, 370);

    NewGame.setStyle(sf::Text::Bold);
    LoadGame.setStyle(sf::Text::Bold);
    Exit.setStyle(sf::Text::Bold);

    sf::Texture ArrowTexture;
    ArrowTexture.loadFromFile("Graphics/Arrow.png");
    sf::Sprite ArrowSprite(ArrowTexture);
    ArrowSprite.setPosition(350.0f, ArrowY);

    while(Window.isOpen()) 
    {
        while(Window.pollEvent(Event))
        {
            if((Event.type == sf::Event::KeyPressed) && (Event.key.code == sf::Keyboard::Up))
            {
                if(Command != 1)
                {
                    --Command;
                    ArrowY -= 35;
                    ArrowSprite.setPosition(350.0f, ArrowY);
                }
            }
            else if((Event.type == sf::Event::KeyPressed) && (Event.key.code == sf::Keyboard::Down))
            {
                if(Command != 3)
                {
                    ++Command;
                    ArrowY += 35;
                    ArrowSprite.setPosition(350.0f, ArrowY);
                }
            }
            else if((Event.type == sf::Event::KeyPressed) && (Event.key.code == sf::Keyboard::Return))
            {
                switch(Command)
                {
                case 1:
                    return NEW_GAME;
                case 2:
                    return LOAD_GAME;
                case 3:
                    exit(0);
                }
            }
        }
        Window.clear();
        Window.draw(sf::Sprite(Background));
        Window.draw(ArrowSprite);
        Window.draw(NewGame);
        Window.draw(LoadGame);
        Window.draw(Exit);
        Window.display();
    }
}
Esempio n. 26
0
void Designer::OnControlEvent(Control* control)
{
	if(control == StartPanel->NewMapButton)
	{
		NewMap();
	}
	else if(control == StartPanel->CancelButton)
	{		
		OnExit();
	}
	else if(control == StartPanel->LoadMapButton)
	{
		LoadGame("");

		MainCamera = new Camera(MainMap, Renderer, 800, 600);
		MainCamera->ShowSelectedTile = true;
		MainCamera->ControlRect.x = 0;
		MainCamera->ControlRect.y = 0;
		ChildControls.insert(ChildControls.begin(), MainCamera);

		selectedTile.Height = 0;
		selectedTile.TileID = 3;
		selectedTile.TileSubID = 0;

		StartPanel->Visible = false;
		FocusedControl = MainCamera;

		TileSelector->Visible = true;
		TabMenu->Visible = true;
		DeleteCB->Visible = true;
		PlayerCB->Visible = true;
		TickingCB->Visible = true;

		Paused = false;
	}
	else if(control == EntityList)
	{
		UpdateEditMode(ENTITY);
	}
	else if(control == TileEntityList)
	{
		UpdateEditMode(TILEENTITY);
	}
	else if(control == TabMenu)
	{
		if(TabMenu->SelectedTab == -1)
		{
			UpdateEditMode(TILE);
		}
	}
	else if(control == DeleteCB)
	{
		if(DeleteCB->Checked)
		{
			UpdateEditMode(DELETE);
		}
		else
		{
			UpdateEditMode(TILE);
		}
	}
	else if(control == PlayerCB)
	{
		if(PlayerCB->Checked)
		{
			UpdateEditMode(PLAYER);
		}
		else
		{
			UpdateEditMode(TILE);
		}
	}
};
Esempio n. 27
0
bool MesenMovie::Play(VirtualFile &file)
{
	_movieFile = file;

	std::stringstream ss;
	file.ReadFile(ss);

	_reader.reset(new ZipReader());
	_reader->LoadArchive(ss);

	stringstream settingsData, inputData;
	if(!_reader->GetStream("GameSettings.txt", settingsData)) {
		MessageManager::Log("[Movie] File not found: GameSettings.txt");
		return false;
	}
	if(!_reader->GetStream("Input.txt", inputData)) {
		MessageManager::Log("[Movie] File not found: Input.txt");
		return false;
	}

	while(inputData) {
		string line;
		std::getline(inputData, line);
		if(line.substr(0, 1) == "|") {
			_inputData.push_back(StringUtilities::Split(line.substr(1), '|'));
		}
	}

	_deviceIndex = 0;

	ParseSettings(settingsData);
	
	Console::Pause();
		
	BatteryManager::SetBatteryProvider(shared_from_this());
	ControlManager::RegisterInputProvider(this);
	ApplySettings();

	//Disable auto-configure input option (otherwise the movie file's input types are ignored)
	bool autoConfigureInput = EmulationSettings::CheckFlag(EmulationFlags::AutoConfigureInput);
	EmulationSettings::ClearFlags(EmulationFlags::AutoConfigureInput);
	ControlManager::ResetPollCounter();
	bool gameLoaded = LoadGame();
	EmulationSettings::SetFlagState(EmulationFlags::AutoConfigureInput, autoConfigureInput);

	if(!gameLoaded) {
		Console::Resume();
		return false;
	}

	stringstream saveStateData;
	if(_reader->GetStream("SaveState.mst", saveStateData)) {
		if(!SaveStateManager::LoadState(saveStateData, true)) {
			Console::Resume();
			return false;
		} else {
			ControlManager::ResetPollCounter();
		}
	}

	_playing = true;

	Console::Resume();

	return true;
}
Esempio n. 28
0
LRESULT CALLBACK WndProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	HWND hDlg;
	switch(Message)
	{
	case WM_KEYDOWN:
		if(wParam != VK_PAUSE)
			break;
		// case WM_SYSKEYDOWN:
	case WM_CUSTKEYDOWN:
		{
			int modifiers = GetModifiers(wParam);
			if(!HandleKeyMessage(wParam,lParam, modifiers))
				return 0;
			break;
		}
	case WM_KEYUP:
		if(wParam != VK_PAUSE)
			break;
	case WM_SYSKEYUP:
	case WM_CUSTKEYUP:
		{
			int modifiers = GetModifiers(wParam);
			HandleKeyUp(wParam, lParam, modifiers);
		}
		break;
	case WM_SIZE:
		switch(wParam)
		{
		case SIZE_MINIMIZED:
			break;
		case SIZE_MAXIMIZED:
			pcejin.maximized = true;
			break;
		case SIZE_RESTORED:
			pcejin.maximized = false;
			break;
		default:
			break;
		}
		return 0;
	case WM_MOVE:
		RECT rect;
		GetWindowRect(hWnd,&rect);
		WndX = rect.left;
		WndY = rect.top;
		return 0;
	case WM_DROPFILES:
		{
			char filename[MAX_PATH] = "";
			DragQueryFile((HDROP)wParam,0,filename,MAX_PATH);
			DragFinish((HDROP)wParam);
			
			std::string fileDropped = filename;
			//-------------------------------------------------------
			//Check if mcm file, if so auto-convert and play
			//-------------------------------------------------------
			if (!(fileDropped.find(".mcm") == std::string::npos) && (fileDropped.find(".mcm") == fileDropped.length()-4))
			{
				if (!pcejin.romLoaded)	//If no ROM is loaded, prompt for one
				{
					soundDriver->pause();
					LoadGame();
					pcejin.tempUnPause();
				}
				if (pcejin.romLoaded && !(fileDropped.find(".mcm") == std::string::npos))	
					LoadMCM(fileDropped.c_str(), true);
			}
			//-------------------------------------------------------
			//Check if Movie file
			//-------------------------------------------------------
			else if (!(fileDropped.find(".mc2") == std::string::npos) && (fileDropped.find(".mc2") == fileDropped.length()-4))
			{
				if (!pcejin.romLoaded)	//If no ROM is loaded, prompt for one
				{
					soundDriver->pause();
					LoadGame();
					pcejin.tempUnPause();
				}
				if (pcejin.romLoaded && !(fileDropped.find(".mc2") == std::string::npos))
				{
					LoadMovie(fileDropped.c_str(), 1, false, false);
					RecentMovies.UpdateRecentItems(fileDropped);
				}
			}
			
			//-------------------------------------------------------
			//Check if Savestate file
			//-------------------------------------------------------
			else if (!(fileDropped.find(".nc") == std::string::npos))
			{
				if (fileDropped.find(".nc") == fileDropped.length()-4)
				{
					if ((fileDropped[fileDropped.length()-1] >= '0' && fileDropped[fileDropped.length()-1] <= '9'))
					{
						MDFNSS_Load(filename, NULL);
						UpdateToolWindows();
					}
				}
			}
			
			//-------------------------------------------------------
			//Check if Lua script file
			//-------------------------------------------------------
			else if (!(fileDropped.find(".lua") == std::string::npos) && (fileDropped.find(".lua") == fileDropped.length()-4))	 //ROM is already loaded and .dsm in filename
			{
				if(LuaScriptHWnds.size() < 16)
				{
					char temp [1024];
					strcpy(temp, fileDropped.c_str());
					HWND IsScriptFileOpen(const char* Path);
					RecentLua.UpdateRecentItems(fileDropped);
					if(!IsScriptFileOpen(temp))
					{
						HWND hDlg = CreateDialog(g_hInstance, MAKEINTRESOURCE(IDD_LUA), hWnd, (DLGPROC) LuaScriptProc);
						SendDlgItemMessage(hDlg,IDC_EDIT_LUAPATH,WM_SETTEXT,0,(LPARAM)temp);
					}
				}
			}
			
			//-------------------------------------------------------
			//Check if watchlist file
			//-------------------------------------------------------
			else if (!(fileDropped.find(".wch") == std::string::npos) && (fileDropped.find(".wch") == fileDropped.length()-4))	 //ROM is already loaded and .dsm in filename
			{
				if(!RamWatchHWnd)
				{
					RamWatchHWnd = CreateDialog(g_hInstance, MAKEINTRESOURCE(IDD_RAMWATCH), hWnd, (DLGPROC) RamWatchProc);
				}
				else
					SetForegroundWindow(RamWatchHWnd);
				Load_Watches(true, fileDropped.c_str());
			}
			
			//-------------------------------------------------------
			//Else load it as a ROM
			//-------------------------------------------------------
			
			else
			{
				ALoad(fileDropped.c_str());
			}
		}
		return 0;
	case WM_ENTERMENULOOP:
		soundDriver->pause();
		EnableMenuItem(GetMenu(hWnd), IDM_RECORD_MOVIE, MF_BYCOMMAND | (movieMode == MOVIEMODE_INACTIVE && pcejin.romLoaded) ? MF_ENABLED : MF_GRAYED);
		EnableMenuItem(GetMenu(hWnd), IDM_PLAY_MOVIE, MF_BYCOMMAND | (movieMode == MOVIEMODE_INACTIVE && pcejin.romLoaded) ? MF_ENABLED : MF_GRAYED);
		EnableMenuItem(GetMenu(hWnd), IDM_STOPMOVIE, MF_BYCOMMAND | (movieMode != MOVIEMODE_INACTIVE) ? MF_ENABLED : MF_GRAYED);
		EnableMenuItem(GetMenu(hWnd), IDM_RESTARTMOVIE, MF_BYCOMMAND | (movieMode != MOVIEMODE_INACTIVE) ? MF_ENABLED : MF_GRAYED);
		EnableMenuItem(GetMenu(hWnd), IDM_FILE_STOPAVI, MF_BYCOMMAND | (DRV_AviIsRecording()) ? MF_ENABLED : MF_GRAYED);
		EnableMenuItem(GetMenu(hWnd), IDM_FILE_RECORDAVI, MF_BYCOMMAND | (!DRV_AviIsRecording()) ? MF_ENABLED : MF_GRAYED);
		
		//Window Size
		checkMenu(IDC_WINDOW1X, ((pcejin.windowSize==1)));
		checkMenu(IDC_WINDOW2X, ((pcejin.windowSize==2)));
		checkMenu(IDC_WINDOW3X, ((pcejin.windowSize==3)));
		checkMenu(IDC_WINDOW4X, ((pcejin.windowSize==4)));
		checkMenu(IDC_ASPECT, ((pcejin.aspectRatio)));
		checkMenu(ID_VIEW_FRAMECOUNTER,Hud.FrameCounterDisplay);
		checkMenu(ID_VIEW_DISPLAYINPUT,Hud.ShowInputDisplay);
		checkMenu(ID_VIEW_DISPLAYSTATESLOTS,Hud.DisplayStateSlots);
		checkMenu(ID_VIEW_DISPLAYLAG,Hud.ShowLagFrameCounter);
		checkMenu(IDM_MUTE,soundDriver->userMute);
		break;
	case WM_EXITMENULOOP:
		pcejin.tempUnPause();
		break;

	case WM_CLOSE:
		{
			SaveIniSettings();
			PostQuitMessage(0);
		}

	case WM_DESTROY:
		{
			PostQuitMessage(0);
		}
		// HANDLE_MSG(hWnd, WM_DESTROY, OnDestroy);
		// HANDLE_MSG(hWnd, WM_PAINT, OnPaint);
		// HANDLE_MSG(hwnd, WM_COMMAND, OnCommand);
	case WM_COMMAND:
			//Recent ROMs
			if(wParam >= RECENTROM_START && wParam <= RECENTROM_START + RecentROMs.MAX_RECENT_ITEMS - 1)
			{
				ALoad(RecentROMs.GetRecentItem(wParam - RECENTROM_START).c_str());
				break;
			}
			else if (wParam == RecentROMs.GetClearID())
			{
				RecentROMs.ClearRecentItems();
				break;
			}
			else if (wParam == RecentROMs.GetAutoloadID())
			{
				RecentROMs.FlipAutoLoad();
				break;
			}
			//Recent Movies
			if(wParam >= RECENTMOVIE_START && wParam <= RECENTMOVIE_START + RecentMovies.MAX_RECENT_ITEMS - 1)
			{
				strcpy(Tmp_Str, RecentMovies.GetRecentItem(wParam - RECENTMOVIE_START).c_str());
				RecentMovies.UpdateRecentItems(Tmp_Str);
				//WIN32_StartMovieReplay(Str_Tmp);
				break;
			}
			else if (wParam == RecentMovies.GetClearID())
			{
				RecentMovies.ClearRecentItems();
				break;
			}
			else if (wParam == RecentMovies.GetAutoloadID())
			{
				RecentMovies.FlipAutoLoad();
				break;
			}
			//Recent Lua
			if(wParam >= RECENTLUA_START && wParam <= RECENTLUA_START + RecentLua.MAX_RECENT_ITEMS - 1)
			{
				if(LuaScriptHWnds.size() < 16)
				{
					char temp [1024];
					strcpy(temp, RecentLua.GetRecentItem(wParam - RECENTLUA_START).c_str());
					HWND IsScriptFileOpen(const char* Path);
					RecentLua.UpdateRecentItems(temp);
					if(!IsScriptFileOpen(temp))
					{
						HWND hDlg = CreateDialog(g_hInstance, MAKEINTRESOURCE(IDD_LUA), hWnd, (DLGPROC) LuaScriptProc);
						SendDlgItemMessage(hDlg,IDC_EDIT_LUAPATH,WM_SETTEXT,0,(LPARAM)temp);
					}
				}

				break;
			}
			else if (wParam == RecentLua.GetClearID())
			{
				RecentLua.ClearRecentItems();
				break;
			}
			else if (wParam == RecentLua.GetAutoloadID())
			{
				RecentLua.FlipAutoLoad();
				break;
			}
		wmId = LOWORD(wParam);
		wmEvent = HIWORD(wParam);
		// Parse the menu selections:
		switch (wmId)
		{
		case IDC_WINDOW1X:
			pcejin.windowSize=1;
			ScaleScreen(pcejin.windowSize);
			break;
		case IDC_WINDOW2X:
			pcejin.windowSize=2;
			ScaleScreen(pcejin.windowSize);
			break;
		case IDC_WINDOW3X:
			pcejin.windowSize=3;
			ScaleScreen(pcejin.windowSize);
			break;
		case IDC_WINDOW4X:
			pcejin.windowSize=4;
			ScaleScreen(pcejin.windowSize);
			break;
		case IDC_ASPECT:
			pcejin.aspectRatio ^= 1;
			ScaleScreen(pcejin.windowSize);
			break;
		case IDM_EXIT:
			SaveIniSettings();
			PostQuitMessage(0);
			break;
		case IDM_RESET:
			PCE_Power();
			break;
		case IDM_OPEN_ROM:
			soundDriver->pause();
			LoadGame();
			pcejin.tempUnPause();
			break;
		case IDM_RECORD_MOVIE:
			soundDriver->pause();
			MovieRecordTo();
			pcejin.tempUnPause();
			return 0;
		case IDM_PLAY_MOVIE:
			soundDriver->pause();
			Replay_LoadMovie();
			pcejin.tempUnPause();
			return 0;
		case IDM_INPUT_CONFIG:
			soundDriver->pause();
			DialogBox(g_hInstance, MAKEINTRESOURCE(IDD_INPUTCONFIG), hWnd, DlgInputConfig);
			pcejin.tempUnPause();
			// RunInputConfig();
			break;
		case IDM_HOTKEY_CONFIG:
			{
				soundDriver->pause();

				DialogBox(g_hInstance, MAKEINTRESOURCE(IDD_KEYCUSTOM), hWnd, DlgHotkeyConfig);
				pcejin.tempUnPause();

			}
			break;

		case IDM_BIOS_CONFIG:
			soundDriver->pause();

			DialogBox(g_hInstance, MAKEINTRESOURCE(IDD_BIOS), hWnd, (DLGPROC) BiosSettingsDlgProc);
			// DialogBox(g_hInstance, MAKEINTRESOURCE(IDD_KEYCUSTOM), hWnd, BiosSettingsDlgProc);
			pcejin.tempUnPause();
			break;
		case ID_VIEW_FRAMECOUNTER:
			Hud.FrameCounterDisplay ^= true;
			WritePrivateProfileBool("Display", "FrameCounter", Hud.FrameCounterDisplay, IniName);
			return 0;

		case ID_VIEW_DISPLAYINPUT:
			Hud.ShowInputDisplay ^= true;
			WritePrivateProfileBool("Display", "Display Input", Hud.ShowInputDisplay, IniName);
			osd->clear();
			return 0;

		case ID_VIEW_DISPLAYSTATESLOTS:
			Hud.DisplayStateSlots ^= true;
			WritePrivateProfileBool("Display", "Display State Slots", Hud.DisplayStateSlots, IniName);
			osd->clear();
			return 0;

		case ID_VIEW_DISPLAYLAG:
			Hud.ShowLagFrameCounter ^= true;
			WritePrivateProfileBool("Display", "Display Lag Counter", Hud.ShowLagFrameCounter, IniName);
			osd->clear();
			return 0;
		case IDC_NEW_LUA_SCRIPT:
			if(LuaScriptHWnds.size() < 16)
			{
				CreateDialog(g_hInstance, MAKEINTRESOURCE(IDD_LUA), g_hWnd, (DLGPROC) LuaScriptProc);
			}
			break;
		case IDM_CONVERT_MCM:
			ConvertMCM(hWnd);

			break;
		case IDM_MUTE:
			soundDriver->doUserMute();
			break;
		case IDM_STOPMOVIE:
			StopMovie();
			return 0;
			break;
		case IDM_RESTARTMOVIE:
			PCE_Power();
			ResetFrameCount();
			movieMode = MOVIEMODE_PLAY;
			movie_readonly = true;
			return 0;
			break; 
		case ID_RAM_SEARCH:
			if(!RamSearchHWnd)
			{
				InitRamSearch();
				RamSearchHWnd = CreateDialog(winClass.hInstance, MAKEINTRESOURCE(IDD_RAMSEARCH), hWnd, (DLGPROC) RamSearchProc);
			}
			else
				SetForegroundWindow(RamSearchHWnd);
			break;

		case ID_RAM_WATCH:
			if(!RamWatchHWnd)
			{
				RamWatchHWnd = CreateDialog(winClass.hInstance, MAKEINTRESOURCE(IDD_RAMWATCH), hWnd, (DLGPROC) RamWatchProc);
			}
			else
				SetForegroundWindow(RamWatchHWnd);
			return 0;
		case IDM_MEMORY:
			if (!RegWndClass("MemView_ViewBox", MemView_ViewBoxProc, 0, sizeof(CMemView*)))
				return 0;

			OpenToolWindow(new CMemView());
			return 0;
		case IDM_ABOUT:
			soundDriver->pause();

			DialogBox(winClass.hInstance, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
			pcejin.tempUnPause();
			break;
		case IDM_FILE_RECORDAVI:
			soundDriver->pause();
			RecordAvi();
			pcejin.tempUnPause();
			break;
		case IDM_FILE_STOPAVI:
			StopAvi();
			break;
		}
		break;
	}
	return DefWindowProc(hWnd, Message, wParam, lParam);
}
Esempio n. 29
0
///////////////////////////////////////////////////////////////////////
// Name: Execute()
// Desc:
///////////////////////////////////////////////////////////////////////
void CGame::Execute( bool bFullScreen, bool bHardware )
{
  
  float    ftimer	= 0.0f;
  float    ftimediff = 0.0f;
  float    ffpstime	= 0.0f;
  int	   fps		= 0, 
		   frames	= 0;
  char	   szfps[3]	= { '0', '0' };
  int      i		= 0;
  int	   dx		= 0, 
		   dy		= 0;
  Uint32   winner_index		= 0U, 
		   winner_index2	= 0U;
  Uint32   time_destroyem	= 0U;
  Uint32   time_showwinner	= 0U;
  SDL_Rect rtemp;
  bool	   change_map			= false;
  bool	   change_map_key		= false;
  bool	   change_shadows		= false;
  bool	   change_shadows_key	= false;
  bool	   game_paused_key		= false;
  bool	   menu_escape_key		= false;
  bool	   music_off			= false;
  bool	   music_off_key		= false;
  bool	   toggle_fullscreen	= false;
  bool	   game_end		= false;
  float    qg_frame		= 0.0f;
  bool	   wait_key		= false;
  Uint32   time_round	= 0U, 
		   tv		= 0U;
  bool	   at_exit	= false;
  CVehicle *ptr_veh	= NULL;

  p1_auto_index = 99;
  p2_auto_index = 99;
  
  // init engine
  bRunning = Sdl.Initialize( this, 640, 480, 16, bFullScreen, bHardware );

  Sdl.InitializeJoystick();
  Sdl.AcquireJoystick();

  if ( bRunning )
  {
	  bRunning = LoadGame();

	  LOG("Starting Game loop...");
	  
	  ftimer = (float)SDL_GetTicks();
  }

  while( bRunning )
  {
	// do hires timing
	ftimediff = SDL_GetTicks() - ftimer;
	mpf = ftimediff / 1000.0f;
	ftimer = (float)SDL_GetTicks();
	// calculate fps
	if ( ftimer - ffpstime >= 1000 )
	{
		fps = frames;
		frames = 0;
		ffpstime = (float)SDL_GetTicks();
	}
	frames++;
	//fps = 1.0 / mpf;
  
	// get input  
	Sdl.GetInput(); 
	//if ( Sdl.IsKeyPressed(SDLK_ESCAPE] )
	//bRunning = false;

	// map-change
	if ( Sdl.IsKeyPressed(SDLK_F5) && !change_map_key )
	{
		change_map_key = true;
		change_map = true;
	
		if ( change_map )
		{
			cur_map++;
			if ( cur_map >= NUM_BACKGROUNDS ) cur_map = 1;
			change_map = false;
		}
	}
	if ( !Sdl.IsKeyPressed(SDLK_F5) )
	  change_map_key = false;

	// shadows on/off
	if ( Sdl.IsKeyPressed(SDLK_F9) && !change_shadows_key )
	{
		change_shadows_key = true;
		change_shadows = true;
	
		if ( change_shadows )
		{
			if ( game_shadows ) 
				game_shadows = false;
			else
				game_shadows = true;
			
			change_shadows = false;
		}
	}
	if ( !Sdl.IsKeyPressed(SDLK_F9) )
		change_shadows_key = false;
	
	if ( Sdl.IsKeyPressed(SDLK_F11) && !toggle_fullscreen )
	{
	  toggle_fullscreen = true;
	  Sdl.ToggleFullscreen();
	}
	if ( !Sdl.IsKeyPressed(SDLK_F11) )
	  toggle_fullscreen = false;

	// music on/off
	if ( Sdl.IsKeyPressed(SDLK_F4) && !music_off_key )
	{
		music_off_key = true;
		music_off = true;
	
		if ( music_off )
		{
			if ( Sounds.IsMusicPlaying() ) 
				Sounds.StopMusic();
			else
				Sounds.ResumeMusic();
			
			music_off = false;
		}
	}
	if ( !Sdl.IsKeyPressed(SDLK_F4) )
		music_off_key = false;

	if ( Sdl.IsKeyPressed(SDLK_F6) )
		show_fps = !show_fps;	

#ifdef _DEBUG
	if ( Sdl.IsKeyPressed(SDLK_F12) )
		bRunning = false;
#endif

	// Check music sequence ingame.
	// Play a new track once the previous one has finished playing.
	if ( Gamestate != GS_MENU )
	{
		Sounds.CheckMusic();
	}

	// GAME_STATES
	switch( Gamestate )
	{
	case GS_EXIT:

		if ( !at_exit )
		{
			at_exit = true;

			if ( ( splash = Sdl.LoadBitmap( "gfx/interf/advert.bmp" )) == NULL ) 
				at_exit = false;  
	
			time_destroyem = Timer.Time() + 15000;
		}

		if ( !at_exit || time_destroyem > Timer.Time() )
		{
			Sdl.BlitNow( 0, 0, splash ); 

			for ( i = 0; i < 255; i++ )
			{
				if ( Sdl.IsKeyPressed(i) && !Sdl.IsKeyPressed(SDLK_ESCAPE) )
				{
					bRunning = false;
					RELEASE_SURF( splash );
				}
			}
		}
		else
		{
			bRunning = false;
		}

	break;

	case GS_MENU:

		if ( !Sdl.IsKeyPressed(SDLK_ESCAPE)  )
			menu_escape_key = false;

		Menu.Update();

		if ( Sdl.IsKeyPressed(SDLK_ESCAPE) && !menu_escape_key )
		{
			menu_escape_key = true;
			Menu.SetMenuState( MS_EXIT );
		}

		// play once volume is > 0
		if ( !Sounds.IsMusicPlaying() ) 
		{
			if (Sdl.GetMusicVolume() > 0)
				Sounds.Play( MUS_MENU, true );
		}		

	break;


	case GS_GAMEPLAY_SETUP:

		if ( wait_key )
		{
			Sdl.BlitNow( 0, 0, getready );			
			
			for ( i = 0; i < 255; i++ )
			{
				if ( Sdl.IsKeyPressed(i) )
				{
					Gamestate = GS_GAMEPLAY;	// now play...*/
					wait_key = false;

					// choose random start_map
					cur_map = intGetRnd( 2, NUM_BACKGROUNDS );

					// stop menu-music
					Sounds.StopMusic();
					// start_random_ingame_music
					Sounds.Play( (CONST_MUSIC)intGetRnd( 1, NUM_MUSIX ), false );

					// prepare time if time-round
					time_round = Timer.Time() + game_time * 1000;

					break;
				}
			}
		}
		else
		{
			SetupVehicles();

			// reset classes
			Anims.Reset();
			Dtoys.Reset();
			Mines.Reset();
			wait_key = true;
		}

	break;


	case GS_GAMEPLAY:

		if ( Sdl.IsKeyPressed(SDLK_ESCAPE) && !game_paused )
		{
			//bRunning = false;  // {!} immediate QUIT
			quit_dialog = true;
			Sdl.FlipTo( pause_surf );
		}
		else if ( Sdl.IsKeyPressed(SDLK_p) && !quit_dialog && !game_paused_key )
		{
			game_paused_key = true;

			if ( game_paused ) 
			{
				game_paused = false;
				Timer.Unpause(); // unpause timer
			}
			else
			{
				Sdl.FlipTo( pause_surf );
				game_paused = true;
				Timer.Pause(); // pause timer
			}

		}

		if ( !Sdl.IsKeyPressed(SDLK_p) )
		  game_paused_key = false;


		if ( !game_paused && !quit_dialog ) 
		{
			// blit background
			Sdl.BlitNow( 0, 0, back[0] );
			Sdl.BlitNow( 6, 2, back[cur_map] );
	
			// update animations
			Anims.Update();
			// update toys
			Dtoys.Update();
			Mines.Update();
	
			// update vehicles
			ptr_veh = Auto;
			for ( i = 0; i < game_num_cars; i++, ptr_veh++ )
			{
				ptr_veh->Update();

				switch( i )
				{
				case 0:
					Sdl.BlitNow( 10, 429, ptr_veh->GetDriverNameSurface() );
					break;

				case 1:
					Sdl.BlitNow( 172, 429, ptr_veh->GetDriverNameSurface() );
					break;

				case 2:					
					Sdl.BlitNow( 333, 429, ptr_veh->GetDriverNameSurface() );
					break;

				case 3:					
					Sdl.BlitNow( 493, 429, ptr_veh->GetDriverNameSurface() );
					break;
				}
			
				// check for frag-winner
				if ( Gametype == GT_FRAGS )
				{
					if ( ptr_veh->GetFrags() >= game_frags ) 
					{
						winner_index = i;
						game_end = true;
						break;
					}
				}
			} // end for

			// check for round-time
			if ( Gametype == GT_TIME )
			{
				tv = (time_round - Timer.Time()) / 1000;
				if ( tv > 0 )
				{
					dx = tv / 60;
					sprintf( szfps, "%d", dx );
					Sdl.DrawNum( 305, 3, szfps );
					dx = tv % 60;
					sprintf( szfps, "%.2d", dx );
					Sdl.DrawNum( 319, 3, szfps );
				}
				else
				{
					game_end = true;

					if ( Gamemode == GM_2V2 )
					{
						dx = Auto[0].GetFrags() + Auto[1].GetFrags();
						dy = Auto[2].GetFrags() + Auto[3].GetFrags();

						if ( dx > dy )
						{
							if ( Auto[0].GetFrags() > Auto[1].GetFrags() )
							{
								winner_index = 0;
								winner_index2 = 1;
							}
							else
							{
								winner_index = 1;
								winner_index2 = 0;
							}
						}
						else if ( dx < dy )
						{
							winner_index = 2;
							winner_index2 = 3;
						}
						else
							winner_index = 9999;
					}
					else
					{
						// time's up, see who wins
						ptr_veh = &Auto[1];
						winner_index = 0;
						for ( i = 1; i < game_num_cars; i++, ptr_veh++ )
						{
							if ( ptr_veh->GetFrags() > Auto[winner_index].GetFrags() )
								winner_index = i;
							else if ( ptr_veh->GetFrags() == Auto[winner_index].GetFrags() 
									  && ptr_veh->GetTeam() != Auto[winner_index].GetTeam() )
							{
								winner_index = 9999; // game is draw
								break;
							}
						}
					} // end if GM2v2
				}
			}

			// end-game
			if ( game_end )
			{
				game_end = false;

				// if it's a team-game get the other winner's index
				if ( Gamemode == GM_2V2 && Gametype == GT_FRAGS )
				{
					for ( ptr_veh = &Auto[0], i = 0; i < game_num_cars; i++, ptr_veh++ )
					{
						if ( i != winner_index )
							if ( ptr_veh->GetTeam() == Auto[winner_index].GetTeam() )
							{
								winner_index2 = i;
								break;
							}	
					}
				}

				Gamestate = GS_GAMEPLAY_WINNER;
				time_showwinner = Timer.Time() + TIME_SHOWWINNER;
				//Sounds.FadeMusic( TIME_SHOWWINNER );
				Sounds.StopMusic();
			}
		}

		// do quit_dialog || game_pause
		if ( quit_dialog )
		{
			dx = 320 - (but_quit[0]->w) / 2;
			dy = 240 - (but_quit[0]->h) / 2;

			Sdl.BlitNow( 0, 0, pause_surf );
			//Sdl.BlitShadow( dx + 9, dy + 9, but_quit );
			// blit quit_game dialog
			Sdl.BlitNow( dx, dy, but_quit[(int)qg_frame] );
			qg_frame += mpf * 10;
			if ( qg_frame > 4 )
				qg_frame = 0;

			if ( Sdl.IsKeyPressed(SDLK_y) )
			{
				// reset campaign level
				if ( ( Gameplayers == GP_JUDY_CAMPAIGN || Gameplayers == GP_KEETH_CAMPAIGN ) ) 
					player_level = 1;

				quit_dialog = false;
				Gamestate = GS_MENU;
				Sounds.StopMusic();
				Sounds.Play( MUS_MENU, true );
			}

			if ( Sdl.IsKeyPressed(SDLK_n) )
				quit_dialog = false;
		}
		else if ( game_paused )
		{
			dx = 320 - (but_pause->w / 2);
			dy = 240 - (but_pause->h / 2);

			Sdl.BlitNow( 0, 0, pause_surf );
			Sdl.BlitNow( dx, dy, but_pause );
			/*if ( Sdl.IsKeyPressed(SDLK_p] )
			{
				game_paused = false;
				Timer.Unpause(); // unpause timer
			}*/
		}

	break;


	case GS_GAMEPLAY_WINNER:

		if ( Sdl.IsKeyPressed(SDLK_ESCAPE) || time_showwinner < Timer.Time() )
		{
			Gamestate = GS_MENU;

			if ( time_showwinner < Timer.Time() )
			{
				Sounds.StopMusic();
				Sounds.Play( MUS_MENU, true );
			}
			
			// advance campaign level if player won
			if ( ( Gameplayers == GP_JUDY_CAMPAIGN || Gameplayers == GP_KEETH_CAMPAIGN ) ) 
			{
				if ( winner_index == 0 )
					player_level++;
				else
				{   // go back 1 level
					player_level--;
					if ( player_level < 1 ) player_level = 1;
				}
			}

			// release car-classes
			for ( i = 0; i < game_num_cars; i++ )
				Auto[i].Release();
		}
		else
		{
			// blit background
			Sdl.BlitNow( 0, 0, back[0] );
			Sdl.BlitNow( 6, 2, back[cur_map] );

			// update animations
			Anims.Update();
			// update toys
			Dtoys.Update();
			Mines.Update();
	
			// update vehicles	
			ptr_veh = Auto;
			for ( i = 0; i < game_num_cars; i++, ptr_veh++ )
			{
				ptr_veh->Update();

				switch( i )
				{
				case 0:
					Sdl.BlitNow( 10, 429, ptr_veh->GetDriverNameSurface() );
					break;

				case 1:
					Sdl.BlitNow( 172, 429, ptr_veh->GetDriverNameSurface() );
					break;

				case 2:					
					Sdl.BlitNow( 333, 429, ptr_veh->GetDriverNameSurface() );
					break;

				case 3:					
					Sdl.BlitNow( 493, 429, ptr_veh->GetDriverNameSurface() );
					break;
			
				}

				// destroy looser-vehicles
				if ( Timer.Time() > time_destroyem )
				{
					time_destroyem = 0;
					if ( i != winner_index )
						ptr_veh->DoDamage( 1000, NO_ATTACKER );
				}
			}

			if ( time_destroyem == 0 ) 
			  time_destroyem = Timer.Time() + intGetRnd( 1800, 3000 );

			if ( Gamemode == GM_2V2 )
			{
				if ( winner_index == 9999 )
				{
					// a draw game
					dx = 320 - 30;
					dy = rScreen.h / 2 - 40;
					rtemp.x = 0;
					rtemp.y = 13;
					rtemp.w = 60;
					rtemp.h = 12;
					Sdl.BlitNow( dx, dy, winneris, &rtemp );
				}
				else
				{
					// show 2 winners
					dx = 320 - 32;
					dy = rScreen.h / 2 - 40;
					rtemp.x = 0;
					rtemp.y = 25;
					rtemp.w = 64;
					rtemp.h = 12;
					Sdl.BlitNow( dx, dy, winneris, &rtemp );
					dx += 64;
					Sdl.BlitNow( dx, dy, Auto[winner_index].GetDriverNameSurface() );
					Sdl.BlitNow( dx, dy + 14, Auto[winner_index2].GetDriverNameSurface() );
				}
			}
			else
			{
				if ( winner_index == 9999 )
				{
					// a draw game
					dx = 320 - 30;
					dy = rScreen.h / 2 - 40;
					rtemp.x = 0;
					rtemp.y = 13;
					rtemp.w = 60;
					rtemp.h = 12;
					Sdl.BlitNow( dx, dy, winneris, &rtemp );
				}
				else
				{
					// show who's winner
					dx = 320 - 65;
					dy = rScreen.h / 2 - 40;
					rtemp.x = rtemp.y = 0;
					rtemp.w = 55;
					rtemp.h = 12;
					Sdl.BlitNow( dx, dy, winneris, &rtemp );
					dx += 52;
					Sdl.BlitNow( dx, dy, Auto[winner_index].GetDriverNameSurface() );
				}
			}
		}

	break;


	//case GS_EXIT:
		//...
		//bRunning = false;
	//break;
	}

	if ( show_fps )
	{
		// blit framespersec
		//sprintf( szfps, "%d %f", fps, mpf );
		sprintf( szfps, "%d", fps );
		Sdl.DrawNum( SCREEN_WIDTH - 40, 430, szfps );
		//Sdl.DrawNum( 500, 400, szfps );
	}
	
	// flip buffers
	Sdl.Flip();   
    
  }


}
Esempio n. 30
0
void Game::Start() {

    if(_gameState != Uninitialized) {
        return;
    }

    /* Initialize all prototype arrays and game objects */

    /* Load resources and xml files */
    ConstructResources();   // load all files into memory
    ConstructPrototypes();  // construct entity prototypes (from xml raw files)

    _gameState = Playing;
    _inventoryConsole = NULL;
    _inventoryInfo = NULL;
    Turns = 0;

    // Initialize player:
    player.cam_follow = true;
    player.speed = 100.0f;
    player.viewinginventory = false;

    player.Message("Have a secure day!", TCODColor::green, TCODColor::black);

    GameMap.Initialize(100, 100, getTurf("t_wall"), this);
    RandomGen = new TCODRandom();


    const char* smap[] = {
		"##############################################",
		"#######################      #################",
		"#####################    #     ###############",
		"######################  ###        ###########",
		"##################      #####             ####",
		"################       ########    ###### ####",
		"###############      #################### ####",
		"################    ######                  ##",
		"########   #######  ######   #     #     #  ##",
		"########   ######      ###                  ##",
		"########                                    ##",
		"####       ######      ###   #     #     #  ##",
		"#### ###   ########## ####                  ##",
		"#### ###   ##########   ########### ##########",
		"#### ##################   #####          #####",
		"#### ###             #### #####          #####",
		"####           #     ####                #####",
		"########       #     #### #####          #####",
		"########       #####      #######      #######",
		"#########++ ++####################++++########",
		"##                                          ##",
		"#                                            #",
		"#                                      g     #",
		"#                                     g g    #",
		"#       M                                    #",
		"#                        @                   #",
		"#                                      g     #",
		"#                                            #",
		"#                                            #",
		"#                                            #",
		"#                                            #",
		"#                                            #",
		"#                                            #",
		"#                S                           #",
		"#              S S S                         #",
		"#                                            #",
		"#                                            #",
		"#                                            #",
		"#                                            #",
		"#                                            #",
		"#                                            #",
		"#                                            #",
		"#   //////////////////// /  //////////////// #",
		"#                    /   /      [            #",
		"#                       / ?                  #",
		"#                                            #",
		"#                                            #",
		"#                                            #",
		"#                                            #",
		"#                                            #",
		"#                                            #",
		"#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#",
		"##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##",
		"##############################################",


	};
    for (int y=0; y < 54; y++ ) {
        for (int x=0; x < 46; x++ ) {
            if ( smap[y][x] == '#' ) {
                GameMap.SpawnTurf(x, y, getTurf("t_wall"));
            }
            else if ( smap[y][x] == '~' ) {
                GameMap.SpawnTurf(x, y, getTurf("t_water"));
            }
            else if ( smap[y][x] == 'g' ) {
                GameMap.SpawnTurf(x, y, getTurf("t_grass"));
                GameMap.SpawnMob(x, y, getMob("m_goat"));
            }
            else if ( smap[y][x] == 'M' ) {
                GameMap.SpawnTurf(x, y, getTurf("t_grass"));
                GameMap.SpawnMob(x, y, getMob("m_kelrah"));
            }
            else if ( smap[y][x] == 'S' ) {
                GameMap.SpawnTurf(x, y, getTurf("t_grass"));
                GameMap.SpawnMob(x, y, getMob("m_skeleton"));
            }
            else if ( smap[y][x] == '+' ) {
                GameMap.SpawnTurf(x, y, getTurf("t_window"));
            }
            else if ( smap[y][x] == '@' ) {
                GameMap.SpawnTurf(x, y, getTurf("t_grass"));
                GameMap.InsertMob(x, y, &player);
                player.x = x;
                player.y = y;
                player.cam_x = player.x;
                player.cam_y = player.y;
            }
            else if ( smap[y][x] == '/' ) {
                GameMap.SpawnTurf(x, y, getTurf("t_grass"));
                GameMap.SpawnItem(x, y, getItem("i_shortsword"));
            }
            else if ( smap[y][x] == '[' ) {
                GameMap.SpawnTurf(x, y, getTurf("t_grass"));
                GameMap.SpawnItem(x, y, getItem("i_backpack"));
            }
            else if ( smap[y][x] == '?' ) {
                GameMap.SpawnTurf(x, y, getTurf("t_grass"));
                GameMap.SpawnItem(x, y, getItem("i_flail"));
            }
            else {
                GameMap.SpawnTurf(x, y, getTurf("t_grass"));
            }
        }
    }
    Test = "Lol!";

    // Initialize TCOD
    //TCODConsole::setCustomFont("terminal12x12.png", TCOD_FONT_LAYOUT_ASCII_INROW);
    TCODConsole::initRoot(VIEW_WIDTH, VIEW_HEIGHT, "Origin: Tales of Anarchy", false);
    TCODSystem::setFps(15);
    TCODConsole::setKeyboardRepeat(30, 5);

    DrawHud(true);

    std::cout << "Game Started" << std::endl << std::endl;
    LoadGame();

    while(!IsExiting()) {
        GameLoop();
    }
    SaveGame();
}