示例#1
0
int main(int argc, char *argv[]) {
	// init fnkdat
	if(fnkdat(NULL, NULL, 0, FNKDAT_INIT) < 0) {
      perror("Could not initialize fnkdat");
      exit(EXIT_FAILURE);
	}

	bool bShowDebug = false;
    for(int i=1; i < argc; i++) {
	    //check for overiding params
	    std::string parameter(argv[i]);

		if(parameter == "--showlog") {
		    // special parameter which does not overwrite settings
            bShowDebug = true;
		} else if((parameter == "-f") || (parameter == "--fullscreen") || (parameter == "-w") || (parameter == "--window") || (parameter.find("--PlayerName=") == 0) || (parameter.find("--ServerPort=") == 0)) {
            // normal parameter for overwriting settings
            // handle later
        } else {
            printUsage();
            exit(EXIT_FAILURE);
		}
	}

	if(bShowDebug == false) {
	    // get utf8-encoded log file path
	    std::string logfilePath = getLogFilepath();
	    const char* pLogfilePath = logfilePath.c_str();

	    #if defined (_WIN32)

        // on win32 we need an ansi-encoded filepath
        WCHAR szwLogPath[MAX_PATH];
        char szLogPath[MAX_PATH];

        if(MultiByteToWideChar(CP_UTF8, 0, pLogfilePath, -1, szwLogPath, MAX_PATH) == 0) {
            fprintf(stderr, "Conversion of logfile path from utf-8 to utf-16 failed\n");
            exit(EXIT_FAILURE);
        }

        if(WideCharToMultiByte(CP_ACP, 0, szwLogPath, -1, szLogPath, MAX_PATH, NULL, NULL) == 0) {
            fprintf(stderr, "Conversion of logfile path from utf-16 to ansi failed\n");
            exit(EXIT_FAILURE);
        }

        pLogfilePath = szLogPath;

	    #endif

        int d = open(pLogfilePath, O_WRONLY | O_CREAT | O_TRUNC, 0644);
        if(d < 0) {
            fprintf(stderr, "Opening logfile '%s' failed\n", pLogfilePath);
            exit(EXIT_FAILURE);
        }

        // Hint: fileno(stdout) != STDOUT_FILENO on Win32 (see SDL_win32_main.c)
        if(dup2(d, fileno(stdout)) < 0) {
            fprintf(stderr, "Redirecting stdout failed\n");
            exit(EXIT_FAILURE);
        }

        // Hint: fileno(stderr) != STDERR_FILENO on Win32 (see SDL_win32_main.c)
        if(dup2(d, fileno(stderr)) < 0) {
            fprintf(stderr, "Redirecting stderr failed\n");
            exit(EXIT_FAILURE);
        }
	}

	fprintf(stdout, "Starting Dune Legacy " VERSION " ...\n"); fflush(stdout);

	if(checkForExcessPrecision() == true) {
        fprintf(stdout, "WARNING: Floating point operations are internally calculated with higher precision. Network game might get async. Are you using x87-FPU? Check your compile settings!\n"); fflush(stdout);
	}

    // First check for missing files
    std::vector<std::string> missingFiles = FileManager::getMissingFiles();

    if(missingFiles.empty() == false) {
        // create data directory inside config directory
        char tmp[FILENAME_MAX];
        fnkdat("data/", tmp, FILENAME_MAX, FNKDAT_USER | FNKDAT_CREAT);

        bool cannotShowMissingScreen = false;
        fprintf(stderr,"The following files are missing:\n");
        std::vector<std::string>::const_iterator iter;
        for(iter = missingFiles.begin() ; iter != missingFiles.end(); ++iter) {
            fprintf(stderr," %s\n",iter->c_str());
            if(iter->find("LEGACY.PAK") != std::string::npos) {
                cannotShowMissingScreen = true;
            }
        }

        fprintf(stderr,"Put them in one of the following directories:\n");
        std::vector<std::string> searchPath = FileManager::getSearchPath();
        std::vector<std::string>::const_iterator searchPathIter;
        for(searchPathIter = searchPath.begin(); searchPathIter != searchPath.end(); ++searchPathIter) {
            fprintf(stderr," %s\n",searchPathIter->c_str());
        }

        if(cannotShowMissingScreen == true) {
            return EXIT_FAILURE;
        }
    }

	bool bExitGame = false;
	bool bFirstInit = true;
	bool bFirstGamestart = false;

    debug = false;
    cursorFrame = UI_CursorNormal;

	do {
		int seed = time(NULL);
		srand(seed);

        // check if configfile exists
        std::string configfilepath = getConfigFilepath();
        if(existsFile(configfilepath) == false) {
            std::string userLanguage = getUserLanguage();
            if(userLanguage.empty()) {
                userLanguage = "en";
            }

            if(missingFiles.empty() == true) {
                // if all pak files were found we can create the ini file
                bFirstGamestart = true;
                createDefaultConfigFile(configfilepath, userLanguage);
            }
        }

		INIFile myINIFile(configfilepath);

		settings.general.playIntro = myINIFile.getBoolValue("General","Play Intro",false);
		settings.general.playerName = myINIFile.getStringValue("General","Player Name","Player");
		settings.video.width = myINIFile.getIntValue("Video","Width",640);
		settings.video.height = myINIFile.getIntValue("Video","Height",480);
		settings.video.fullscreen = myINIFile.getBoolValue("Video","Fullscreen",true);
		settings.video.doubleBuffering = myINIFile.getBoolValue("Video","Double Buffering",true);
		settings.video.frameLimit = myINIFile.getBoolValue("Video","FrameLimit",true);
		settings.video.preferredZoomLevel = myINIFile.getIntValue("Video","Preferred Zoom Level", 0);
		settings.video.scaler = myINIFile.getStringValue("Video","Scaler", "scale2x");
		settings.audio.musicType = myINIFile.getStringValue("Audio","Music Type","adl");
		settings.audio.playMusic = myINIFile.getBoolValue("Audio","Play Music", true);
		settings.audio.playSFX = myINIFile.getBoolValue("Audio","Play SFX", true);
		settings.audio.frequency = myINIFile.getIntValue("Audio","Audio Frequency", 22050);

		settings.general.language = myINIFile.getStringValue("General","Language","en");

		settings.network.serverPort = myINIFile.getIntValue("Network","ServerPort",DEFAULT_PORT);
		settings.network.metaServer = myINIFile.getStringValue("Network","MetaServer",DEFAULT_METASERVER);
		settings.network.debugNetwork = myINIFile.getBoolValue("Network","Debug Network",false);

		settings.ai.campaignAI = myINIFile.getStringValue("AI","Campaign AI",DEFAULTAIPLAYERCLASS);

        settings.gameOptions.gameSpeed = myINIFile.getIntValue("Game Options","Game Speed",GAMESPEED_DEFAULT);
        settings.gameOptions.concreteRequired = myINIFile.getBoolValue("Game Options","Concrete Required",true);
		settings.gameOptions.structuresDegradeOnConcrete = myINIFile.getBoolValue("Game Options","Structures Degrade On Concrete",true);
        settings.gameOptions.fogOfWar = myINIFile.getBoolValue("Game Options","Fog of War",false);
        settings.gameOptions.startWithExploredMap = myINIFile.getBoolValue("Game Options","Start with Explored Map",false);
        settings.gameOptions.instantBuild = myINIFile.getBoolValue("Game Options","Instant Build",false);
        settings.gameOptions.onlyOnePalace = myINIFile.getBoolValue("Game Options","Only One Palace",false);
        settings.gameOptions.rocketTurretsNeedPower = myINIFile.getBoolValue("Game Options","Rocket-Turrets Need Power",false);
        settings.gameOptions.sandwormsRespawn = myINIFile.getBoolValue("Game Options","Sandworms Respawn",false);
        settings.gameOptions.killedSandwormsDropSpice = myINIFile.getBoolValue("Game Options","Killed Sandworms Drop Spice",false);
        settings.gameOptions.daynight = myINIFile.getBoolValue("Game Options","Day Night Cycle",false);
        settings.gameOptions.dayscale = (Uint8)myINIFile.getIntValue("Game Options","Day Night Scale",false);

        fprintf(stdout, "loading texts....."); fflush(stdout);
        pTextManager = new TextManager();
        fprintf(stdout, "\t\tfinished\n"); fflush(stdout);

		if(FileManager::getMissingFiles().size() > 0) {
		    // set back to english
            std::vector<std::string> missingFiles = FileManager::getMissingFiles();
            fprintf(stderr,"The following files are missing for language \"%s\":\n",_("LanguageFileExtension").c_str());
            std::vector<std::string>::const_iterator iter;
            for(iter = missingFiles.begin(); iter != missingFiles.end(); ++iter) {
                fprintf(stderr," %s\n",iter->c_str());
            }
            fprintf(stderr,"Language is changed to English!\n");
            settings.general.language = "en";
		}

		for(int i=1; i < argc; i++) {
		    //check for overiding params
            std::string parameter(argv[i]);

			if((parameter == "-f") || (parameter == "--fullscreen")) {
				settings.video.fullscreen = true;
			} else if((parameter == "-w") || (parameter == "--window")) {
				settings.video.fullscreen = false;
			} else if(parameter.find("--PlayerName=") == 0) {
                settings.general.playerName = parameter.substr(strlen("--PlayerName="));
            } else if(parameter.find("--ServerPort=") == 0) {
                settings.network.serverPort = atol(argv[i] + strlen("--ServerPort="));
            }
		}

        if(bFirstInit == true) {
            fprintf(stdout, "initializing SDL..... \t\t"); fflush(stdout);
            if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO) < 0) {
                fprintf(stderr, "ERROR: Couldn't initialise SDL: %s\n", SDL_GetError());
                exit(EXIT_FAILURE);
            }
            fprintf(stdout, "finished\n"); fflush(stdout);
        }

		if(bFirstGamestart == true && bFirstInit == true) {
            // detect 800x600 screen resolution
            if(SDL_VideoModeOK(800, 600, 8, SDL_HWSURFACE | SDL_FULLSCREEN) > 0) {
                settings.video.width = 800;
                settings.video.height = 600;
                settings.video.preferredZoomLevel = 1;

                myINIFile.setIntValue("Video","Width",settings.video.width);
                myINIFile.setIntValue("Video","Height",settings.video.height);
                myINIFile.setIntValue("Video","Preferred Zoom Level",1);

                myINIFile.saveChangesTo(getConfigFilepath());
            }
		}

        Scaler::setDefaultScaler(Scaler::getScalerByName(settings.video.scaler));

		SDL_EnableUNICODE(1);
		SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
		char strenv[] = "SDL_VIDEO_CENTERED=center";
        SDL_putenv(strenv);
		SDL_WM_SetCaption("Dune Legacy", "Dune Legacy");

		if(bFirstInit == true) {
			fprintf(stdout, "initializing sound..... \t");fflush(stdout);
			if( Mix_OpenAudio(settings.audio.frequency, AUDIO_S16SYS, 2, 1024) < 0 ) {
				SDL_Quit();
				fprintf(stderr,"Warning: Couldn't set %d Hz 16-bit audio\n- Reason: %s\n",settings.audio.frequency,SDL_GetError());
				exit(EXIT_FAILURE);
			} else {
				fprintf(stdout, "allocated %d channels.\n", Mix_AllocateChannels(9)); fflush(stdout);
			}
		}

        pFileManager = new FileManager( !missingFiles.empty() );

        // now we can finish loading texts
        if(missingFiles.empty()) {
            pTextManager->loadData();
        }

        if(pFileManager->exists("IBM.PAL") == true) {
            palette = LoadPalette_RW(pFileManager->openFile("IBM.PAL"), true);
        } else {
            // create dummy palette for showing missing files info
            palette = Palette(256);
            palette[115].r = 202;
            palette[115].g = 141;
            palette[115].b = 16;
            palette[255].r = 255;
            palette[255].g = 255;
            palette[255].b = 255;
        }

		screen = NULL;
		setVideoMode();


		fprintf(stdout, "loading fonts...");fflush(stdout);
		pFontManager = new FontManager();
		fprintf(stdout, "\t\tfinished\n"); fflush(stdout);

		if(!missingFiles.empty()) {
		    // some files are missing
		    bExitGame = true;
		    printMissingFilesToScreen();
		    fprintf(stdout, "Deinitialize....."); fflush(stdout);
		} else {
		    // everything is just fine and we can start the game

            fprintf(stdout, "loading graphics..."); fflush(stdout);
            pGFXManager = new GFXManager();
            fprintf(stdout, "\t\tfinished\n"); fflush(stdout);

            fprintf(stdout, "loading sounds..."); fflush(stdout);
            pSFXManager = new SFXManager();
            fprintf(stdout, "\t\tfinished\n"); fflush(stdout);

            GUIStyle::setGUIStyle(new DuneStyle);

            if(bFirstInit == true) {
                fprintf(stdout, "starting sound player..."); fflush(stdout);
                soundPlayer = new SoundPlayer();
                fprintf(stdout, "\tfinished\n");

                fprintf(stdout, "starting music player...\t"); fflush(stdout);
                if(settings.audio.musicType == "directory") {
                    fprintf(stdout, "playing from music directory\n"); fflush(stdout);
                    musicPlayer = new DirectoryPlayer();
                } else if(settings.audio.musicType == "adl") {
                    fprintf(stdout, "playing ADL files\n"); fflush(stdout);
                    musicPlayer = new ADLPlayer();
                } else if(settings.audio.musicType == "xmi") {
                    fprintf(stdout, "playing XMI files\n"); fflush(stdout);
                    musicPlayer = new XMIPlayer();
                } else {
                    fprintf(stdout, "failed\n"); fflush(stdout);
                    exit(EXIT_FAILURE);
                }

                //musicPlayer->changeMusic(MUSIC_INTRO);
            }

            // Playing intro
            if(((bFirstGamestart == true) || (settings.general.playIntro == true)) && (bFirstInit==true)) {
                fprintf(stdout, "playing intro.....");fflush(stdout);
                Intro* pIntro = new Intro();
                pIntro->run();
                delete pIntro;
                fprintf(stdout, "\t\tfinished\n"); fflush(stdout);
            }

            bFirstInit = false;

            fprintf(stdout, "starting main menu...");fflush(stdout);
            MainMenu * myMenu = new MainMenu();
            fprintf(stdout, "\t\tfinished\n"); fflush(stdout);
            if(myMenu->showMenu() == MENU_QUIT_DEFAULT) {
                bExitGame = true;
            }
            delete myMenu;

            fprintf(stdout, "Deinitialize....."); fflush(stdout);

            GUIStyle::destroyGUIStyle();

            // clear everything
            if(bExitGame == true) {
                delete musicPlayer;
                delete soundPlayer;
                Mix_HaltMusic();
                Mix_CloseAudio();
            }

            delete pTextManager;
            delete pSFXManager;
            delete pGFXManager;
		}

		delete pFontManager;
		delete pFileManager;
		if(bExitGame == true) {
			SDL_Quit();
		}
		fprintf(stdout, "\t\tfinished\n"); fflush(stdout);
	} while(bExitGame == false);

	// deinit fnkdat
	if(fnkdat(NULL, NULL, 0, FNKDAT_UNINIT) < 0) {
		perror("Could not uninitialize fnkdat");
		exit(EXIT_FAILURE);
	}

	return EXIT_SUCCESS;
}
示例#2
0
	void AudioManager::quitAudio() {
		Roe::Music::quit();
		Roe::Sound::quit();
		Mix_CloseAudio();
		//Mix_Quit(); // not used in my old version
	}
示例#3
0
static VALUE Mixer_s_close(VALUE mod)
{
    Mix_CloseAudio();
    return Qnil;
}
示例#4
0
int main(int argc, char **argv)
{
	int audio_rate,audio_channels;
	Uint16 audio_format;
	Uint32 t;
	Mix_Music *music;
	int volume=SDL_MIX_MAXVOLUME;

	/* initialize SDL for audio and video */
	if(SDL_Init(SDL_INIT_AUDIO|SDL_INIT_VIDEO)<0)
		cleanExit("SDL_Init");
	atexit(SDL_Quit);

	int initted=Mix_Init(0);
	printf("Before Mix_Init SDL_mixer supported: ");
	print_init_flags(initted);
	initted=Mix_Init(~0);
	printf("After  Mix_Init SDL_mixer supported: ");
	print_init_flags(initted);
	Mix_Quit();

	if(argc<2 || argc>4)
	{
		fprintf(stderr,"Usage: %s filename [depth] [any 3rd argument...]\n"
				"    filename is any music file supported by your SDL_mixer library\n"
				"    depth is screen depth, default is 8bits\n"
				"    if there is a third argument given, we go fullscreen for maximum fun!\n",
				*argv);
		return 1;
	}


	/* open a screen for the wav output */
	if(!(s=SDL_SetVideoMode(W,H,(argc>2?atoi(argv[2]):8),(argc>3?SDL_FULLSCREEN:0)|SDL_HWSURFACE|SDL_DOUBLEBUF)))
		cleanExit("SDL_SetVideoMode");
	SDL_WM_SetCaption("sdlwav - SDL_mixer demo","sdlwav");
	
	/* hide the annoying mouse pointer */
	SDL_ShowCursor(SDL_DISABLE);
	/* get the colors we use */
	white=SDL_MapRGB(s->format,0xff,0xff,0xff);
	black=SDL_MapRGB(s->format,0,0,0);
	
	/* initialize sdl mixer, open up the audio device */
	if(Mix_OpenAudio(44100,MIX_DEFAULT_FORMAT,2,BUFFER)<0)
		cleanExit("Mix_OpenAudio");

	/* we play no samples, so deallocate the default 8 channels... */
	Mix_AllocateChannels(0);
	
	/* print out some info on the formats this run of SDL_mixer supports */
	{
		int i,n=Mix_GetNumChunkDecoders();
		printf("There are %d available chunk(sample) decoders:\n",n);
		for(i=0; i<n; ++i)
			printf("	%s\n", Mix_GetChunkDecoder(i));
		n = Mix_GetNumMusicDecoders();
		printf("There are %d available music decoders:\n",n);
		for(i=0; i<n; ++i)
			printf("	%s\n", Mix_GetMusicDecoder(i));
	}

	/* print out some info on the audio device and stream */
	Mix_QuerySpec(&audio_rate, &audio_format, &audio_channels);
	bits=audio_format&0xFF;
	sample_size=bits/8+audio_channels;
	rate=audio_rate;
	printf("Opened audio at %d Hz %d bit %s, %d bytes audio buffer\n", audio_rate,
			bits, audio_channels>1?"stereo":"mono", BUFFER );

	/* calculate some parameters for the wav display */
	dy=s->h/2.0/(float)(0x1<<bits);
	
	/* load the song */
	if(!(music=Mix_LoadMUS(argv[1])))
		cleanExit("Mix_LoadMUS(\"%s\")",argv[1]);

	{
		Mix_MusicType type=Mix_GetMusicType(music);
		printf("Music type: %s\n",
				type==MUS_NONE?"MUS_NONE":
				type==MUS_CMD?"MUS_CMD":
				type==MUS_WAV?"MUS_WAV":
				/*type==MUS_MOD_MODPLUG?"MUS_MOD_MODPLUG":*/
				type==MUS_MOD?"MUS_MOD":
				type==MUS_MID?"MUS_MID":
				type==MUS_OGG?"MUS_OGG":
				type==MUS_MP3?"MUS_MP3":
				type==MUS_MP3_MAD?"MUS_MP3_MAD":
				type==MUS_FLAC?"MUS_FLAC":
				"Unknown");
	}
	/* set the post mix processor up */
	Mix_SetPostMix(postmix,argv[1]);
	
	SDL_FillRect(s,NULL,black);
	SDL_Flip(s);
	SDL_FillRect(s,NULL,black);
	SDL_Flip(s);
	/* start playing and displaying the wav */
	/* wait for escape key of the quit event to finish */
	t=SDL_GetTicks();
	if(Mix_PlayMusic(music, 1)==-1)
		cleanExit("Mix_PlayMusic(0x%p,1)",music);
	Mix_VolumeMusic(volume);

	while((Mix_PlayingMusic() || Mix_PausedMusic()) && !done)
	{
		SDL_Event e;
		while(SDL_PollEvent(&e))
		{
			switch(e.type)
			{
				case SDL_KEYDOWN:
					switch(e.key.keysym.sym)
					{
						case SDLK_ESCAPE:
							done=1;
							break;
						case SDLK_LEFT:
							if(e.key.keysym.mod&KMOD_SHIFT)
							{
								Mix_RewindMusic();
								position=0;
							}
							else
							{
								int pos=position/audio_rate-1;
								if(pos<0)
									pos=0;
								Mix_SetMusicPosition(pos);
								position=pos*audio_rate;
							}
							break;
						case SDLK_RIGHT:
							switch(Mix_GetMusicType(NULL))
							{
								case MUS_MP3:
									Mix_SetMusicPosition(+5);
									position+=5*audio_rate;
									break;
								case MUS_OGG:
								case MUS_FLAC:
								case MUS_MP3_MAD:
								/*case MUS_MOD_MODPLUG:*/
									Mix_SetMusicPosition(position/audio_rate+1);
									position+=audio_rate;
									break;
								default:
									printf("cannot fast-forward this type of music\n");
									break;
							}
							break;
						case SDLK_UP:
							volume=(volume+1)<<1;
							if(volume>SDL_MIX_MAXVOLUME)
								volume=SDL_MIX_MAXVOLUME;
							Mix_VolumeMusic(volume);
							break;
						case SDLK_DOWN:
							volume>>=1;
							Mix_VolumeMusic(volume);
							break;
						case SDLK_SPACE:
							if(Mix_PausedMusic())
								Mix_ResumeMusic();
							else
								Mix_PauseMusic();
							break;
						default:
							break;
					}
					break;
				case SDL_QUIT:
					done=1;
					break;
				default:
					break;
			}
		}
		/* the postmix processor tells us when there's new data to draw */
		if(need_refresh)
			refresh();
		SDL_Delay(0);
	}
	t=SDL_GetTicks()-t;
	
	/* free & close */
	Mix_FreeMusic(music);
	Mix_CloseAudio();
	SDL_Quit();
	/* show a silly statistic */
	printf("fps=%.2f\n",((float)flips)/(t/1000.0));
	return(0);
}
示例#5
0
void Audio::quit()
{
    Mix_FreeMusic(this->audio);
    Mix_CloseAudio();
}
	/*****************************************************************
	 * Função responsavel por liberar todos os SubSistemas alocados
	 * pela Api SDL
	 *
	 ****************************************************************/
	void Initializer::Shutdown(void) 
	{   
		TTF_Quit();
		Mix_CloseAudio();
		SDL_Quit();
	}
示例#7
0
void	wolf3d_audio_release(t_wolf3d *wolf)
{
	Mix_FreeChunk(wolf->music);
	wolf->music = NULL;
	Mix_CloseAudio();
}
int main(int argc, char *argv[])
{
	// init fnkdat
	if(fnkdat(NULL, NULL, 0, FNKDAT_INIT) < 0) {
      perror("Could not initialize fnkdat");
      exit(EXIT_FAILURE);
	}

	bool bShowDebug = false;
    for(int i=1; i < argc; i++) {
	    //check for overiding params
		if (strcmp(argv[i], "--showlog") == 0)
			bShowDebug = true;
	}

	if(bShowDebug == false) {
        int d = open(GetLogFilepath().c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
        if(d < 0) {
            perror("Opening logfile failed");
            exit(EXIT_FAILURE);
        }

        if(dup2(d, STDOUT_FILENO) < 0) {
            perror("Redirecting stdout failed");
            exit(EXIT_FAILURE);
        }

        if(dup2(d, STDERR_FILENO) < 0) {
            perror("Redirecting stderr failed");
            exit(EXIT_FAILURE);
        }
	}

    // First check for missing files
    std::vector<std::string> MissingFiles = FileManager::getMissingFiles(LNG_ENG);

    if(MissingFiles.size() > 0) {
        // create data directory inside config directory
        char tmp[FILENAME_MAX];
        fnkdat("data/", tmp, FILENAME_MAX, FNKDAT_USER | FNKDAT_CREAT);

        bool cannotShowMissingScreen = false;
        fprintf(stderr,"The following files are missing:\n");
        std::vector<std::string>::const_iterator iter;
        for(iter = MissingFiles.begin() ; iter != MissingFiles.end(); ++iter) {
            fprintf(stderr," %s\n",iter->c_str());
            if(iter->find("LEGACY.PAK") != std::string::npos) {
                cannotShowMissingScreen = true;
            }
        }

        fprintf(stderr,"Put them in one of the following directories:\n");
        std::vector<std::string> searchPath = FileManager::getSearchPath();
        std::vector<std::string>::const_iterator searchPathIter;
        for(searchPathIter = searchPath.begin(); searchPathIter != searchPath.end(); ++searchPathIter) {
            fprintf(stderr," %s\n",searchPathIter->c_str());
        }

        if(cannotShowMissingScreen == true) {
            return EXIT_FAILURE;
        }
    }

	bool ExitGame = false;
	bool FirstInit = true;
	bool FirstGamestart = false;

    debug = false;
    cursorFrame = UI_CursorNormal;

	do {
		int seed = time(NULL);
		srand(seed);

        // check if configfile exists
        std::string configfilepath = GetConfigFilepath();
        if(ExistsFile(configfilepath) == false) {
            int UserLanguage = GetUserLanguage();
            if(UserLanguage == LNG_UNKNOWN) {
                UserLanguage = LNG_ENG;
            }

            if(MissingFiles.empty() == true) {
                // if all pak files were found we can create the ini file
                FirstGamestart = true;
                CreateDefaultConfigFile(configfilepath, UserLanguage);
            }
        }

		INIFile myINIFile(configfilepath);

		settings.General.PlayIntro = myINIFile.getBoolValue("General","Play Intro",false);
		settings.General.ConcreteRequired = myINIFile.getBoolValue("General","Concrete Required",true);
        settings.General.FogOfWar = myINIFile.getBoolValue("General","Fog of War",false);
		settings.General.PlayerName = myINIFile.getStringValue("General","Player Name","Player");
		settings.Video.Width = myINIFile.getIntValue("Video","Width",640);
		settings.Video.Height = myINIFile.getIntValue("Video","Height",480);
		settings.Video.Fullscreen = myINIFile.getBoolValue("Video","Fullscreen",true);
		settings.Video.DoubleBuffering = myINIFile.getBoolValue("Video","Double Buffering",true);
		settings.Video.FrameLimit = myINIFile.getBoolValue("Video","FrameLimit",true);
		settings.Audio.MusicType = myINIFile.getStringValue("Audio","Music Type","adl");
		std::string Lng = myINIFile.getStringValue("General","Language","en");
		if(Lng == "en") {
			settings.General.setLanguage(LNG_ENG);
		} else if (Lng == "fr") {
			settings.General.setLanguage(LNG_FRE);
		} else if (Lng == "de") {
			settings.General.setLanguage(LNG_GER);
		} else {
			fprintf(stderr,"INI-File: Invalid Language \"%s\"! Default Language (en) is used.\n",Lng.c_str());
			settings.General.setLanguage(LNG_ENG);
		}

		if(FileManager::getMissingFiles(settings.General.Language).size() > 0) {
		    // set back to english
            std::vector<std::string> MissingFiles = FileManager::getMissingFiles(settings.General.Language);
            fprintf(stderr,"The following files are missing for language \"%s\":\n",settings.General.LanguageExt.c_str());
            std::vector<std::string>::const_iterator iter;
            for(iter = MissingFiles.begin() ; iter != MissingFiles.end(); ++iter) {
                fprintf(stderr," %s\n",iter->c_str());
            }
            fprintf(stderr,"Language is changed to English!\n");
            settings.General.setLanguage(LNG_ENG);
		}

		lookDist[0] = 10;lookDist[1] = 10;lookDist[2] = 9;lookDist[3] = 9;lookDist[4] = 9;lookDist[5] = 8;lookDist[6] = 8;lookDist[7] = 7;lookDist[8] = 6;lookDist[9] = 4;lookDist[10] = 1;


		for(int i=1; i < argc; i++) {
		    //check for overiding params
			if((strcmp(argv[i], "-f") == 0) || (strcmp(argv[i], "--fullscreen") == 0))
				settings.Video.Fullscreen = true;
			else if((strcmp(argv[i], "-w") == 0) || (strcmp(argv[i], "--window") == 0))
				settings.Video.Fullscreen = false;
		}

		if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO) < 0) {
			fprintf(stderr, "ERROR: Couldn't initialise SDL: %s\n", SDL_GetError());
			exit(EXIT_FAILURE);
		}

		if(FirstGamestart == true && FirstInit == true) {
            // detect 800x600 screen resolution
            if(SDL_VideoModeOK(800, 600, 8, SDL_HWSURFACE | SDL_FULLSCREEN) > 0) {
                settings.Video.Width = 800;
                settings.Video.Height = 600;

                myINIFile.setIntValue("Video","Width",settings.Video.Width);
                myINIFile.setIntValue("Video","Height",settings.Video.Height);

                myINIFile.SaveChangesTo(GetConfigFilepath());
            }
		}

		SDL_EnableUNICODE(1);
		SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
		char strenv[] = "SDL_VIDEO_CENTERED=center";
        SDL_putenv(strenv);
		SDL_WM_SetCaption("Dune Legacy", "Dune Legacy");

		if(FirstInit == true) {
			fprintf(stdout, "initialising sound..... \t");fflush(stdout);
			if( Mix_OpenAudio(22050, AUDIO_S16SYS, 2, 1024) < 0 ) {
				SDL_Quit();
				fprintf(stderr,"Warning: Couldn't set 22050 Hz 16-bit audio\n- Reason: %s\n",SDL_GetError());
				exit(EXIT_FAILURE);
			} else {
				fprintf(stdout, "allocated %d channels.\n", Mix_AllocateChannels(4)); fflush(stdout);
			}
		}

        pFileManager = new FileManager( (MissingFiles.size() > 0) );

        if(pFileManager->exists("IBM.PAL") == true) {
            palette = LoadPalette_RW(pFileManager->OpenFile("IBM.PAL"), true);
        } else {
            // create dummy palette for showing missing files info
            palette = Palette(256);
            palette[255].r = 255;
            palette[255].g = 255;
            palette[255].b = 255;
        }

		screen = NULL;
		setVideoMode();


		fprintf(stdout, "loading fonts.....");fflush(stdout);
		pFontManager = new FontManager();

		fprintf(stdout, "\t\tfinished\n"); fflush(stdout);

		if(MissingFiles.size() > 0) {
		    // some files are missing
		    ExitGame = true;
		    PrintMissingFilesToScreen();
		    fprintf(stdout, "Deinitialize....."); fflush(stdout);
		} else {
		    // everything is just fine and we can start the game

            //get the house palettes
            houseColor[HOUSE_ATREIDES]  =   COLOR_ATREIDES;
            houseColor[HOUSE_ORDOS]     =   COLOR_ORDOS;
            houseColor[HOUSE_HARKONNEN] =   COLOR_HARKONNEN;
            houseColor[HOUSE_SARDAUKAR] =   COLOR_SARDAUKAR;
            houseColor[HOUSE_FREMEN]    =   COLOR_FREMEN;
            houseColor[HOUSE_MERCENARY] =   COLOR_MERCENARY;

            fprintf(stdout, "loading graphics....."); fflush(stdout);
            if((pGFXManager = new GFXManager()) == NULL) {
                fprintf(stderr,"main: Cannot create GFXManager!\n");
                exit(EXIT_FAILURE);
            }
            fprintf(stdout, "\t\tfinished\n"); fflush(stdout);

            fprintf(stdout, "loading sounds....."); fflush(stdout);
            if((pSFXManager = new SFXManager()) == NULL) {
                fprintf(stderr,"main: Cannot create SFXManager!\n");
                exit(EXIT_FAILURE);
            }
            fprintf(stdout, "\t\tfinished\n"); fflush(stdout);

            fprintf(stdout, "loading texts....."); fflush(stdout);
            if((pTextManager = new TextManager()) == NULL) {
                fprintf(stderr,"main: Cannot create TextManager!\n");
                exit(EXIT_FAILURE);
            }
            fprintf(stdout, "\t\tfinished\n"); fflush(stdout);

            GUIStyle::SetGUIStyle(new DuneStyle);

            if(FirstInit == true) {
                fprintf(stdout, "starting sound player..."); fflush(stdout);
                soundPlayer = new SoundPlayer();
                fprintf(stdout, "\tfinished\n");

                fprintf(stdout, "starting music player...\t"); fflush(stdout);
                if(settings.Audio.MusicType == "directory") {
                    fprintf(stdout, "playing from music directory\n"); fflush(stdout);
                    musicPlayer = new DirectoryPlayer();
                } else if(settings.Audio.MusicType == "adl") {
                    fprintf(stdout, "playing ADL files\n"); fflush(stdout);
                    musicPlayer = new ADLPlayer();
                } else if(settings.Audio.MusicType == "xmi") {
                    fprintf(stdout, "playing XMI files\n"); fflush(stdout);
                    musicPlayer = new XMIPlayer();
                } else {
                    fprintf(stdout, "failed\n"); fflush(stdout);
                    exit(EXIT_FAILURE);
                }

                //musicPlayer->changeMusic(MUSIC_INTRO);
            }

            // Playing intro
            if(((FirstGamestart == true) || (settings.General.PlayIntro == true)) && (FirstInit==true)) {
                fprintf(stdout, "playing intro.....");fflush(stdout);
                Intro* pIntro = new Intro();

                pIntro->run();

                delete pIntro;
                fprintf(stdout, "\t\tfinished\n"); fflush(stdout);
            }

            FirstInit = false;

            fprintf(stdout, "starting main menu.......");fflush(stdout);

            MainMenu * myMenu = new MainMenu();

            fprintf(stdout, "\tfinished\n"); fflush(stdout);

            if(myMenu->showMenu() == -1) {
                ExitGame = true;
            }
            delete myMenu;

            fprintf(stdout, "Deinitialize....."); fflush(stdout);

            GUIStyle::DestroyGUIStyle();

            // clear everything
            if(ExitGame == true) {
                delete musicPlayer;
                delete soundPlayer;
                Mix_HaltMusic();
                Mix_CloseAudio();
            }

            delete pTextManager;
            delete pSFXManager;
            delete pGFXManager;
		}

		delete pFontManager;
		delete pFileManager;
		if(ExitGame == true) {
			SDL_Quit();
		}
		fprintf(stdout, "\t\tfinished\n"); fflush(stdout);
	} while(ExitGame == false);

	// deinit fnkdat
	if(fnkdat(NULL, NULL, 0, FNKDAT_UNINIT) < 0) {
		perror("Could not uninitialize fnkdat");
		exit(EXIT_FAILURE);
	}

	return EXIT_SUCCESS;
}
示例#9
0
int usdxMain(int argc, char ** argv)
{
	try
	{
		const char * windowTitle = USDXVersionStr();

		if (Platform::TerminateIfAlreadyRunning(windowTitle))
			return 1;

		// fix the locale for string-to-float parsing in C-libs
		Common::SetDefaultNumericLocale();

		// initialize SDL
		// without SDL_INIT_TIMER SDL_GetTicks() might return strange values
		if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER) == -1)
			return 1;

		// initialize SDL_mixer
		if (Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 4096) == -1)
			return 1;

		SDL_StartTextInput();

		// create LuaCore first so other classes can register their events
		new LuaCore();

		// load the command-line arguments
		Params.Load(argc, argv);

		// Setup the logger/benchmarker
		new Log();
		sLog.BenchmarkStart(0);

		// Setup the texture manager
		new TextureMgr();

		// Language
		sLog.BenchmarkStart(1);
		sLog.Status("Initialize Paths", "Initialization");
		InitializePaths();
		sLog.Status("Load Language", "Initialization");
		new Language();

		// Add const values
		sLanguage.AddConst("US_VERSION", USDXVersionStr());
		sLog.BenchmarkEnd(1);
		sLog.Benchmark(1, "Loading Language");

		// Skins
		sLog.BenchmarkStart(1);
		sLog.Status("Loading Skin List", "Initialization");
		new Skins();
		sLog.BenchmarkEnd(1);
		sLog.Benchmark(1, "Loading Skin List");

		// Themes
		sLog.BenchmarkStart(1);
		sLog.Status("Loading Theme List", "Initialization");
		new Themes();
		sLog.BenchmarkEnd(1);
		sLog.Benchmark(1, "Loading Theme List");

		// INI file
		sLog.BenchmarkStart(1);
		sLog.Status("Loading INI", "Initialization");
		new Ini();
		sIni.Load();

		// Set the language.
		// NOTE: Command-line takes precedence.
		if (!Params.LanguageName.empty())
			sLanguage.ChangeLanguage(Params.LanguageName);
		else
			sLanguage.ChangeLanguage(sIni.LanguageName);
		
		// It is possible that this is the first run, so create an .ini file if necessary.
		sLog.Status("Writing INI", "Initialization");
		sIni.Save();

		sLog.BenchmarkEnd(1);
		sLog.Benchmark(1, "Loading INI");

		// Sound
		sLog.BenchmarkStart(1);
		sLog.Status("Initialize Sound", "Initialization");
		new SoundLibrary();
		sLog.BenchmarkEnd(1);
		sLog.Benchmark(1, "Initializing Sound");

		// Lyrics engine with media reference timer
		// new LyricsState();
		
		// Theme
		sLog.BenchmarkStart(1);
		sLog.Status("Load Theme", "Initialization");
		sThemes.LoadTheme(sIni.Theme, sIni.ThemeColor);
		sLog.BenchmarkEnd(1);
		sLog.Benchmark(1, "Loading Theme");

		// Covers cache
		sLog.BenchmarkStart(1);
		sLog.Status("Creating Covers cache", "Initialization");
		// new Covers();
		sLog.BenchmarkEnd(1);
		sLog.Benchmark(1, "Loading Covers cache");

		// Category covers
		sLog.BenchmarkStart(1);
		sLog.Status("Creating Category Covers array", "Initialization");
		// new CatCovers();
		sLog.BenchmarkEnd(1);
		sLog.Benchmark(1, "Loading Category Covers array");

		// Songs
		sLog.BenchmarkStart(1);
		sLog.Status("Creating song array", "Initialization");
		// new Songs();
		sLog.Status("Creating 2nd song array", "Initialization");
		// new CatSongs();
		sLog.BenchmarkEnd(1);
		sLog.Benchmark(1, "Loading songs");

		// Graphics
		sLog.BenchmarkStart(1);
		sLog.Status("Initialize 3D", "Initialization");
		Initialize3D(windowTitle);
		sLog.BenchmarkEnd(1);
		sLog.Benchmark(1, "Initializing 3D");

		// Score saving
		sLog.BenchmarkStart(1);
		sLog.Status("Loading database", "Initialization");
		new Database();
		if (ScoreFile.empty())
		{
			Platform::GetGameUserPath(&ScoreFile);
			ScoreFile /= "Ultrastar.db";
		}
		sDatabase.Init(ScoreFile);
		sLog.BenchmarkEnd(1);
		sLog.Benchmark(1, "Loading database");

		// Playlist manager
		sLog.BenchmarkStart(1);
		sLog.Status("Playlist manager", "Initialization");
		// new PlaylistManager();
		sLog.BenchmarkEnd(1);
		sLog.Benchmark(1, "Loading playlist manager");

		// Effect manager (for the twinkling golden stars and such)
		sLog.BenchmarkStart(1);
		sLog.Status("Effect manager", "Initialization");
		// new EffectManager();
		sLog.BenchmarkEnd(1);
		sLog.Benchmark(1, "Loading effect manager");

		// Joypad
		if (sIni.Joypad || Params.Joypad)
		{
			sLog.BenchmarkStart(1);
			sLog.Status("Joystick", "Initialization");
			// new Joystick();
			sLog.BenchmarkEnd(1);
			sLog.Benchmark(1, "Loading joystick");
		}

		// Party manager
		sLog.BenchmarkStart(1);
		sLog.Status("Party manager", "Initialization");
		// new PartyGame();
		sLog.BenchmarkEnd(1);
		sLog.Benchmark(1, "Loading party manager");

		// Lua
		sLog.BenchmarkStart(1);
		// sLuaCore.RegisterModule("Log",        LuaLog_Lib_f);
		// sLuaCore.RegisterModule("Gl",         LuaGl_Lib_f);
		// sLuaCore.RegisterModule("TextGl",     LuaTextGl_Lib_f);
		// sLuaCore.RegisterModule("Party",      LuaParty_Lib_f);
		// sLuaCore.RegisterModule("ScreenSing", LuaScreenSing_Lib_f);
		sLog.BenchmarkEnd(1);
		sLog.Benchmark(1, "Initializing LuaCore");

		// Lua plugins
		sLog.BenchmarkStart(1);
		sLuaCore.LoadPlugins();
		sLog.BenchmarkEnd(1);
		sLog.Benchmark(1, "Loading Lua plugins");
		sLuaCore.DumpPlugins();

		sLog.BenchmarkEnd(0);
		sLog.Benchmark(0, "Loading time");

		// Prepare software cursor
		sDisplay.SetCursor();

		// Start background music
		sSoundLib.StartBgMusic();
		
		// Check microphone settings, go to record options if they are incorrect
		/*
		int badPlayer = AudioInputProcessor::ValidateSettings();
		if (badPlayer >= 0)
		{
			ScreenPopupError::ShowPopup("ERROR_PLAYER_DEVICE_ASSIGNMENT", BadPlayer + 1);
			sDisplay.CurrentScreen->FadeTo(&ScreenOptionsRecord);
		}
		*/

		// Start main loop
		sLog.Status("Main loop", "Initialization");
		usdxMainLoop();
	}
	catch (const CriticalException& e)
	{
		printf("Critical exception occurred: %s\n", e.what());
	}
	catch (const std::exception& e)
	{
		printf("Unhandled exception occurred: %s\n", e.what());
	}
	catch (...)
	{
		printf("Unhandled exception occurred.\n");
	}

	FreeGfxResources();

	// delete PartyGame::getSingletonPtr();
	// delete Joystick::getSingletonPtr();
	// delete EffectManager::getSingletonPtr();
	// delete PlaylistManager::getSingletonPtr();
	delete Database::getSingletonPtr();
	// delete CatSongs::getSingletonPtr();
	// delete Songs::getSingletonPtr();
	// delete CatCovers::getSingletonPtr();
	// delete Covers::getSingletonPtr();
	// delete LyricsState::getSingletonPtr();
	delete Ini::getSingletonPtr();
	delete Themes::getSingletonPtr();
	delete Skins::getSingletonPtr();
	delete Language::getSingletonPtr();
	delete TextureMgr::getSingletonPtr();
	delete Log::getSingletonPtr();
	delete LuaCore::getSingletonPtr();
	delete SoundLibrary::getSingletonPtr();

	SDL_StopTextInput();
	Mix_CloseAudio();
	SDL_Quit();

	return 0;
}
示例#10
0
int SoundMix::Quit()
{
	Mix_CloseAudio();
	return true;
}
示例#11
0
DKAudio::~DKAudio()
{
	Mix_FreeChunk(sound);
	Mix_CloseAudio();
}
示例#12
0
int main( int argc , char* argv[] )
{
	//  Create access to the InputSystem and an SDL_Window
	InputSystem*	input = InputSystem::Get_Instance();
	SDL_Window		window;

	//  Define the window. If the window definition fails, return a failure flag.
	if ( !window.Define_Window( WINDOW_WIDTH , WINDOW_HEIGHT , 32 , false , "MenuDialog System (build 0001)" ) ) return -1;

	// Initialize SDL_Mixer
	if( Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 4096 ) == -1 )
	{
		char* error = SDL_GetError();
		return -2;
	}
	music = Mix_LoadMUS( "Sounds/Mario - Star.wav" ); 

	//  Create a Menu Dialog. If the dialog creation fails, return a failure flag.
	test_dialog = MenuDialog::CreateMenuDialog( "TestMenuDialog" );
	if (test_dialog == NULL) return -3;

	test_dialog->Load_Bitmap_Font("Arial");

	MenuElement_CheckBox* check_box_test = dynamic_cast<MenuElement_CheckBox*>(test_dialog->Get_Element("CheckBoxTest"));
	if (check_box_test)
	{
		check_box_test->Set_Check_Event(&Set_Text_Block);
	}

	MenuElement_TextureButton* texture_button_test = dynamic_cast<MenuElement_TextureButton*>(test_dialog->Get_Element("TextureButtonTest"));
	if (texture_button_test)
	{
		texture_button_test->Set_Click_Event(&Set_Text_Block);
	}

	MenuElement_TextButton* text_button_test = dynamic_cast<MenuElement_TextButton*>(test_dialog->Get_Element("TextButtonTest"));
	if (text_button_test != NULL)
	{
		text_button_test->Set_Text("The quick red fox jumped over the lazy brown dog. Testing!");
		text_button_test->Set_Click_Event(&Set_Text_Block);
	}

	MenuElement_DropDown* drop_down_test = dynamic_cast<MenuElement_DropDown*>(test_dialog->Get_Element("DropDownTest"));
	if (drop_down_test != NULL)
	{
		drop_down_test->Add_Item("TestString1");
		drop_down_test->Add_Item("TestString2");
		drop_down_test->Add_Item("TestString3");
		drop_down_test->Set_Selection_Event(&Set_Text_Block);
	}
	
	MenuElement_TextBlock* text_block_test = dynamic_cast<MenuElement_TextBlock*>(test_dialog->Get_Element("TextBlockTest"));
	if (text_block_test != NULL)
	{
		text_block_test->Set_Text("This is a test of the string parsing functionality of the text block menu element. These words should parse down to multiple strings that render in lines downward.");
	}

	MenuElement_ListBox* list_box_test = dynamic_cast<MenuElement_ListBox*>(test_dialog->Get_Element("ListBoxTest"));
	if (list_box_test != NULL)
	{
		list_box_test->Add_Item("TestString2");
		list_box_test->Add_Item("TestString3");
		list_box_test->Add_Item("TestString4");
		list_box_test->Add_Item("TestString5");
		list_box_test->Add_Item("TestString6");
		list_box_test->Add_Item("TestString7");
		list_box_test->Add_Item("TestString8");
		list_box_test->Add_Item("TestString9");
		list_box_test->Add_Item("TestString10");
		list_box_test->Set_Selection_Event(&Set_Text_Block);
	}
	
	MenuElement_EditBox* edit_box_test = dynamic_cast<MenuElement_EditBox*>(test_dialog->Get_Element("EditBoxTest"));
	if (edit_box_test != NULL)
	{
		edit_box_test->Set_Text("Testing");
	}


	// Set up the general information for the rendering of the window through OpenGL
	glClearColor(0.4f, 0.4f, 0.4f, 1.0f);
	glClearDepth(1.0f);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);
	glEnable(GL_BLEND);
	glEnable(GL_ALPHA_TEST);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glAlphaFunc(GL_GREATER, 0.02f);

	//  Process any events from the Operating System
	while (SDL_ProcessEvents( input ))
	{
		if (input->Get_Key(27)) break;		// 27 : ESCAPE

		// Get the time slice
		static float time_slice;
		static int elapsed_time[2];
		elapsed_time[0] = SDL_GetTicks();
		time_slice = std::max(std::min((float)(elapsed_time[0] - elapsed_time[1]) / 1000.0f, 1.0f), 0.1f);
		elapsed_time[1] = elapsed_time[0];

		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		
		// Initiate the 2D Rendering Context
		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		gluOrtho2D(0, (GLdouble)WINDOW_WIDTH, (GLdouble)WINDOW_HEIGHT, 0);
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();

		test_dialog->Input( input );
		test_dialog->Update( time_slice );
		test_dialog->Render();

		SDL_GL_SwapBuffers();
		input->Invalidate_Old_Input();
	}

	Mix_FreeMusic( music ); 
	Mix_CloseAudio();

	return 0;
}
示例#13
0
SoundManager::~SoundManager()
{
    Mix_CloseAudio();
}
int main( int argc, char* args[] )
{
 SDL_Init(SDL_INIT_EVERYTHING);
 Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 1, 4096 );
 //screen=SDL_SetVideoMode((LIN_MAX+1)*40,(COL_MAX+1)*40,32,SDL_FULLSCREEN/*SDL_SWSURFACE*/);
 screen=SDL_SetVideoMode(0,0,32,SDL_FULLSCREEN);
 TTF_Init();
 font=TTF_OpenFont("font2.ttf",40);
 music=Mix_LoadMUS("bck.wav");
 clear=SDL_LoadBMP("wooden_background.bmp");
 apply_surface(0,0,clear,screen);
 if(mute==0)
    Mix_PlayMusic(music, -1 );
 load_level("a");
 print_level();
 //welcome_message();
 clear=SDL_LoadBMP("clear.bmp");
 print_background();
 burn=SDL_LoadBMP("fire.bmp");
 background=SDL_LoadBMP("name_background.bmp");
 message=TTF_RenderText_Solid(font,"Player 2",color1);
 apply_surface((COL_MAX+COL_START+2)*40,0,background,screen);
 apply_surface((COL_MAX+COL_START+2)*40+5,0,message,screen);
 SDL_Flip(screen);
 message=TTF_RenderText_Solid(font,"Player 1",color1);
 apply_surface((0)*40,0,background,screen);
 apply_surface((0)*40+5,0,message,screen);
 SDL_Flip(screen);
 player=SDL_LoadBMP("warrior_on_grass.bmp");
 player1=SDL_LoadBMP("warrior1_on_grass.bmp");
 obs[player2.lin][player2.col]=2;
 obs[player1.lin][player1.col]=3;
 print_hp(player2.hp,1,COL_MAX+COL_START+2);
 print_hp(player1.hp,1,0);
 print_mana(player2.mana,2,COL_MAX+COL_START+2);
 print_mana(player2.mana,2,0);
 time_ex=0;
 if(mute<=1)
    sound=Mix_LoadWAV("hit.wav");
 print_level();
 int start_t=0;
 put_arena_wall();
 player1_load_save("player1");
 player2_load_save("player2");
 while(keystates[SDLK_ESCAPE]==NULL && player1.hp>0 && player2.hp>0)
       {flag_player=0;
	   t=time(NULL);
        if(t-t1>=2)
           {
            start_t++;
            if(start_t>=4)
               {
			    clear_arena_wall();
               }
            t1=t;
            if(player2.mana<=99)
			{
			 player2.mana++;
			 print_mana(player2.mana,2,COL_MAX+COL_START+2);
			}
		  if(player1.mana<=99)
			{
			 player1.mana++;
			 print_mana(player1.mana,2,0);
			}
            //load_level("a");
            print_level();
            player2.permission=player1.permission=0;
           }
	   if(t-t2>=1)
		 {
		  t2=t;
		  player2.permission_basic=player1.permission_basic=0;
		 }
        up=keystates[SDLK_UP];
        down=keystates[SDLK_DOWN];
        right=keystates[SDLK_RIGHT];
        left=keystates[SDLK_LEFT];
        atack_left=keystates[SDLK_RCTRL];
        atack_right=keystates[SDLK_RCTRL];
        power1=keystates[SDLK_u];
        power2=keystates[SDLK_i];
        power3=keystates[SDLK_o];
        power4=keystates[SDLK_p];
        atack1_left=keystates[SDLK_z];
        atack1_right=keystates[SDLK_z];
        if(power1==1 && player2.mana>=10 && player2.hp<=90)
           {
            player2.mana-=10;
            player2.hp+=10;
            print_mana(player2.mana,2,COL_MAX+COL_START+2);
            print_hp(player2.hp,1,COL_MAX+COL_START+2);
           }
        if(power2==1 && player2.mana>=30 && player2.permission==0)
           {
            player2.mana-=30;
            player2.permission=1;
            if(max(player1.lin,player2.lin)-min(player1.lin,player2.lin)<=2 && max(player1.col,player2.col)-min(player1.col,player2.col)<=2)
               {
                player1.hp-=40+player2.fire_dmg*3/10-player1.fire_res*3/10;
                print_hp(player1.hp,1,0);
               }
            if(player2.lin-2<=0)
               beg1=1;
            else
               beg1=player2.lin-2;
            if(player2.lin+2>=LIN_MAX)
               end1=LIN_MAX;
            else
               end1=player2.lin+2;
            if(player2.col-2<=0)
               beg2=1;
            else
               beg2=player2.col-2;
            if(player2.col+2>=COL_MAX)
               end2=COL_MAX;
            else
               end2=player2.col+2;
            for(int i=beg1;i<=end1;i++)
                for(int j=beg2;j<=end2;j++)
                    {
                     if(obs[i][j]==0)
                        {
                         //get_burn(i,j);
                         //burn=SDL_LoadBMP("fire.bmp");
                         apply_surface((j+COL_START)*40,i*40,burn,screen);
                        }
                    }
            print_mana(player2.mana,2,COL_MAX+COL_START+2);
           }
        if(power3==1 && player2.hp>10)
           {
            player2.hp-=10;
            player2.mana+=10;
            print_mana(player2.mana,2,COL_MAX+COL_START+2);
            print_hp(player2.hp,1,COL_MAX+COL_START+2);
           }
        if(atack_left==1 && player2.permission_basic==0)
           {
            player=SDL_LoadBMP("warrior_on_grass_left.bmp");
            if(obs[player2.lin][player2.col-1]==3)
               {
			 player2.permission_basic=1;
			 player1.hp-=10+player2.attack/10-player1.block/10;
                print_hp(player1.hp,1,0);
                Mix_PlayChannel(-1, sound, 0);
               }
           }
        if(atack_right==1 && player2.permission_basic==0)
           {
            player=SDL_LoadBMP("warrior_on_grass.bmp");
            if(obs[player2.lin][player2.col+1]==3)
               {
			    player2.permission_basic=1;
			    player1.hp-=10+player2.attack/10-player1.block/10;
                print_hp(player1.hp,1,0);
                Mix_PlayChannel(-1, sound, 0);
               }
           }
        if(up==1 && player2.lin>1)
           {
            time_ex++;
            if(obs[player2.lin-1][player2.col]==0)
               {
                obs[player2.lin][player2.col]=0;
			 put_back(player2.lin,player2.col);
                player2.lin--;
                obs[player2.lin][player2.col]=2;
               }
           }
        if(down==1 && player2.lin<COL_MAX)
           {
		  time_ex++;
            if(obs[player2.lin+1][player2.col]==0)
               {
                obs[player2.lin][player2.col]=0;
			 put_back(player2.lin,player2.col);
                player2.lin++;
                obs[player2.lin][player2.col]=2;
               }
           }
        if(left==1 && player2.col>1)
           {
		  time_ex++;
            if(obs[player2.lin][player2.col-1]==0)
               {
                obs[player2.lin][player2.col]=0;
			 put_back(player2.lin,player2.col);
                player2.col--;
                obs[player2.lin][player2.col]=2;
                player=SDL_LoadBMP("warrior_on_grass_left.bmp");
               }
           }
        if(right==1 && player2.col<LIN_MAX)
           {
            time_ex++;
            if(obs[player2.lin][player2.col+1]==0)
               {
                obs[player2.lin][player2.col]=0;
			 put_back(player2.lin,player2.col);
                player2.col++;
                obs[player2.lin][player2.col]=2;
                player=SDL_LoadBMP("warrior_on_grass.bmp");
               }
           }
        apply_surface((player2.col+COL_START)*40,player2.lin*40,player,screen);
        up=keystates[SDLK_w];
        down=keystates[SDLK_s];
        right=keystates[SDLK_d];
        left=keystates[SDLK_a];
        power1=keystates[SDLK_1];
        power2=keystates[SDLK_2];
        power3=keystates[SDLK_3];
        power4=keystates[SDLK_4];
        if(power1==1 && player1.mana>=10 && player1.hp<=90)
           {
            player1.mana-=10;
            player1.hp+=10;
            print_mana(player1.mana,2,0);
            print_hp(player1.hp,1,0);
           }
        if(power2==1 && player1.mana>=30 && player1.permission==0)
           {
            player1.mana-=30;
            player1.permission=1;
            if(max(player2.lin,player1.lin)-min(player1.lin,player2.lin)<=2 && max(player1.col,player2.col)-min(player1.col,player2.col)<=2)
               {
                player2.hp-=40+player1.fire_dmg*3/10-player2.fire_res*3/10;
                print_hp(player2.hp,1,COL_MAX+COL_START+2);
               }
            if(player1.lin-2<=0)
               beg1=1;
            else
               beg1=player1.lin-2;
            if(player1.lin+2>=LIN_MAX)
               end1=LIN_MAX;
            else
               end1=player1.lin+2;
            if(player1.col-2<=0)
               beg2=1;
            else
               beg2=player1.col-2;
            if(player1.col+2>=COL_MAX)
               end2=COL_MAX;
            else
               end2=player1.col+2;
            for(int i=beg1;i<=end1;i++)
                for(int j=beg2;j<=end2;j++)
                    {
                     if(obs[i][j]==0)
                        {
                         //get_burn(i,j);
                         //burn=SDL_LoadBMP("fire.bmp");
                         apply_surface((j+COL_START)*40,i*40,burn,screen);
                        }
                    }
            print_mana(player1.mana,2,0);
           }
        if(power3==1 && player1.hp>10)
           {
            player1.hp-=10;
            player1.mana+=10;
            print_mana(player1.mana,2,0);
            print_hp(player1.hp,1,0);
           }
        if(atack1_left==1 && player1.permission_basic==0 && flag_player==0)
           {
            if(obs[player1.lin][player1.col-1]==2)
               {
			 player1.permission_basic=1;
                player1=SDL_LoadBMP("warrior1_on_grass_left.bmp");
			 player2.hp-=10+player1.attack/10-player2.block/10;
                //SDL_FreeSurface(player);
                print_hp(player2.hp,1,COL_MAX+COL_START+2);
                /*player2=SDL_LoadBMP("hit_warrior_on_grass.bmp");
                apply_surface(player2.col*40,player2.lin*40,player,screen);*/
                SDL_Flip(screen);
                Mix_PlayChannel(-1, sound, 0);
               }
           }
        if(atack1_right==1 && player1.permission_basic==0 && flag_player==0)
           {
            if(obs[player1.lin][player1.col+1]==2)
               {
			    player1.permission_basic=1;
                player1=SDL_LoadBMP("warrior1_on_grass.bmp");
			    player2.hp-=10+player1.attack/10-player2.block/10;
                print_hp(player2.hp,1,COL_MAX+COL_START+2);
                //SDL_FreeSurface(player);
                player2=SDL_LoadBMP("hit_warrior_on_grass.bmp");
                /*apply_surface(player2.col*40,player2.lin*40,player,screen);
                SDL_Flip(screen);*/
                Mix_PlayChannel(-1, sound, 0);
               }
           }
        if(up==1 && player1.lin>1)
           {
            time_ex++;
            if(obs[player1.lin-1][player1.col]==0)
               {
                obs[player1.lin][player1.col]=0;
			    put_back(player1.lin,player1.col);
                player1.lin--;
                obs[player1.lin][player1.col]=3;
               }
           }
        if(down==1 && player1.lin<COL_MAX)
           {
		  time_ex++;
            if(obs[player1.lin+1][player1.col]==0)
               {
                obs[player1.lin][player1.col]=0;
			    put_back(player1.lin,player1.col);
                player1.lin++;
                obs[player1.lin][player1.col]=3;
               }
           }
        if(left==1 && player1.col>1)
           {
            time_ex++;
            if(obs[player1.lin][player1.col-1]==0)
			{
			 obs[player1.lin][player1.col]=0;
			 put_back(player1.lin,player1.col);
                player1.col--;
                obs[player1.lin][player1.col]=3;
                player1=SDL_LoadBMP("warrior1_on_grass_left.bmp");
               }
           }
        if(right==1 && player1.col<LIN_MAX)
           {
            time_ex++;
            if(obs[player1.lin][player1.col+1]==0)
               {
                obs[player1.lin][player1.col]=0;
			 put_back(player1.lin,player1.col);
                player1.col++;
                obs[player1.lin][player1.col]=3;
                player1=SDL_LoadBMP("warrior1_on_grass.bmp");
               }
           }
        SDL_Delay(50);
        apply_surface((player1.col+COL_START)*40,player1.lin*40,player1,screen);
        SDL_Flip(screen);
        SDL_PumpEvents();
       }
 if(player2.hp>player1.hp)
    {
     player1=SDL_LoadBMP("dead_warrior1_on_grass.bmp");
     apply_surface((player1.col+COL_START)*40,player1.lin*40,player1,screen);
     message=TTF_RenderText_Solid(font,"Player 2 wins!",textColor);
     player2.money+=player2.hp+player2.mana+player1.money/50;
     player1.money+=player2.money/75+20;
     player2.xp+=100;
     player1.xp+=20;
    }
 else
    if(player2.hp!=player1.hp)
       {
        player=SDL_LoadBMP("dead_warrior_on_grass.bmp");
        apply_surface((player2.col+COL_START)*40,player2.lin*40,player,screen);
        message=TTF_RenderText_Solid(font,"Player 1 wins!",textColor);
        player1.money+=player1.hp+player1.mana+player2.money/50;
        player2.money+=player1.money/75+20;
        player1.xp+=100;
        player2.xp+=20;
       }
    else
       {
        player1=SDL_LoadBMP("dead_warrior1_on_grass.bmp");
        apply_surface((player1.col+COL_START)*40,player1.lin*40,player1,screen);
        player=SDL_LoadBMP("dead_warrior_on_grass.bmp");
        apply_surface((player2.col+COL_START)*40,player2.lin*40,player,screen);
	    message=TTF_RenderText_Solid(font,"Round draw!",textColor);
        int cash=(player2.money+player1.money)/2/25;
        player1.money+=cash;
        player2.money+=cash;
        player2.xp+=50;
        player1.xp+=50;
       }
 player1.save_player1("player1");
 player2.save_player("player2");
 Mix_CloseAudio();
 Mix_OpenAudio(22050,MIX_DEFAULT_FORMAT,2,4096);
 sound=Mix_LoadWAV("win.wav");
 Mix_PlayChannel(-1,sound,0);
 apply_surface(((COL_MAX+COL_START)/2-1)*40,(LIN_MAX/2-1)*40,message,screen);
 SDL_Flip(screen);
 SDL_Delay(2000);
 TTF_CloseFont(font);
 SDL_Quit();
return 0;
}
示例#15
0
int main()
{
    bool running;
    int fps;
    Mix_Music *music;
    snake s(840,640,20);
    Uint32 start;


    while(1)
    {

        s.Init();
        fps=6;
    //Intro

        Mix_OpenAudio(22050,AUDIO_S16SYS,2,128);
        music=Mix_LoadMUS("Music/stronger.mp3");
        Mix_PlayMusic(music,-1);
        music=Mix_LoadMUS("Music/snake.wav");
        s.Draw_Bg();
        s.WaitKey();
        Mix_PlayMusic(music,-1);
        s.Draw_Bg();
        s.Ready();
        s.Fill_Screen();
        SDL_Delay(2000);
        running=true;

        while(running)
        {

            start=SDL_GetTicks();
            running=s.Go_To();
            s.Draw_Bg();
            s.Draw_Border();
            s.Draw_Score();
            s.Draw_Food(&fps);
            s.Draw_Node();
            s.Fill_Screen();

            if(1000/fps>(int)(SDL_GetTicks()-start))
                SDL_Delay(1000/fps -SDL_GetTicks() +start);

        }

        Mix_FreeMusic(music);
        music=Mix_LoadMUS("Music/game_over.wav");
        Mix_PlayMusic(music,-1);

        SDL_Delay(800);
        s.Draw_Bg();
        s.Game_Over();
        s.Fill_Screen();
        SDL_Delay(4000);
        Mix_FreeMusic(music);
        Mix_CloseAudio();
    }


}
示例#16
0
int main( int argc, char* args[] )
{

    quit = 0;
    Tile *tiles[ TOTAL_TILES ];

    Timer fps;    levelwon = 0;

     //Initialize
        if( init() == false )
        {
            return 1;
        }

        if( TTF_Init() == -1 )
        {
            return false;
        }


        //Initialize SDL_mixer
        if( Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 4096 ) == -1 )
        {
            return false;
        }

 //Load the files
        if( load_files() == false )
        {
            return 1;
        }

        //Clip the tile sheeti
        if( Mix_PlayMusic( music, -1 ) == -1 ) { return 1; }

        clip_tiles();

        if(!welcome)return 1;
        SDL_BlitSurface(welcome, NULL, screen, NULL );
        SDL_Flip( screen );
        SDL_Delay(6000);

        robin robinp;

    while(quit ==false)
    {

        if(level!= 1)
        {
            SDL_BlitSurface( prepare, NULL, screen, NULL );
            SDL_Flip(screen);
            SDL_Delay(3000);
        }

        robinp.reset();

        //Set the tiles
        if( set_tiles( tiles ) == false )
        {
            return 1;
        }
       // SDL_Delay(3000);
        first=1;
    /////////////////////////////////////////////////////////////////////////////////////
        while( quit == false && levelwon == 0)///////////////////////////////////
        {

            //Start the frame timer
            fps.start();

            //While there's events to handle
            while( SDL_PollEvent( &event ) )
            {

              robinp.handle_events();


                //If the user has Xed out the window
                if( event.type == SDL_QUIT )
                {
                    //Quit the program
                    quit = true;
                }
            }

            SDL_BlitSurface( background, NULL, screen, NULL );


            robinp.move(tiles);
            robinp.set_camera();

         for( int t = 0; t < TOTAL_TILES; t++ )
            {
                tiles[ t ]->show();
            }


        for(int i=0;i< en_num;i++)
        {
            enemys[en_num]->show();        //robinp.reset();
        }


            robinp.show();
            showscore();

            //Update the screen
            if( SDL_Flip( screen ) == -1 )
            {
                return 1;
            }

            //Cap the frame rate
            if( fps.get_ticks() < 1000 / FRAMES_PER_SECOND )
            {
                SDL_Delay( ( 1000 / FRAMES_PER_SECOND ) - fps.get_ticks() );
            }


        }

        clean_up(tiles);
        level++;
        levelwon = 0;
    /////////////////////////////////////////////////////////////////////////////////////
        //cout<<"out of level";
    }


        SDL_FreeSurface( background );
        SDL_FreeSurface( gameover );
         SDL_FreeSurface( tileSheet );

        //Free the music
        Mix_FreeMusic( music );
        Mix_FreeChunk( jumpsou );
        Mix_FreeChunk( coinsou );
        Mix_FreeChunk( hitsou );
        Mix_FreeChunk( diamoundsou );

        //Close the font
        TTF_CloseFont( font );

        //Quit SDL_mixer
        Mix_CloseAudio();
          SDL_Quit();
        //Quit SDL_ttf
        TTF_Quit();

    return 0;

    }
示例#17
0
void AGameEngine::AudioPool::Destroy()
{
	Mix_CloseAudio();
}
示例#18
0
Audio_SDL::~Audio_SDL() {
  g_pErr->DFI("Audio_SDL::~Audio_SDL", m_id, 1);
  Mix_CloseAudio();
  g_pErr->DFO("Audio_SDL::~Audio_SDL", m_id, 1);
}
示例#19
0
SoundManager::SoundManager(const SoundManager&)
{
	Mix_CloseAudio();
}
示例#20
0
void EZX_SDL_mix_CloseAudio(void)
{
    Mix_CloseAudio();
}
示例#21
0
	InitSoundBuffer::~InitSoundBuffer() {
		--nbrOfInstances_;
		if (nbrOfInstances_ < 1) {
			Mix_CloseAudio();
		}
	}
示例#22
0
/*******************************************************************************
 Name:              AudioEngine
 Description:       Destructor
 ******************************************************************************/
AudioEngine::~AudioEngine()
{
    Mix_CloseAudio();
}
示例#23
0
/* Open the mixer with a certain desired audio format */
int Mix_OpenAudio(int frequency, Uint16 format, int nchannels, int chunksize)
{
	int i;
	SDL_AudioSpec desired;

	/* If the mixer is already opened, increment open count */
	if ( audio_opened ) {
		if ( format == mixer.format && nchannels == mixer.channels ) {
			++audio_opened;
			return(0);
		}
		while ( audio_opened ) {
			Mix_CloseAudio();
		}
	}

	/* Set the desired format and frequency */
	desired.freq = frequency;
	desired.format = format;
	desired.channels = nchannels;
	desired.samples = chunksize;
	desired.callback = mix_channels;
	desired.userdata = NULL;

	/* Accept nearly any audio format */
	if ( SDL_OpenAudio(&desired, &mixer) < 0 ) {
		return(-1);
	}
#if 0
	PrintFormat("Audio device", &mixer);
#endif

	/* Initialize the music players */
	if ( open_music(&mixer) < 0 ) {
		SDL_CloseAudio();
		return(-1);
	}

	num_channels = MIX_CHANNELS;
	mix_channel = (struct _Mix_Channel *) SDL_malloc(num_channels * sizeof(struct _Mix_Channel));

	/* Clear out the audio channels */
	for ( i=0; i<num_channels; ++i ) {
		mix_channel[i].chunk = NULL;
		mix_channel[i].playing = 0;
		mix_channel[i].looping = 0;
		mix_channel[i].volume = SDL_MIX_MAXVOLUME;
		mix_channel[i].fade_volume = SDL_MIX_MAXVOLUME;
		mix_channel[i].fade_volume_reset = SDL_MIX_MAXVOLUME;
		mix_channel[i].fading = MIX_NO_FADING;
		mix_channel[i].tag = -1;
		mix_channel[i].expire = 0;
		mix_channel[i].effects = NULL;
		mix_channel[i].paused = 0;
	}
	Mix_VolumeMusic(SDL_MIX_MAXVOLUME);

	_Mix_InitEffects();

	/* This list is (currently) decided at build time. */
	add_chunk_decoder("WAVE");
	add_chunk_decoder("AIFF");
	add_chunk_decoder("VOC");
#ifdef OGG_MUSIC
	add_chunk_decoder("OGG");
#endif
#ifdef FLAC_MUSIC
	add_chunk_decoder("FLAC");
#endif

	audio_opened = 1;
	SDL_PauseAudio(0);
	return(0);
}
示例#24
0
SoundPlayer::~SoundPlayer()
{
	stop();
	Mix_CloseAudio();
}
示例#25
0
void clean_up()
{
    //free all surfaces
    SDL_FreeSurface( background );
    SDL_FreeSurface (frisbee1);
    SDL_FreeSurface (frisbee2);
    SDL_FreeSurface (frisbee3);
    SDL_FreeSurface (frisbee4);
    SDL_FreeSurface (frisbee5);
    SDL_FreeSurface (frisbee6);
    SDL_FreeSurface (frisbee7);
    SDL_FreeSurface (frisbee8);
    SDL_FreeSurface (frisbee9);
    SDL_FreeSurface (frisbee10);
    SDL_FreeSurface (frisbee11);
    SDL_FreeSurface (frisbee12);
    SDL_FreeSurface (frisbee13);
    SDL_FreeSurface (frisbee14);
    SDL_FreeSurface (frisbee15);
    SDL_FreeSurface (frisbee16);
    SDL_FreeSurface (frisbee17);
    SDL_FreeSurface (frisbee18);
    SDL_FreeSurface (frisbee19);
    SDL_FreeSurface (frisbee20);
    SDL_FreeSurface (frisbee21);
    SDL_FreeSurface (frisbee22);
    SDL_FreeSurface (frisbee23);
    SDL_FreeSurface (frisbee24);
    SDL_FreeSurface (frisbee25);
    SDL_FreeSurface (frisbee26);
    SDL_FreeSurface (frisbee27);
    SDL_FreeSurface (frisbee28);
    SDL_FreeSurface (frisbee29);
    SDL_FreeSurface (frisbee30);
    SDL_FreeSurface (frisbee31);
    SDL_FreeSurface (frisbee32);
    SDL_FreeSurface (frisbee33);
    SDL_FreeSurface (frisbee34);
    SDL_FreeSurface (frisbee35);
    SDL_FreeSurface (frisbee36);
    SDL_FreeSurface (frisbee37);
    SDL_FreeSurface (frisbee38);
    SDL_FreeSurface (frisbee39);
    SDL_FreeSurface (frisbee40);
    SDL_FreeSurface (frisbee41);
    SDL_FreeSurface (frisbee42);
    SDL_FreeSurface (frisbee43);
    SDL_FreeSurface (frisbee44);
    SDL_FreeSurface (frisbee45);
    SDL_FreeSurface (arrow0);
    SDL_FreeSurface (left45);
    SDL_FreeSurface (left30);
    SDL_FreeSurface (left15);
    SDL_FreeSurface (right45);
    SDL_FreeSurface (right30);
    SDL_FreeSurface (right15);
    SDL_FreeSurface (angle0);
    SDL_FreeSurface (angle3);
    SDL_FreeSurface (angle6);
    SDL_FreeSurface (angle9);
    SDL_FreeSurface (angle12);
    SDL_FreeSurface (angle15);
    SDL_FreeSurface (message);
    SDL_FreeSurface (p0);
    SDL_FreeSurface (p1);
    SDL_FreeSurface (p2);
    SDL_FreeSurface (p3);
    SDL_FreeSurface (p4);
    SDL_FreeSurface (p5);
    SDL_FreeSurface (p6);
    SDL_FreeSurface (p7);
    SDL_FreeSurface (p8);
    SDL_FreeSurface (p9);
    SDL_FreeSurface (p10);
    SDL_FreeSurface (p11);
    SDL_FreeSurface (p12);
    SDL_FreeSurface (p13);
    SDL_FreeSurface (p14);
    SDL_FreeSurface (p15);
    SDL_FreeSurface (horzText);
    SDL_FreeSurface (vertText);
    SDL_FreeSurface (scoreText);
    SDL_FreeSurface (scoreHoleText);
    SDL_FreeSurface (hitText);
    
    // free music
    Mix_FreeMusic(music);
    
    //close fonts
    TTF_CloseFont(font);
    TTF_CloseFont(font2);

    //Quit Mixer
    Mix_CloseAudio();
    
    TTF_Quit();
    
    std::cout<<"Quitting SDL..."<<std::endl;
    
    //quit sdl
    SDL_Quit();
    
}
示例#26
0
文件: main.c 项目: Sehsyha/ProjetC
int main(void)
{
//    int good = 0;
//    int numeroMap = 0;
//    do{
//        printf("Quelle map?\n");
//        printf("1 - Original\n");
//        printf("2 - Hard\n");
//        printf("3 - Lol\n");
//        printf("4 - Rez De chaussez Aile Sud Telecom Nancy\n");
//        scanf("%d", &numeroMap);
//        switch(numeroMap){
//            case 1:
//                loadMap("../projec/map/original.map");
//                good = 1;
//                break;
//            case 2:
//                loadMap("../projec/map/hard.map");
//                good = 1;
//                break;

//            case 3:
//                loadMap("../projec/map/maplol.map");
//                good = 1;
//                break;
//            case 4:
//                loadMap("../projec/map/rdastn.map");
//                good = 1;
//                break;

//            case 42:
//                loadMap("../projec/map/rdastn.map");
//                good = 1;
//                setQ();
//                break;
//        }
//    }while(!good);
    //Create SDL objects
    SDL_Window *window = 0;
    SDL_Event event;
    SDL_Renderer *renderer = 0;
    int terminate = 0;

    //Initialise SDL
    if(SDL_Init(SDL_INIT_VIDEO) < 0){
        printf("Error with SDL : %s\n", SDL_GetError());
        SDL_Quit();
        return EXIT_FAILURE;
    }

    window = SDL_CreateWindow("Pacman", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 544, 344, SDL_WINDOW_SHOWN);
    terminate = 0;
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    SDL_Surface *menu = IMG_Load("../projec/texture/menu/menu.jpg");

    SDL_Texture *menuTexture = SDL_CreateTextureFromSurface(renderer, menu);

    SDL_FreeSurface(menu);
    SDL_RenderClear(renderer);
    int x, y;
    while(!terminate){
        SDL_Rect dest = {0, 0, 544, 344};
        SDL_RenderCopy(renderer, menuTexture, NULL, &dest);
        SDL_RenderPresent(renderer);
        SDL_WaitEvent(&event);
        switch(event.type){
            case SDL_MOUSEBUTTONDOWN:
                x = event.motion.x;
                y = event.motion.y;
                if(x >= 57 && x <= (57+54) && y >=  94 && y <= (94 + 74)){
                    loadMap("../projec/map/original.map");
                    terminate = 1;
                }
                if(x >= 124 && x <= (124+53) && y >=  208 && y <= (208 + 73)){
                    loadMap("../projec/map/hard.map");
                    terminate = 1;
                }
                if(x >= 221 && x <= (221+59) && y >=  95 && y <= (95 + 80)){
                    loadMap("../projec/map/maplol.map");
                    terminate = 1;
                }
                if(x >= 311 && x <= (311+63) && y >=  208 && y <= (208 + 76)){
                    loadMap("../projec/map/rdastn.map");
                    terminate = 1;
                }
                if(x >= 350 && x <= (350+124) && y >=  73 && y <= (73 + 109)){
                    loadMap("../projec/map/rdastn.map");
                    terminate = 1;
                    setQ();
                }
                break;
        }

        SDL_Delay(1000 / FPS);
    }
    SDL_DestroyTexture(menuTexture);

    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);

    //Search the pacman on the map and create him
    Pacman *pacman = getPacmanInstance();
    unsigned int initialX = pacman->x;
    unsigned int initialY = pacman->y;
    Map *map = getMapInstance();
    //If the pacman is not found
    if(!pacman){
        printf("Pacman not found on map\n");
        freeMap(map);
        exit(EXIT_FAILURE);
    }
    printf("Pacman found !\n");

    Ghost *clyde = searchAndCreateGhost(CLYDE);
    if(!clyde){
        printf("Clyde not found on map\n");
        freeMap(map);
        exit(EXIT_FAILURE);
    }
    printf("Clyde found !\n");

    Ghost *blinky = searchAndCreateGhost(BLINKY);
    if(!blinky){
        printf("Blinky not found on map\n");
        freeMap(map);
        freeGhost(clyde);
        exit(EXIT_FAILURE);
    }
    printf("Blinky found !\n");

    Ghost *inky = searchAndCreateGhost(INKY);
    if(!inky){
        printf("Inky not found on map\n");
        freeMap(map);
        freeGhost(clyde);
        freeGhost(blinky);
        exit(EXIT_FAILURE);
    }
    printf("Inky found !\n");

    Ghost *pinky = searchAndCreateGhost(PINKY);
    if(!pinky){
        printf("Pinky not found on map\n");
        freeMap(map);
        freeGhost(clyde);
        freeGhost(blinky);
        freeGhost(inky);
        exit(EXIT_FAILURE);
    }
    printf("Pinky found !\n");
    printf("SDL initialisation\n");



    if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4096) == -1){
        printf("%s", Mix_GetError());
    }

    Mix_Music *music = NULL;
    music = Mix_LoadMUS("../projec/pacman.wav");
    if(!music){
        printf("Erreur de chargement de la musique %s \n", Mix_GetError());
    }else{
        Mix_VolumeMusic(MIX_MAX_VOLUME);
        Mix_PlayMusic(music, -1);
    }

    if(TTF_Init() == -1){
        printf("Error during TTF initialization : %s\n", TTF_GetError());
    }

    TTF_Font *police = NULL;

    police = TTF_OpenFont("../projec/monof.ttf", 65);
    if(!police){
        printf("Error during font load : %s\n", TTF_GetError());
    }
    SDL_Color color = { 255, 255, 255, 255};



    //Create the window
    window = SDL_CreateWindow("Pacman", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, TILE_SIZE * map->col, TILE_SIZE * map->row + TILE_SIZE, SDL_WINDOW_SHOWN);

    //If there is an error
    if(window == 0){
        printf("Error during window creation : %s \n", SDL_GetError());
        SDL_Quit();
        freeMap(map);
        return EXIT_FAILURE;
    }
    int j;
    printf("SDL init success\n");
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

    //NEED gerer erreurs

    loadTextures(renderer);

    SDL_Surface *score = TTF_RenderText_Solid(police, "Score : ", color);
    SDL_Texture *scoreT = SDL_CreateTextureFromSurface(renderer, score);
    SDL_FreeSurface(score);
    char scoreString[15];

    SDL_Rect dest = {0, map->row * TILE_SIZE , map->row * TILE_SIZE / 6, 20};
    SDL_RenderCopy(renderer, scoreT, NULL, &dest);
    SDL_Surface *scoreN;
    SDL_Texture *scoreTN;
    int open = 0;
    int konami[10] = {0,0,0,0,0,0,0,0,0,0};
    //Infinite loop until we want to stop the game
    terminate = 0;
    while(!terminate){
        SDL_Rect dest2 = {map->row * TILE_SIZE / 6, map->row * TILE_SIZE, map->row * TILE_SIZE / 15, 20};
        sprintf(scoreString, "%d", pacman->point);
        scoreN = TTF_RenderText_Solid(police, scoreString, color);
        scoreTN = SDL_CreateTextureFromSurface(renderer, score);
        renderMap(renderer);
        open = renderPacman(open, renderer);
        renderClyde(clyde, renderer);
        renderBlinky(blinky, renderer);
        renderPinky(pinky, renderer);
        renderInky(inky, renderer);

        changeDirectionGhost(blinky);
        changeDirectionGhost(clyde);
        changeDirectionGhost(inky);
        changeDirectionGhost(pinky);
        SDL_Rect dest = {0, map->row * TILE_SIZE , map->row * TILE_SIZE / 6, 20};
        SDL_RenderCopy(renderer, scoreT, NULL, &dest);



        SDL_RenderCopy(renderer, scoreTN, NULL, &dest2);

        SDL_RenderPresent(renderer);
        //Event handling

        SDL_PollEvent(&event);
        switch(event.type){
            case SDL_KEYDOWN:
                switch(event.key.keysym.scancode){
                    case SDL_SCANCODE_UP:
                        setPacmanDirection(NORTH);
                        if(konami[0]){
                            if(konami[1]){
                                for(j = 0 ; j < 10 ; j++){
                                    konami[j] = 0;
                                }
//                                printf("Déjà deux\n");
                            }else{
                                konami[1] = 1;
                            }
                        }else{
                            konami[0] = 1;
                        }
                        break;
                    case SDL_SCANCODE_DOWN:
                        setPacmanDirection(SOUTH);
                        break;
                    case SDL_SCANCODE_RIGHT:
                        setPacmanDirection(EAST);
                        break;
                    case SDL_SCANCODE_LEFT:
                        setPacmanDirection(WEST);
                        break;
                    default:
                        break;
                }
                break;
        }
        terminate = update(clyde, blinky, inky, pinky);
        if(terminate){
            if(pacman->life > 0 ){
                pacman->life--;
                terminate = 0;
                pacman->x = initialX;
                pacman->y = initialY;
            }
        }
        if(event.window.event == SDL_WINDOWEVENT_CLOSE){
            terminate = 1;
        }
        SDL_Delay(1000 / FPS);
        SDL_DestroyTexture(scoreTN);
        SDL_FreeSurface(scoreN);
    }
    printf("Score final : %d\n", pacman->point);
    Mix_FreeMusic(music);
    Mix_CloseAudio();
    freeTextures();
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
    SDL_DestroyTexture(scoreT);
    freePacman();
    freeGhost(clyde);
    freeGhost(blinky);
    freeGhost(inky);
    freeGhost(pinky);
    freeMap();
    TTF_CloseFont(police);
    TTF_Quit();
    return EXIT_SUCCESS;
}
示例#27
0
int main(int argc, char* argv[]){
  foutp=fopen("data.out", "w");
  close(foutp);
  //smpls = gen_triangle_buffer();
  //  smpls = gen_sawtooth_buffer();
  smpls = snd_load("/media/c5bcf67f-e9eb-4e12-be75-d8b6e09e27ba/olivier/hti/ginf/cpu-emu/cpu-emu/sin.table");
  

  /* //sound_buffer = malloc(sizeof(SNDFMT)*512); */
  /* 	//	mem[0] = malloc(sizeof(SNDFMT)*mem0size); */
  /* 	//	mem[1] = malloc(sizeof(SNDFMT)*mem1size); */
  
  /* // init without mixer        init_sdl ();  */

  /* // start SDL with audio support */
  
  if (SDL_Init (SDL_INIT_VIDEO|SDL_INIT_AUDIO) < 0)
    exit (-1);

  atexit (SDL_Quit);
  screen = SDL_SetVideoMode (640, 480, 16, SDL_HWSURFACE);

  if (screen == NULL)
    exit (-1);

  // open SMPFREQ, signed 8bit, system byte order,
  //      stereo audio, using 1024 byte chunks
  if(Mix_OpenAudio(SMPFREQ, AUDIO_S8, 1, WAVEFORM_LENGTH)==-1) {
    printf("Mix_OpenAudio: %s\n", Mix_GetError());
    exit(2);
  }

  Mix_Chunk *sound = NULL; 
  
  sound = Mix_QuickLoad_RAW(smpls,WAVEFORM_LENGTH);

  if(sound == NULL) {
    fprintf(stderr, "Unable to load WAV file: %s\n", Mix_GetError());
  }
  
   int channel;
  
  channel = Mix_PlayChannel(-1, sound, -1);
  if(channel == -1) {
    fprintf(stderr, "Unable to play WAV file: %s\n", Mix_GetError());
  }
  //while(Mix_Playing(channel) != 0);

  int len = WAVEFORM_LENGTH;
  smpls = gen_sin_buffer();
  save("sin.out",smpls,len);
  smpls = gen_triangle_buffer();
  save("triangle.out",smpls,len);
  smpls = gen_sawtooth_buffer();
  save("sawtooth.out",smpls,len);
  smpls = gen_square_buffer();
  save("square.out",smpls,len);
  smpls = gen_pwm_buffer(0.2);
  save("pwm.out",smpls,len);
  
  
 // violine
  int attack = 500;
  int decay = 300;
  int sustain = 10;
  int sustainlength0 = (attack / 1000.0) * SMPFREQ;
  int sustain_max = 15; // 4 Bit 0-15
  float sustain0 = (float) sustain * ((float)1.0)/(float)sustain_max;
  float sustain_level = sustain0;
  int release = 750; 
  int release0 = (release / 1000.0) * SMPFREQ;
  int attack0 = (attack / 1000.0) * SMPFREQ;
  int decay0  = (decay  / 1000.0) * SMPFREQ;
  int t1 = attack0;
  int t2 = t1 + decay0;
  int t3 = t2 + sustainlength0;
  int t4 = t3 + release0;

 instrument[0].a_attack = ((float)1.0/(float)attack0);
  instrument[0].a_decay  =  ((float) ( 1.0 - sustain0)) / (float) ( t1-t2) ;
  instrument[0].b_decay = (float)1.0 - ((float)instrument[0].a_decay*(float)attack0);
  instrument[0].a_release = sustain_level / (float) (t3-t4) ;
  instrument[0].b_release = sustain_level - (float)instrument[0].a_release * (float)t3;
  instrument[0].adsr_counter = 0;
  instrument[0].gate=0;
  adsr_length = gen_adsr_buffer(&adsr_buffer);

  saveadsr("data.out",adsr_buffer,adsr_length);
  savebuffer = malloc(sizeof(float)*adsr_length);
  //  register adsrEffect as a mix processor

  if(!Mix_RegisterEffect(channel, adsrEffect, NULL, &(instrument[0]) )) {
    printf("Mix_RegisterEffect: %s\n", Mix_GetError());
  }
	

  /* Mix_VolumeChunk(sound, volume); */
  /* printf("volume: %d\n", volume); */


  /* 	Hz=440; */

  /* 	//	main_synthesiser(1, NULL); */
  /* 	printf("start play\n"); */

  /* 	//        play (); */

  /* 	//	SDL_MixAudio(stream, waveptr, len, SDL_MIX_MAXVOLUME);  */

	int i=0;
	SDL_Event event;
	int done=0;
	int hzinc=0,amplitudeinc;
	


	/*

	float* adsrptr;
	int len;
	saveadsr("data.out",adsrptr,len);
	if(smp_index < WAVEFORM_LENGTH){
	  for(i = 0; i < len; i++){
            adsrptr[i] = adsrptr[i] * smpls[(int)smp_index];
	    //            smp_index +=freq;
	    smp_index++;
            if(smp_index >= WAVEFORM_LENGTH)
                smp_index = 0;
	  }
	}
	Mix_CloseAudio();
	SDL_Quit();
        return 0; 
	*/

	while(!done) {
	  while(SDL_PollEvent(&event)) {
	    
 switch(event.type) {
	    case SDL_KEYDOWN:	
      switch(event.key.keysym.sym){
	      case SDLK_LEFT:
		volume-=10;
		Mix_VolumeChunk(sound, volume);
		//		Mix_VolumeChunk(sound, (volume>MIX_MAX_VOLUME-10) ?  (volume = MIX_MAX_VOLUME):(volume-=10) );
		printf("SDLK_LEFT volume: %i\n",volume);
		amplitudeinc = -1;
		break;
	      case SDLK_RIGHT:
		volume+=10;
		Mix_VolumeChunk(sound, volume );
		//		Mix_VolumeChunk(sound, (volume<10) ?  (volume = 0): (volume+=10) );
		printf("SDLK_RIGHT volume: %i\n",volume);
		amplitudeinc = +1;;
		break;
	      case SDLK_UP:
		hzinc = 1;
		printf("up active\n");
		break;
	      case SDLK_DOWN:
		hzinc = -1;
		printf("down active\n");
		break;
	      default:
		handleKey(event.key);
		break;
	      }
	      break;
	    case SDL_KEYUP:
	      switch(event.key.keysym.sym){
	      case SDLK_LEFT:
		amplitudeinc = 0;
		break;
	      case SDLK_RIGHT:
		amplitudeinc = 0;
		break;
	      case SDLK_UP:
		tonstufe++;
		hzinc = 0;
		printf("up in-active\n");
		break;
	      case SDLK_DOWN:
		tonstufe--;
		hzinc = 0;
		printf("down in-active\n");
		break;
	      default:
		handleKey(event.key);
		break;
	      }
	      break;
	    case SDL_QUIT:
	      done = 1;
	      printf("SDL_QUIT\n");
	      break;
	    case SDL_MOUSEBUTTONUP:
	      switch(event.button.button){
		case SDL_BUTTON_WHEELUP:
		  Hz += 1;
		  break;
		case SDL_BUTTON_WHEELDOWN:
		  Hz -= 1;
		  break;
		}
	      break;
	    default:
	      /* do nothing */
	      break;
	    }
	  }
	  
	  freq += hzinc;

	  //Hz= 2*Hz;
	  Hz = Hz + hzinc;
	  amplitude = amplitude + amplitudeinc;
	  //	  printf("Hz: %f\n",Hz);
	  //% Hz = frequency(music[i++%10]);
	  int y;
	  //	  SDL_Flip(screen);
	  SDL_Delay (50);
	}
	//	save("sndout6.snd");
	saveadsr("adsr.out",savebuffer,adsr_length);

	
	Mix_FreeChunk(sound);
	
	Mix_CloseAudio();
	SDL_Quit();
        return 0; 
	

	
} 
示例#28
0
 AudioSimpleSDL::~AudioSimpleSDL()
 {
   Mix_CloseAudio();
 }
示例#29
0
文件: audio.cpp 项目: AsGreyWolf/Q
void Audio::Quit()
{
    Mix_CloseAudio();
    return;
}
void soundLib::close_audio() {
	Mix_FreeMusic(music);
	Mix_CloseAudio();
}