void SDLSound::nextSong()
{
    static Mix_Music *music = 0;
    if (music != 0) {
        Mix_HaltMusic();
        Mix_FreeMusic(music);
        music = 0;
    }

    if(currentsong == musicfiles.end()) {
        // create a new random playlist
        std::random_shuffle(musicfiles.begin(), musicfiles.end());
        currentsong = musicfiles.begin();
    }

    musics_t::iterator lastsong = currentsong;
    do {
        const char* toplay = currentsong->c_str();
        currentsong++;
//#ifdef HAS_LOADMUS_RW
        /*
         * use LoadMUS_RW from newer SDL_mixers
         */
        try {
            SDL_RWops * ops = getFileForSDL(toplay);
            if ( ! ops ) break; // XXX ???
            music = Mix_LoadMUS_RW(ops);
            if (music) {
                if (Mix_PlayMusic(music, 1) == 0) {
                    LOG (("Start playing song '%s'", toplay));
                    break; // break while cycle
                } else {
                    LOG (("Failed to play song '%s': %s",
                          toplay, Mix_GetError()));
                }
            } else {
                LOG (("Failed to load mus_rw '%s': %s",
                      toplay, Mix_GetError()));
            }
        } catch (Exception &e) {
            LOG (("Failed to load song '%s': %s",
                  toplay, e.what()));
        }
#if 0
        music = Mix_LoadMUS(filesystem::getRealName(toplay).c_str());
        if (music) {
            if (Mix_PlayMusic(music, 1) == 0) {
                LOG (("Start playing song '%s'", toplay));
                break; // break while cycle
            } else {
                LOG (("Failed to play song '%s': %s",
                      toplay, Mix_GetError()));
            }
        } else {
            LOG (("Failed to load song '%s': %s",
                  toplay, Mix_GetError()));
        }
#endif

        if(currentsong == musicfiles.end()) {
            currentsong = musicfiles.begin();
        }
    } while(currentsong != lastsong);
}
Exemple #2
0
void Audio::init(char *file)
{
    Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4096);
    this->audio = Mix_LoadMUS(file);
}
Exemple #3
0
bool load_files( std::string backgroundFile, std::string musicFile )
{
    std::cout<<"Loading files..."<<std::endl;
    
    //Background
    background = load_image( backgroundFile );
    
    //Frisbee images
    frisbee1 = load_image("../../pictures/discs/white/ultimate_disc_white_1.png" );
    frisbee2 = load_image("../../pictures/discs/white/ultimate_disc_white_2.png" );
    frisbee3 = load_image("../../pictures/discs/white/ultimate_disc_white_3.png" );
    frisbee4 = load_image("../../pictures/discs/white/ultimate_disc_white_4.png" );
    frisbee5 = load_image("../../pictures/discs/white/ultimate_disc_white_5.png" );
    frisbee6 = load_image("../../pictures/discs/white/ultimate_disc_white_6.png" );
    frisbee7 = load_image("../../pictures/discs/white/ultimate_disc_white_7.png" );
    frisbee8 = load_image("../../pictures/discs/white/ultimate_disc_white_8.png" );
    frisbee9 = load_image("../../pictures/discs/white/ultimate_disc_white_9.png" );
    frisbee10 = load_image("../../pictures/discs/white/ultimate_disc_white_10.png" );
    frisbee11 = load_image("../../pictures/discs/white/ultimate_disc_white_11.png" );
    frisbee12 = load_image("../../pictures/discs/white/ultimate_disc_white_12.png" );
    frisbee13 = load_image("../../pictures/discs/white/ultimate_disc_white_13.png" );
    frisbee14 = load_image("../../pictures/discs/white/ultimate_disc_white_14.png" );
    frisbee15 = load_image("../../pictures/discs/white/ultimate_disc_white_15.png" );
    frisbee16 = load_image("../../pictures/discs/white/ultimate_disc_white_16.png" );
    frisbee17 = load_image("../../pictures/discs/white/ultimate_disc_white_17.png" );
    frisbee18 = load_image("../../pictures/discs/white/ultimate_disc_white_18.png" );
    frisbee19 = load_image("../../pictures/discs/white/ultimate_disc_white_19.png" );
    frisbee20 = load_image("../../pictures/discs/white/ultimate_disc_white_20.png" );
    frisbee21 = load_image("../../pictures/discs/white/ultimate_disc_white_21.png" );
    frisbee22 = load_image("../../pictures/discs/white/ultimate_disc_white_22.png" );
    frisbee23 = load_image("../../pictures/discs/white/ultimate_disc_white_23.png" );
    frisbee24 = load_image("../../pictures/discs/white/ultimate_disc_white_24.png" );
    frisbee25 = load_image("../../pictures/discs/white/ultimate_disc_white_25.png" );
    frisbee26 = load_image("../../pictures/discs/white/ultimate_disc_white_26.png" );
    frisbee27 = load_image("../../pictures/discs/white/ultimate_disc_white_27.png" );
    frisbee28 = load_image("../../pictures/discs/white/ultimate_disc_white_28.png" );
    frisbee29 = load_image("../../pictures/discs/white/ultimate_disc_white_29.png" );
    frisbee30 = load_image("../../pictures/discs/white/ultimate_disc_white_30.png" );
    frisbee31 = load_image("../../pictures/discs/white/ultimate_disc_white_31.png" );
    frisbee32 = load_image("../../pictures/discs/white/ultimate_disc_white_32.png" );
    frisbee33 = load_image("../../pictures/discs/white/ultimate_disc_white_33.png" );
    frisbee34 = load_image("../../pictures/discs/white/ultimate_disc_white_34.png" );
    frisbee35 = load_image("../../pictures/discs/white/ultimate_disc_white_35.png" );
    frisbee36 = load_image("../../pictures/discs/white/ultimate_disc_white_36.png" );
    frisbee37 = load_image("../../pictures/discs/white/ultimate_disc_white_37.png" );
    frisbee38 = load_image("../../pictures/discs/white/ultimate_disc_white_38.png" );
    frisbee39 = load_image("../../pictures/discs/white/ultimate_disc_white_39.png" );
    frisbee40 = load_image("../../pictures/discs/white/ultimate_disc_white_40.png" );
    frisbee41 = load_image("../../pictures/discs/white/ultimate_disc_white_41.png" );
    frisbee42 = load_image("../../pictures/discs/white/ultimate_disc_white_42.png" );
    frisbee43 = load_image("../../pictures/discs/white/ultimate_disc_white_43.png" );
    frisbee44 = load_image("../../pictures/discs/white/ultimate_disc_white_44.png" );
    frisbee45 = load_image("../../pictures/discs/white/ultimate_disc_white_45.png" );
    
    //Powerbar images
    p0 = load_image("../../pictures/powerbars/0.bmp");
    p1 = load_image("../../pictures/powerbars/1.bmp");
    p2 = load_image("../../pictures/powerbars/2.bmp");
    p3 = load_image("../../pictures/powerbars/3.bmp");
    p4 = load_image("../../pictures/powerbars/4.bmp");
    p5 = load_image("../../pictures/powerbars/5.bmp");
    p6 = load_image("../../pictures/powerbars/6.bmp");
    p7 = load_image("../../pictures/powerbars/7.bmp");
    p8 = load_image("../../pictures/powerbars/8.bmp");
    p9 = load_image("../../pictures/powerbars/9.bmp");
    p10 = load_image("../../pictures/powerbars/10.bmp");
    p11 = load_image("../../pictures/powerbars/11.bmp");
    p12 = load_image("../../pictures/powerbars/12.bmp");
    p13 = load_image("../../pictures/powerbars/13.bmp");
    p14 = load_image("../../pictures/powerbars/14.bmp");
    p15 = load_image("../../pictures/powerbars/15.bmp");
    
    //arrow images
    arrow0 = load_image("../../pictures/arrows/0.png");
    left15 = load_image("../../pictures/arrows/15_left.png");
    left30 = load_image("../../pictures/arrows/30_left.png");
    left45 = load_image("../../pictures/arrows/45_left.png");
    right15 = load_image("../../pictures/arrows/15_right.png");
    right30 = load_image("../../pictures/arrows/30_right.png");
    right45 = load_image("../../pictures/arrows/45_right.png");
    
    //angle images
    angle0 = load_image("../../pictures/angle_arrows/Angle_arrow0.bmp");
    angle3 = load_image("../../pictures/angle_arrows/Angle_arrow3.bmp");
    angle6 = load_image("../../pictures/angle_arrows/Angle_arrow6.bmp");
    angle9 = load_image("../../pictures/angle_arrows/Angle_arrow9.bmp");
    angle12 = load_image("../../pictures/angle_arrows/Angle_arrow12.bmp");
    angle15 = load_image("../../pictures/angle_arrows/Angle_arrow15.bmp");
    
    //Open the font
    font = TTF_OpenFont( "../../fonts/BEBAS.ttf", 24 );
    font2 = TTF_OpenFont( "../../fonts/BEBAS.ttf", 80 );
    
    if( background ==NULL || frisbee45 == NULL || font==NULL  )
    {
      std::cout<<"Files did not load correctly"<<std::endl;
      return false;
    }
    
    //Load music
    music = Mix_LoadMUS ( musicFile.c_str());

    //Possible problem loading music
    if(music == NULL)
    {
	std::cout<<"Music did not load correctly"<<std::endl;
	return false;
    }

    std::cout<<"Files loaded correctly"<<std::endl;
    return true;
}
Exemple #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);
}
Exemple #5
0
int main(int argc, char *argv[])
{
	SDL_Init(SDL_INIT_VIDEO);
	displayWindow = SDL_CreateWindow("Final Project", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_OPENGL);
	SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
	SDL_GL_MakeCurrent(displayWindow, context);
#ifdef _WINDOWS
	glewInit();
#endif

	ShaderProgram* program = new ShaderProgram(RESOURCE_FOLDER"vertex_textured.glsl", RESOURCE_FOLDER"fragment_textured.glsl");

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	glViewport(0, 0, 640, 480);

	Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4096);

	Matrix modelMatrix;
	Matrix textMatrix;
	Matrix viewMatrix;
	Matrix projectionMatrix;
	projectionMatrix.setOrthoProjection(-10.0f, 10.0f, -7.5f, 7.5f, -1.0f, 1.0f);
	
	std::vector<Entity> entities;

	int lastWinner;

	// Load player sprites
	GLint paddleBlue = LoadTextureClamp(RESOURCE_FOLDER"assets\\paddleBlu.png");
	GLint paddleRed = LoadTextureClamp(RESOURCE_FOLDER"assets\\paddleRed.png");
	// Load item sprites
	GLint coinCopperSprite = LoadTextureClamp(RESOURCE_FOLDER"assets\\coinCopper.png");
	GLint coinSilverSprite = LoadTextureClamp(RESOURCE_FOLDER"assets\\coinSilver.png");
	GLint coinGoldSprite = LoadTextureClamp(RESOURCE_FOLDER"assets\\coinGold.png");
	GLint coinPlatinumSprite = LoadTextureClamp(RESOURCE_FOLDER"assets\\coinPlatinum.png");
	GLint starCopperSprite = LoadTextureClamp(RESOURCE_FOLDER"assets\\starCopper.png");
	GLint starSilverSprite = LoadTextureClamp(RESOURCE_FOLDER"assets\\starSilver.png");
	GLint starGoldSprite = LoadTextureClamp(RESOURCE_FOLDER"assets\\starGold.png");
	GLint starPlatinumSprite = LoadTextureClamp(RESOURCE_FOLDER"assets\\starPlatinum.png");
	// Load font
	GLuint fontSheet = LoadTextureClamp(RESOURCE_FOLDER"assets\\font1.png");
	// Load level bg
	GLint mainBG = LoadTextureRepeat(RESOURCE_FOLDER"assets\\bg_main.png");
	GLint levelBG = LoadTextureRepeat(RESOURCE_FOLDER"assets\\bg_level.png");
	GLint overBG = LoadTextureRepeat(RESOURCE_FOLDER"assets\\bg_over.png");

	// Load music
	Mix_Music *music1;
	music1 = Mix_LoadMUS(RESOURCE_FOLDER"assets\\Im Free.mp3");
	Mix_Music *music2;
	music2 = Mix_LoadMUS(RESOURCE_FOLDER"assets\\Lagrima.mp3");
	Mix_Music *music3;
	music3 = Mix_LoadMUS(RESOURCE_FOLDER"assets\\The Old Song.mp3");
	Mix_Music *music4;
	music4 = Mix_LoadMUS(RESOURCE_FOLDER"assets\\FASE.mp3");
	// Load sounds
	Mix_Chunk* itemHit;
	itemHit = Mix_LoadWAV(RESOURCE_FOLDER"hit.wav");
	Mix_Chunk* buttonPress;
	buttonPress = Mix_LoadWAV(RESOURCE_FOLDER"Menu Selection Click.wav");


	// Initialize players
	Entity playerBlue(ENTITY_PLAYER, paddleBlue, fontSheet, SDL_SCANCODE_A, SDL_SCANCODE_D, -5.0f);
	Entity playerRed(ENTITY_PLAYER, paddleRed, fontSheet, SDL_SCANCODE_LEFT, SDL_SCANCODE_RIGHT, 5.0f);

	Entity coinCopper(ENTITY_ITEM, coinCopperSprite, fontSheet, 10, buttonPress);
	Entity coinSilver(ENTITY_ITEM, coinSilverSprite, fontSheet, 25, buttonPress);
	Entity coinGold(ENTITY_ITEM, coinGoldSprite, fontSheet, 50, buttonPress);
	Entity coinPlatinum(ENTITY_ITEM, coinPlatinumSprite, fontSheet, 100, buttonPress);
	Entity starCopper(ENTITY_ITEM, starCopperSprite, fontSheet, 100, buttonPress);
	Entity starSilver(ENTITY_ITEM, starSilverSprite, fontSheet, 250, buttonPress);
	Entity starGold(ENTITY_ITEM, starGoldSprite, fontSheet, 500, buttonPress);
	Entity starPlatinum(ENTITY_ITEM, starPlatinumSprite, fontSheet, 1000, buttonPress);

	entities.push_back(playerBlue);
	entities.push_back(playerRed);
	entities.push_back(coinCopper);
	entities.push_back(coinSilver);
	entities.push_back(coinGold);
	entities.push_back(coinPlatinum);
	entities.push_back(starCopper);
	entities.push_back(starSilver);
	entities.push_back(starGold);
	entities.push_back(starPlatinum);

	Level level1(LEVEL_FREEPLAY, fontSheet, levelBG, music3, entities);
	Level level2(LEVEL_CLOCKED, fontSheet, levelBG, music4, entities);
	Level level3(LEVEL_SCORED, fontSheet, levelBG, music1, entities);

	Mix_PlayMusic(music3, -1);

	SDL_Event event;
	bool done = false;
	while (!done) {
		while (SDL_PollEvent(&event)) {
			if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) {
				done = true;
			}
		}
		glClear(GL_COLOR_BUFFER_BIT);

		program->setModelMatrix(modelMatrix);
		program->setViewMatrix(viewMatrix);
		program->setProjectionMatrix(projectionMatrix);
		glUseProgram(program->programID);

		switch (state)
		{
		case MAIN_MENU:
			RenderBG(program, mainBG);
			if (keys[SDL_SCANCODE_1]) { // Press 1 to get into game level
				state = GAME_LEVEL_1;
				Mix_PlayChannel(-1, buttonPress, 0);
				Mix_PlayMusic(level1.getBgm(), -1);
			}
			if (keys[SDL_SCANCODE_2]) { // Press 2 to get into game level
				state = GAME_LEVEL_2;
				Mix_PlayChannel(-1, buttonPress, 0);
				Mix_PlayMusic(level2.getBgm(), -1);
			}
			if (keys[SDL_SCANCODE_3]) { // Press 3 to get into game level
				state = GAME_LEVEL_3;
				Mix_PlayChannel(-1, buttonPress, 0);
				Mix_PlayMusic(level3.getBgm(), -1);
			}
			if (keys[SDL_SCANCODE_ESCAPE]){
				done = true;
			}
			break;
		case GAME_LEVEL_1:
			if (!level1.isComplete()){
				level1.Update();
				level1.FixedUpdate();
				level1.Render(program);
				level1.RenderText(program);
			}
			else {
				lastWinner = level1.getWinner();
				state = MAIN_MENU;
				level1.reset();
				Mix_PlayMusic(music3, -1);
			}
			break;
		case GAME_LEVEL_2:
			if (!level2.isComplete()){
				level2.Update();
				level2.FixedUpdate();
				level2.Render(program);
				level2.RenderText(program);
			}
			else {
				lastWinner = level2.getWinner();
				state = GAME_OVER;
				level2.reset();
				Mix_PlayMusic(music3, -1);
			}
			break;
		case GAME_LEVEL_3:
			if (!level3.isComplete()){
				level3.Update();
				level3.FixedUpdate();
				level3.Render(program);
				level3.RenderText(program);
			}
			else {
				lastWinner = level3.getWinner();
				state = GAME_OVER;
				level3.reset();
				Mix_PlayMusic(music3, -1);
			}
			break;
		case GAME_OVER:
			RenderBG(program, overBG);
			program->setModelMatrix(textMatrix);
			textMatrix.identity();
			textMatrix.Translate(-7.5f, 0.0f, 0.0f);
			if (lastWinner == 0)
				DrawText(program, fontSheet, "Blue Player wins!", 1.0f, 0.005f);
			else if (lastWinner == 1)
				DrawText(program, fontSheet, "Red Player wins!", 1.0f, 0.005f);
			if (keys[SDL_SCANCODE_RETURN]) {
				level1.reset();
				level2.reset();
				level3.reset();
				state = MAIN_MENU;
				Mix_PlayChannel(-1, buttonPress, 0);
			}
			else if (keys[SDL_SCANCODE_ESCAPE]) {
				done = true;
			}
			break;
		}

		SDL_GL_SwapWindow(displayWindow);
	}

	SDL_Quit();
	return 0;
}
Exemple #6
0
//the massive main function
int main(int argc, char* args[]) // Gets command line input
{
	bool quit = false, playing = true, falling = true, held = false, paused = false, cheating = false; // All our miscellaneous bools to keep track of game states.
	
	int level = 0, lines = 0, score = 0, choice = 0, cheatseq = 0;
	
	Scores scores("gfx"); // Opens the uber camoflaged gfx file for getting highscores. Tricksy, eh?
	
	Uint32 start = 0; // A REALLY big int for keeping track of time
	
	srand(SDL_GetTicks()); // seeding the random... seed
	
	if( init() == false ) // Initialize SDL
	{
		cout << "Init fail" << endl;
		return 1; //ERR !!!!
	}
	
	block = load_image( "blocks.png" ); // load blocks
	
	if(block == NULL) 
	{
		cout << "Error loading blocks.png" << endl;
		return 1; //ERR!
	}
	
	back = load_image( "back.png" ); // load background
	
	if(back == NULL)
	{
		cout << "Error loading back.png" << endl;
		return 1; //ERR!
	}
	
	smallblock = load_image( "smallblocks.png" ); // small blocks for next and hold
	
	if(smallblock == NULL)
	{
		cout << "Error loading smallblocks.png" << endl;
		return 1; //ERR!
	}
	
	title = load_image( "title.png" ); // title
	
	if(title == NULL)
	{
		cout << "Error loading title.png" << endl;
		return 1; //ERR!
	}
	
	cursor = load_image( "cursor.png" ); // cursor in menu
	
	if(cursor == NULL)
	{
		cout << "Error loading cursor.png" << endl;
		return 1; //ERR!
	}
	
	font = TTF_OpenFont("ProggyClean.ttf", FONTSIZE); // our font
	
	if(font == NULL)
	{
		cout << "Error loading ProggyClean.ttf" << endl;
		return 1; //Yup. Didn't load.
	}
	
	effect = Mix_LoadWAV( "pause.wav" ); // dee doo sound
	
	if(effect == NULL)
	{
		cout << "Mix_LoadWAV: " << Mix_GetError() << endl;
	}
	
	while(playing) // while the user hasn't quit
	{
		score = 0;
		quit = false;
		Mix_FadeOutMusic(100); // fades out the music (if playing) for menu.
		
		Mix_FreeMusic(music); // gets rid of any music we might have loaded
		
		if(XM == true) // load title music
		{
			music = Mix_LoadMUS("title.xm");
		}
		else
		{
			music = Mix_LoadMUS("title.mp3");
		}
		
		if(!music)
		{
	   		cout << "Mix_LoadMUS(\"title.mp3\"): %s\n" << Mix_GetError() << endl;
	   		// music didn't load...
		}
		
		Mix_PlayMusic(music, -1); // play it til the user can't stand it no mo'.

		for(int i = 600; i>=100; i--) // slowly bring up the title
		{
			while( SDL_PollEvent( &event ) ) // gets any recent events (mouse, keyboard, whatev)
			{
				if( event.type == SDL_QUIT ) // X button
				{
					i = 100;
					playing = false;
					quit = true;
				}
				else if( event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE) //escape
				{
					i = 100; // brings the title screen instantly
				}
			}
			SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 0x00, 0x00, 0x00 ) ); // fill screen black
			apply_surface( 200, i, title, screen ); // apply title
			if( SDL_Flip( screen ) == -1 ) // hand *screen to video card
			{
				return 1; //ERRRRRRR !!
			}
			SDL_Delay(2); // slows it down a wee bit.
		}
		
		apply_surface( 325, 402 + choice * 50, cursor, screen ); // display cursor
		
		numbers = TTF_RenderText_Blended(font, "START", fontColor); // start
		apply_surface( 350, 400, numbers, screen );
		
		numbers = TTF_RenderText_Blended(font, "HIGH SCORES", fontColor); // high scores
		apply_surface( 350, 450, numbers, screen );
		
		numbers = TTF_RenderText_Blended(font, "EXIT", fontColor); // exit
		apply_surface( 350, 500, numbers, screen );
		
		if( SDL_Flip( screen ) == -1 )
		{
			return 1; //ERRRRRRR !!
		}
		
		paused = true; //pause for menu
		while(paused && !quit)
		{
			while( SDL_PollEvent( &event ) ) // wait for events
			{
				if( event.type == SDL_QUIT )
				{
					paused = false;
					playing = false;
					quit = true;
				}
				else if( event.type == SDL_KEYDOWN )
				{
					switch(event.key.keysym.sym)
					{
						case SDLK_ESCAPE:
							paused = false;
							quit = true;
							playing = false;
							break;
						case SDLK_RETURN:
							switch(choice)
							{
								case 0:
									paused = false;
									break;
								case 1:
									scores.display();
									break;
								case 2:
									paused = false;
									quit = true;
									playing = false;
									break;
							}
							break;
						case SDLK_DOWN: // down, move cursor down
							Mix_PlayChannel(-1, effect, 0); // dee doo sound
							if(choice < 2)
							{
								choice++;
							}
							else
							{
								choice = 0;
							}
							break;
						case SDLK_UP: // up, move cursor up
							Mix_PlayChannel(-1, effect, 0); // see above
							if(choice > 0)
							{
								choice--;
							}
							else
							{
								choice = 2;
							}
							break;
					}
					SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 0x00, 0x00, 0x00 ) );
					
					apply_surface( 200, 100, title, screen );
					apply_surface( 325, 402 + choice * 50, cursor, screen );
							
					numbers = TTF_RenderText_Blended(font, "START", fontColor);
					apply_surface( 350, 400, numbers, screen );
					
					numbers = TTF_RenderText_Blended(font, "HIGH SCORES", fontColor);
					apply_surface( 350, 450, numbers, screen );
		
					numbers = TTF_RenderText_Blended(font, "EXIT", fontColor);
					apply_surface( 350, 500, numbers, screen );
		
					if( SDL_Flip( screen ) == -1 )
					{
						return 1; //ERRRRRRR !!
					}
				}
			}
		}
		
		if(!quit) // if the user didn't quit
		{		
			Mix_FadeOutMusic(100); //fade out title music
			
			Mix_FreeMusic(music); //free it
			
			if(XM == true) // change to game music
			{
				music = Mix_LoadMUS("music.xm");
			}
			else
			{
				music = Mix_LoadMUS("music.mp3");
			}
		
			if(!music)
			{
	   			cout << "Mix_LoadMUS(\"music.mp3\"): %s\n" << Mix_GetError() << endl;
	   			// music didn't load...
			}
			
			Mix_PlayMusic(music, -1);
		
			SDL_Delay(1500); // wait for ba-ding! to finish
		}
		
		Tile *tile = NULL, *next = NULL, *next2 = NULL, *next3 = NULL, *hold = NULL, *blank = NULL; //current tile, next tiles 1 2 3, hold, and the tile used for switching hold
		
		setclips(); // set the clip boxes for tiles
		
		clearfield(); // initialize the field

		next = new Tile(); // inits new tiles
		next2 = new Tile();
		next3 = new Tile();
		
		while(!quit)
		{
			SDL_Delay(50); // wait a bit for the next block to drop
			tile = next; // next to current
			next = next2; // move nexts
			next2 = next3;
			next3 = new Tile(); // new next 3
			if(!tile->check(0, 0)) // if the tile is colliding from the get go
			{
				tile->show();
				if( SDL_Flip( screen ) == -1 )
				{
					return 1; //ERRRRRRR !!
				}
				gameOver(); // THEN YOU LOSE! HA!
				scores.checkScore(score); // Did you get a high score?
				scores.save(); // save the high score file
				scores.display(); // display the current high scores
				quit = true;
			}
			falling = true;
			
			while(falling && !quit) // the there a lot of !quits from now on so it goes straight back to the menu
			{
				apply_surface( 0, 0, back, screen ); // background
				tile->show(); // show the current tile
				if(hold != NULL)
				{
					hold->disp(27,78); // display hold
				}
				next->disp(390, 78); // display nexts
				next2->disp(390, 158);
				next3->disp(390, 238);
				start = SDL_GetTicks(); // start the timer
				while( falling && SDL_GetTicks() - start < (1/((static_cast<double>(level)/25) + 1))*(SPEED - MINSPEED)+MINSPEED) // spiffy formula I took way to long to make for speeding up
				{
					while( SDL_PollEvent( &event ) ) // get events
					{
						if( event.type == SDL_QUIT ) // quit immediatly
						{
							clean();
							exit(0);
							playing = false;
						}
						else if( event.type == SDL_KEYDOWN ) // was a key pressed?
						{
							switch( event.key.keysym.sym ) // what key was pressed?
							{
								case SDLK_LEFT: // move left
									tile->check(-1, 0);
									break;
								case SDLK_RIGHT: // move right
									tile->check(1, 0);
									break;
								case SDLK_z: // rotate CCW
									tile->rotate(CC);
									break;
								case SDLK_x: // rotate CW
									tile->rotate(CW);
									break;
								case SDLK_DOWN: // soft drop
									if(!tile->check(0,1)) // if it hits something as a result of dropping once
									{
	                                    falling = false; // apply the tile
	                                }
	                                start = SDL_GetTicks(); // reset the timer
									break;
								case SDLK_UP: // hard drop
									while(tile->check(0,1)) // move it down til it cant any more
									{
										score += 2 * (level + 1); // you get points for being so daring!
									}
									start -= 1000; //Lock that sucka!
									break;
								case SDLK_n: // this is the cheat key. But you have to be cheating to use it ;D
									if(cheating)
									{
										delete tile; // basically just gives you new tiles
										tile = new Tile();
									}
									break;
								case SDLK_ESCAPE: // back to main menu
									quit = true;
									break;
								case SDLK_k: //SUPER SECRET KYLE-MODE!
									block = load_image( "kyles.png" );
									back = load_image( "kyleback.png" );
									smallblock = load_image("smallkyles.png");
									Mix_HaltMusic();
									music = Mix_LoadMUS("rawk.mp3");
									Mix_PlayMusic(music, -1);
									break;
								case SDLK_o: // back to original
									block = load_image( "blocks.png" );
									back = load_image( "back.png" );
									smallblock = load_image("smallblocks.png");
									Mix_HaltMusic();
									music = Mix_LoadMUS("music.mp3");
									Mix_PlayMusic(music, -1);
									break;
								case SDLK_c: // hold
									if(hold && !held) // if there is something held and you haven't held yet this turn
									{
										blank = hold; // switch current and held
										hold = tile;
										tile = blank;
									}
									else if(!hold) // if you've never held
									{
										hold = tile; // hold current and make more tiles
										tile = next;
										next = next2;
										next2 = next3;
										next3 = new Tile();
									}
									hold->reset(); // reset the x and y values of the tile
									held = true;
									break;
								case SDLK_p: // pause
									paused = true;
									Mix_PauseMusic(); // pause music
									Mix_PlayChannel(-1, effect, 0); // play the dee doo
									apply_surface( 0, 0, back, screen ); // cover the tiles
									numbers = TTF_RenderText_Solid(font, intToStr(score).c_str(), fontColor); // but keep the scores
									apply_surface( 550, 50, numbers, screen );
									numbers = TTF_RenderText_Solid(font, intToStr(level).c_str(), fontColor);
									apply_surface( 550, 120, numbers, screen );
									if( SDL_Flip( screen ) == -1 ) // display screen
									{
										return 1; //ERRRRRRR !!
									}
									while(paused)
									{
										while(SDL_PollEvent( &event )) // get events
										{
											if( event.type == SDL_QUIT ) // quit immediatly
											{
												quit = true;
												paused = false;
												playing = false;
											}
											else if( event.type == SDL_KEYDOWN ) // key down?
											{
												switch( event.key.keysym.sym ) // what key?
												{
													case SDLK_ESCAPE: // unpause
													case SDLK_p: // unpause
														paused = false;
														break;
													case SDLK_UP: // CHEATING!! WOO!!! UP UP DOWN DOWN LEFT RIGHT LEFT RIGHT A B. <3 CONTRA.
														if(cheatseq == 0 || cheatseq == 1)
														{
															cheatseq++;
														}
														else
														{
															cheatseq = 0; // if you screwed up
														}
														break;
													case SDLK_DOWN:
														if(cheatseq == 2 || cheatseq == 3)
														{
															cheatseq++;
														}
														else
														{
															cheatseq = 0;
														}
														break;
													case SDLK_LEFT:
														if(cheatseq == 4 || cheatseq == 6)
														{
															cheatseq++;
														}
														else
														{
															cheatseq = 0;
														}
														break;
													case SDLK_RIGHT:
														if(cheatseq == 5 || cheatseq == 7)
														{
															cheatseq++;
														}
														else
														{
															cheatseq = 0;
														}
														break;
													case SDLK_z:
														if(cheatseq == 8)
														{
															cheatseq++;
														}
														else
														{
															cheatseq = 0;
														}
														break;
													case SDLK_x:
														if(cheatseq == 9)
														{
															Mix_PlayChannel(-1, effect, 0);
															cheating = true;
														}
														else
														{
															cheatseq = 0;
														}
														break;
													default:
														cheatseq = 0;
														break;
												}
											}
										}
									}
									cheatseq = 0; // If you screwed up the cheat sequence
									Mix_ResumeMusic(); // play that funky music
									break;
							}
							apply_surface( 0, 0, back, screen ); // put the background up
							screen << *tile; //There. Overloading. Huzzah.
							if(hold != NULL) // display hold
							{
								hold->disp(27,78);
							}
							next->disp(390, 78); // display all the nexts
							next2->disp(390, 158);
							next3->disp(390, 238);
							numbers = TTF_RenderText_Solid(font, intToStr(score).c_str(), fontColor); //display scores
							apply_surface( 550, 50, numbers, screen );
							numbers = TTF_RenderText_Solid(font, intToStr(level).c_str(), fontColor); //Pretty sweet you can use all the sweet string functions with a function that returns a string =D
							apply_surface( 550, 120, numbers, screen );
							if( SDL_Flip( screen ) == -1 ) // show screen
							{
								return 1; //ERRRRRRR !!
							}
						}
					}
					numbers = TTF_RenderText_Solid(font, intToStr(score).c_str(), fontColor); // display scores
					apply_surface( 550, 50, numbers, screen );
					numbers = TTF_RenderText_Solid(font, intToStr(level).c_str(), fontColor);
					apply_surface( 550, 120, numbers, screen );
					if( SDL_Flip( screen ) == -1 )
					{
						return 1; //ERRRRRRR !!
					}
					SDL_Delay(1);
				}
				if(tile->check(0, 1) == 0) // if it can't fall any more
				{
					falling = false; // stop falling
				}
			}
			tile->apply(); // apply it to the pile
			held = false; // you can hold again!
			score += (level+1)*checklines(lines); // check the lines and score accordingly
			level = lines/10; // level up?
			delete tile; // delete the current tile so we don't get yelled at
		}
		delete next; // delete all the other tiles if you lost
		delete next2;
		delete next3;
		delete hold;
	}
	clean(); // uninitialize SDL and everything
	return 0; // RETURN THAT ZERO, BABY.
} // Fin
Exemple #7
0
int main(int argc, char *args[]) {
	SDL_Init(SDL_INIT_EVERYTHING); //Init SDL
	Mix_Init(MIX_INIT_FLAC | MIX_INIT_MOD | MIX_INIT_MP3 | MIX_INIT_OGG); //Init SDL Mixer
	Mix_OpenAudio(22050, AUDIO_S16SYS, 2, 4096); //Open audiostream
	int temp = officalDelay; //The delay it will play
	int holder = -1; //Hold which sound it played before
	int counter = 0; //How many soundclips have been played

	//Create window and check if it's loaded
	SDL_Window *win = SDL_CreateWindow("Omvand Synestesi", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 800, SDL_WINDOW_SHOWN);
	if (win == NULL) {
		std::cout << "Couldn't create window, unkown error." << std::endl;
	}
	
	//Make a renderer
	SDL_Renderer *renderer = SDL_CreateRenderer(win, 0, SDL_RENDERER_ACCELERATED);
	
	//Create a texture, load it. Check if it's loaded
	SDL_Texture *texture = load_texture("get.bmp", renderer);
	if(texture == NULL) {
		std::cout << "Couldn't load picture, check so it's named get.bmp" << std::endl;
	}

	//Loads a surface, this is the picture it will take and make sound of.
	SDL_Surface *image = SDL_LoadBMP("get.bmp");
	if (image == NULL) {
		std::cout << "Couldn't load picture until surface. Check the name so it is get.bmp" << std::endl;
	}

	//Load soundfiles
	Mix_Music *sound[15];
	for (int i = 1; i < 16; i++) {
		std::string path = "sound/get" + convertInt(i) + ".wav";
		sound[i] = Mix_LoadMUS(path.c_str());
		std::cout << "Loaded soundfile: " << path << std::endl;

		if (sound[i] == NULL) {
			std::cout << "Couldn't load soundfile " << path << ". Check so the name is get" << i << ".wav" << std::endl;
		}
	}

	//Loop through the whole picture
	for (int y = 0; y < size_h; y++) {
		for (int x = 0; x < size_w; x++) {
			Uint32 pix = getPixel(image, x, y);
			SDL_RenderClear(renderer); //Clear the screen
			SDL_RenderCopy(renderer, texture, NULL, NULL); //Print out the picture
			SDL_RenderPresent(renderer); //Actually render the picture
			
			int npix = pix % 16 + 1; //Get's a value from the pixel and makes it so it's just 1 to 16

			std::cout << "!-- " << pix << " --! " << npix << " | " << counter << "/1296" << std::endl; //Prints out some stuff so you can see for debugging mostly

			//If the same value is again, make a longer delay before playing next song, and if not, go back to standard delay
			if (npix == holder) {
				temp = temp + 120;
			}
			else {
				temp = officalDelay;
			}

			//Play right soundfile from value of pixel
			for (int i = 1; i < 15; i++) {
				int newi = i + 1;
				if (i == npix) {
					Mix_PlayMusic(sound[newi], 0);
					SDL_Delay(temp);
					holder = i;
				}
			}

			//If value is 16, don't play a sound and make a 3sec long delay.
			if (npix == 16) {
				std::cout << std::endl << "-----" << std::endl << std::endl;
				SDL_Delay(3000);
			}
			counter++;
		}
	}

	SDL_FreeSurface(image);
	SDL_DestroyRenderer(renderer);
	SDL_DestroyTexture(texture);
	SDL_DestroyWindow(win);

	for (int i = 1; i < 16; i++) {
		Mix_FreeMusic(sound[i]);
	}

	Mix_Quit();
	SDL_Quit();
	return 0;
}
Exemple #8
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();
    }


}
// Sets a music track, its track number will always be 0
void AudioHandler::setMusic(char* _fileName, bool _loop)
{
	AudioHandler::music = Mix_LoadMUS(_fileName);
	AudioHandler::loop = _loop;
}
Mix_Music* ZipResourceManager::getMusic(std::string name) {
	return Mix_LoadMUS(name.c_str());
}
Exemple #11
0
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;
}
Mix_Music* MusicManager::loadMusic(std::string fileName) {
	fileName = "files/sounds/" + fileName + ".wav";
	return Mix_LoadMUS("files/sounds/overworld.wav");
}
Exemple #13
0
SoundSystem::SoundSystem ()
{
  audio = false;
  sound = true;
  music = true;
  musicplaying = false;
  volumesound = 100;
  volumemusic = 100;
#ifndef USE_GLUT
  char buf [STDSIZE];
#ifndef HAVE_SDL_MIXER
  waveclick1 = new WaveFile (dirs->getSounds ("click1.wav"));
  if (SDL_OpenAudio (&waveclick1->spec, NULL) < 0)
  {
    sprintf (buf, "Couldn't open audio: %s, no sound available", SDL_GetError ());
    display (buf, LOG_ERROR);
    audio = false;
    delete waveclick1;
    return;
  }
  else
  {
    audio = true;
  }
  delete waveclick1;
#else
  display ("Using SDL_mixer", LOG_MOST);
  if (Mix_OpenAudio (22050, AUDIO_S16, 2, 4096))
  {
    display ("Unable to open audio device", LOG_ERROR);
    audio = false;
    return;
  }
  else
  {
    audio = true;
  }
  music1 = Mix_LoadMUS (dirs->getMusic ("winner.s3m"));
  if (music1 == NULL)
  {
    sprintf (buf, "Cannot open winner.s3m: %s", Mix_GetError ());
    display (buf, LOG_FATAL);
    exit (EXIT_LOADFILE);
  }
  Mix_FreeMusic (music1);
  music1 = Mix_LoadMUS (dirs->getMusic ("loser.s3m"));
  if (music1 == NULL)
  {
    sprintf (buf, "Cannot open loser.s3m: %s", Mix_GetError ());
    display (buf, LOG_FATAL);
    exit (EXIT_LOADFILE);
  }
  Mix_FreeMusic (music1);
  music1 = Mix_LoadMUS (dirs->getMusic ("dark.s3m"));
  if (music1 == NULL)
  {
    sprintf (buf, "Cannot open dark.s3m: %s", Mix_GetError ());
    display (buf, LOG_FATAL);
    exit (EXIT_LOADFILE);
  }
  Mix_FreeMusic (music1);
  music1 = Mix_LoadMUS (dirs->getMusic ("stars.s3m"));
  if (music1 == NULL)
  {
    sprintf (buf, "Cannot open stars.s3m: %s", Mix_GetError ());
    display (buf, LOG_FATAL);
    exit (EXIT_LOADFILE);
  }
  Mix_FreeMusic (music1);
  music1 = Mix_LoadMUS (dirs->getMusic ("ambient.s3m"));
  if (music1 == NULL)
  {
    sprintf (buf, "Cannot open ambient.s3m: %s", Mix_GetError ());
    display (buf, LOG_FATAL);
    exit (EXIT_LOADFILE);
  }
  Mix_FreeMusic (music1);
  music1 = Mix_LoadMUS (dirs->getMusic ("standby.s3m"));
  if (music1 == NULL)
  {
    sprintf (buf, "Cannot open standby.s3m: %s", Mix_GetError ());
    display (buf, LOG_FATAL);
    exit (EXIT_LOADFILE);
  }
  Mix_FreeMusic (music1);
  music1 = Mix_LoadMUS (dirs->getMusic ("electro.s3m"));
  if (music1 == NULL)
  {
    sprintf (buf, "Cannot open electro.s3m: %s", Mix_GetError ());
    display (buf, LOG_FATAL);
    exit (EXIT_LOADFILE);
  }
  Mix_FreeMusic (music1);
  music1 = Mix_LoadMUS (dirs->getMusic ("softtec.s3m"));
  if (music1 == NULL)
  {
    sprintf (buf, "Cannot open softtec.s3m: %s", Mix_GetError ());
    display (buf, LOG_FATAL);
    exit (EXIT_LOADFILE);
  }
  playtime = 0;
#endif
  int i;
  waveexplosion1 = new WaveFile (dirs->getSounds ("explode1.wav"));
  waveclick1 = new WaveFile (dirs->getSounds ("click1.wav"));
  wavecannon1 = new WaveFile (dirs->getSounds ("cannon1.wav"));
  wavemissile1 = new WaveFile (dirs->getSounds ("missile1.wav"));
  wavethunder1 = new WaveFile (dirs->getSounds ("thunder1.wav"));
  for (i = 0; i < 1; i ++)
  {
    sprintf (buf, "plane%d.wav", i + 1);
    waveplane [i] = new WaveFile (dirs->getSounds (buf));
  }
  engine = 0;
  wavehit1 = new WaveFile (dirs->getSounds ("hit1.wav"));
  wavebeep1 = new WaveFile (dirs->getSounds ("beep1.wav"));
  wavechaff1 = new WaveFile (dirs->getSounds ("chaff1.wav"));
  wavebeep2 = new WaveFile (dirs->getSounds ("beep2.wav"));
  wavecannon1->setVolume (50);
  wavemissile1->setVolume (110);
  waveclick1->setVolume (80);
#endif
}
int mix_play_file(char *filename, int loop, void (*hook_finished_track)())
{
	SDL_RWops *rw = NULL;
	PHYSFS_file *filehandle = NULL;
	char full_path[PATH_MAX];
	char *fptr;
	unsigned int bufsize = 0;

	mix_free_music();	// stop and free what we're already playing, if anything

	fptr = strrchr(filename, '.');

	if (fptr == NULL)
		return 0;

	// It's a .hmp!
	if (!stricmp(fptr, ".hmp"))
	{
#ifdef _WIN32 // on _WIN32, play natively
		return digi_win32_play_midi_song( filename, loop );
#else // otherwise convert and load to current_music
		hmp2mid(filename, &current_music_hndlbuf, &bufsize);
		rw = SDL_RWFromConstMem(current_music_hndlbuf,bufsize*sizeof(char));
		current_music = Mix_LoadMUS_RW(rw);
#endif
	}

	// try loading music via given filename
	if (!current_music)
		current_music = Mix_LoadMUS(filename);

	// allow the shell convention tilde character to mean the user's home folder
	// chiefly used for default jukebox level song music referenced in 'descent.m3u' for Mac OS X
	if (!current_music && *filename == '~')
	{
		snprintf(full_path, PATH_MAX, "%s%s", PHYSFS_getUserDir(),
				 &filename[1 + (!strncmp(&filename[1], PHYSFS_getDirSeparator(), strlen(PHYSFS_getDirSeparator())) ?
				 strlen(PHYSFS_getDirSeparator()) : 0)]);
		current_music = Mix_LoadMUS(full_path);
		if (current_music)
			filename = full_path;	// used later for possible error reporting
	}


	// no luck. so it might be in Searchpath. So try to build absolute path
	if (!current_music)
	{
		PHYSFSX_getRealPath(filename, full_path);
		current_music = Mix_LoadMUS(full_path);
		if (current_music)
			filename = full_path;	// used later for possible error reporting
	}

	// still nothin'? Let's open via PhysFS in case it's located inside an archive
	if (!current_music)
	{
		filehandle = PHYSFS_openRead(filename);
		if (filehandle != NULL)
		{
			unsigned len = (unsigned)(PHYSFSX_UNSAFE_TRUNCATE_TO_32BIT_INT)PHYSFS_fileLength(filehandle);
			unsigned char *p = (unsigned char *)d_realloc(current_music_hndlbuf, sizeof(char)*len);
			if (p)
			{
			current_music_hndlbuf = p;
			bufsize = (unsigned int)(PHYSFSX_UNSAFE_TRUNCATE_TO_32BIT_INT)PHYSFS_read(filehandle, current_music_hndlbuf, sizeof(char), len);
			rw = SDL_RWFromConstMem(current_music_hndlbuf,bufsize*sizeof(char));
			current_music = Mix_LoadMUS_RW(rw);
			}
			PHYSFS_close(filehandle);
		}
	}

	if (current_music)
	{
		Mix_PlayMusic(current_music, (loop ? -1 : 1));
		Mix_HookMusicFinished(hook_finished_track ? hook_finished_track : mix_free_music);
		return 1;
	}
	else
	{
		con_printf(CON_CRITICAL,"Music %s could not be loaded: %s\n", filename, Mix_GetError());
		mix_stop_music();
	}

	return 0;
}
void Meniu::Init()
{
	SDL_Surface* temp = IMG_Load("data/img/Meniu4.jpg");
	bg = SDL_DisplayFormat(temp);
	SDL_FreeSurface(temp);
//-----------------------------------------------------------------------------
 Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 4096 );
MeniuMusic = Mix_LoadMUS("data/sound/Meniu.wav");
if(!MeniuMusic)
    std::cout<<Mix_GetError()<<std::endl;
Mix_PlayMusic(MeniuMusic,1);

   /*knopke naus;
   naus.Mygtukas.set(W_HEIGHT/2 - bH/2 - 2*bH - 2*tarpas, bH, bW, "New game");
   Head.Mygtukas.set(W_HEIGHT/2 - bH/2 - 2*bH - 2*tarpas, bH, bW, "New game");
   Head.kitas=&naus;//Mygtukas.set(W_HEIGHT/2-bH/2 - bH -  tarpas, bH, bW, "Multiplayer");
   Head.kitas->kitas->Mygtukas.set( W_HEIGHT/2 - bH/2, bH, bW, "Setings");
   //--------------------------------------------------------------------------
   Head.kitas->kitas->kitas->Mygtukas.set(W_HEIGHT/2  + (bH/2 + tarpas), bH, bW, "About");

   //--------------------------------------------------------------------------
   Head.kitas->kitas->kitas->kitas->Mygtukas.set(W_HEIGHT/2+(bH/2 + bH+2*tarpas ), bH, bW, "Quit");
   Head.kitas->kitas->kitas->kitas->kitas=&Head;
   Head.kitas->kitas->kitas->kitas->buves= Head.kitas->kitas->kitas;*/

  // Head.kitas->buves=&Head;
    //M.kitas.kitas.set( W_HEIGHT/2 - bH/2, bH, bW, "Setings");
    MygtukuSarasas = new DLCL;
//-----------------------------------------------------------------------------
    Button* b1;
    b1 = new Button;
    b1->set(W_HEIGHT/2 - bH/2 - 2*bH - 2*tarpas, bH, bW, "New game");
    MygtukuSarasas->insert(b1);
//-----------------------------------------------------------------------------
    Button* b2;
    b2 = new Button;
    b2->set(W_HEIGHT/2-bH/2 - bH -  tarpas, bH, bW, "Multiplayer");
    MygtukuSarasas->insert(b2);

//-----------------------------------------------------------------------------
    Button* b3;
    b3 = new Button;
    b3->set( W_HEIGHT/2 - bH/2, bH, bW, "Settings");
    MygtukuSarasas->insert(b3);
//-----------------------------------------------------------------------------
    Button* b4;
    b4 = new Button;
    b4->set(W_HEIGHT/2  + (bH/2 + tarpas), bH, bW, "About");
    MygtukuSarasas->insert(b4);
//-----------------------------------------------------------------------------
    Button* b5;
    b5 = new Button;
    b5->set(W_HEIGHT/2+(bH/2 + bH+2*tarpas ), bH, bW, "Quit");
    MygtukuSarasas->insert(b5);
//-----------------------------------------------------------------------------



    Naujas.set(W_HEIGHT/2 - bH/2 - 2*bH - 2*tarpas, bH, bW, "New game");

    Multiplayer.set(W_HEIGHT/2-bH/2 - bH -  tarpas, bH, bW, "Multiplayer");

    Nustatymai.set( W_HEIGHT/2 - bH/2, bH, bW, "Settings");//per lango viduri

    Apie.set(W_HEIGHT/2  + (bH/2 + tarpas), bH, bW, "About");
    Iseiti.set(W_HEIGHT/2+(bH/2 + bH+2*tarpas ), bH, bW, "Quit");


}
void Game::Start()
{
  // Seed the random number generator
  srand(time(NULL));

  GameEngine *pGE = GameEngine::GetEngine();
  SDL_Renderer *renderer = pGE->GetRenderer();

  // Create and load the bitmaps
  SDL_Color scTrans = {255, 0, 255, 255};
  _pOfficeBitmap = new Bitmap(renderer, "res/Office.bmp");
  _pTargetBitmap = new Bitmap(renderer, "res/Target.bmp", &scTrans);
  _pPowBitmap = new Bitmap(renderer, "res/Pow.bmp", &scTrans);
  _pGuyBitmaps[0] = new Bitmap(renderer, "res/Guy1.bmp", &scTrans);
  _pGuyBitmaps[1] = new Bitmap(renderer, "res/Guy2.bmp", &scTrans);
  _pGuyBitmaps[2] = new Bitmap(renderer, "res/Guy3.bmp", &scTrans);
  _pGuyBitmaps[3] = new Bitmap(renderer, "res/Guy4.bmp", &scTrans);
  _pGuyBitmaps[4] = new Bitmap(renderer, "res/Guy5.bmp", &scTrans);
  _pSmallGuyBitmap = new Bitmap(renderer, "res/SmallGuy.bmp", &scTrans);
  _pGameOverBitmap = new Bitmap(renderer, "res/GameOver.bmp", &scTrans);

  // Create the target, pow, and guy sprites
  SDL_Rect rcBounds = { 0, 0, 500, 400 };
  _pTargetSprite = new Sprite(_pTargetBitmap, rcBounds, BA_STOP);
  _pTargetSprite->SetZOrder(4);
  pGE->AddSprite(_pTargetSprite);
  _pPowSprite = new Sprite(_pPowBitmap, rcBounds, BA_STOP);
  _pPowSprite->SetZOrder(3);
  _pPowSprite->SetHidden(true);
  pGE->AddSprite(_pPowSprite);
  _pGuySprites[0] = new Sprite(_pGuyBitmaps[0], rcBounds);
  _pGuySprites[0]->SetPosition(92, 175);
  _pGuySprites[0]->SetZOrder(2);
  _pGuySprites[0]->SetHidden(true);
  pGE->AddSprite(_pGuySprites[0]);
  _pGuySprites[1] = new Sprite(_pGuyBitmaps[1], rcBounds);
  _pGuySprites[1]->SetPosition(301, 184);
  _pGuySprites[1]->SetZOrder(2);
  _pGuySprites[1]->SetHidden(true);
  pGE->AddSprite(_pGuySprites[1]);
  _pGuySprites[2] = new Sprite(_pGuyBitmaps[2], rcBounds);
  _pGuySprites[2]->SetPosition(394, 61);
  _pGuySprites[2]->SetZOrder(2);
  _pGuySprites[2]->SetHidden(true);
  pGE->AddSprite(_pGuySprites[2]);
  rcBounds.x = 340;
  _pGuySprites[3] = new Sprite(_pGuyBitmaps[3], rcBounds, BA_WRAP);
  _pGuySprites[3]->SetNumFrames(4);
  _pGuySprites[3]->SetPosition(500, 10);
  _pGuySprites[3]->SetVelocity(-3, 0);
  _pGuySprites[3]->SetZOrder(1);
  _pGuySprites[3]->SetHidden(true);
  pGE->AddSprite(_pGuySprites[3]);
  rcBounds.x = 385;
  _pGuySprites[4] = new Sprite(_pGuyBitmaps[4], rcBounds, BA_WRAP);
  _pGuySprites[4]->SetNumFrames(4);
  _pGuySprites[4]->SetFrameDelay(5);
  _pGuySprites[4]->SetPosition(260, 60);
  _pGuySprites[4]->SetVelocity(5, 0);
  _pGuySprites[4]->SetZOrder(1);
  _pGuySprites[4]->SetHidden(true);
  pGE->AddSprite(_pGuySprites[4]);

  // Initialize the remaining global variables
  _iGuyMasterDelay = 50;
  _iHits = 0;
  _iMisses = 0;
  _bGameOver = false;
  
  //Load the music
  _mmMusic = Mix_LoadMUS("res/Music.xm");
  if(_mmMusic==nullptr) cout << "Could not play music: " <<  Mix_GetError();

  //Load the sound effetcs
  _mcWhack = Mix_LoadWAV("res/Whack.wav");
  _mcTaunt = Mix_LoadWAV("res/Taunt.wav");
  _mcBoo = Mix_LoadWAV("res/Boo.wav");
  
  // Play the background music
  pGE->PlaySong(_mmMusic);
}
Exemple #17
0
int main(int argc, char *argv[]) {
    Matrix projectionMatrix;
    Matrix modelMatrix;
    Matrix viewMatrix;
    
    init();
    ShaderProgram program(RESOURCE_FOLDER "vertex_textured.glsl", RESOURCE_FOLDER "fragment_textured.glsl");
    glUseProgram(program.programID);

    float lastFrameTicks = 0.0f;

//    float vertices[] = {-0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5};
//    float texCoords[] = {0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0};
//    float vertices[] = {-0.09, -0.09, 0.09, -0.09, 0.09, 0.09, -0.09, -0.09, 0.09, 0.09, -0.09, 0.09};
    Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 4096 );
    SDL_Event event;
    bool done = false;
    
/*    Sprites courtesy of http://gooperblooper22.deviantart.com/art/Space-Invaders-Sprite-Sheet-135338373  */
    GLuint spriteSheetTexture = LoadTexture("space_invaders_sprite_sheet_by_gooperblooper22.png");
    GLuint white = LoadTexture("white.png");
    GLuint textTexture = LoadTexture("font1.png");
    Mix_Music *bgm = Mix_LoadMUS("bgm.mp3");
    Mix_Chunk *missile = Mix_LoadWAV("157439__nengisuls__misslie-1.wav");
    bool pressed = false;
    int score = 0;
    int currentIndex = 0;
    int state;
    const int numFrames = 2;
    float animation[] = {(74.0f/617.0f),(107.0f/617.0f)};
    float animationElapsed = 0.0f;
    float framesPerSecond = 0.0004f;
    std::vector<SheetSprite> aliens;
    
    while (!done) {
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) {
                done = true;
            }
        }
        program.setProjectionMatrix(projectionMatrix);
        program.setModelMatrix(modelMatrix);
        program.setViewMatrix(viewMatrix);
        
        float ticks = (float)SDL_GetTicks()/1000;
        float elapsed = ticks - lastFrameTicks;
        lastFrameTicks = ticks;
        
        animationElapsed += 1/elapsed;
        if(animationElapsed > 1.0/framesPerSecond) {
            currentIndex++;
            animationElapsed = 0.0;
            if(currentIndex > numFrames-1) {
                currentIndex = 0;
            }
        }
        
        glClear(GL_COLOR_BUFFER_BIT);
        
        score = ticks;
        SheetSprite menu(spriteSheetTexture, 160.0f/617.0f, 1.0f/2035.0f, 250.0f/617.0f, 171.0f/2035.0f, 0.5);
        Entity text;
        Player cannon(spriteSheetTexture, 277.0f/617.0f, 227.0f/2035.0f, 26.0f/617.0f, 17.0f/2035.0f, 0.05);
        SheetSprite alien(spriteSheetTexture, animation[currentIndex], (225.0f/2035.0f), 22.0f/617.0f, 16.0f/2035.0f, 0.05);
        
        const Uint8 *keys = SDL_GetKeyboardState(NULL);
        
        switch (state) {
            case STATE_MAIN_MENU:
                menu.update(lastFrameTicks, elapsed, projectionMatrix, viewMatrix, program, true);
                menu.draw(program);
                if (!Mix_PlayingMusic()) {
                    Mix_PlayMusic(bgm, -1);
                }
                if (keys[SDL_SCANCODE_RETURN]) {
                    state++;
                }
                break;
                
            case STATE_GAME_LEVEL:
                text.DrawText(program, textTexture, "Score:" + std::to_string(score), 0.075, 0, -0.23, 0.9);
                cannon.update(lastFrameTicks, elapsed, projectionMatrix, viewMatrix, program, white, alien);
                cannon.draw(program);
                alien.update(lastFrameTicks, elapsed, projectionMatrix, viewMatrix, program, false);
                alien.draw(program);
                if (keys[SDL_SCANCODE_SPACE]) {
                    Mix_PlayChannel( -1, missile, 0);
                    Mix_VolumeChunk(missile, 15);
                }
                if (keys[SDL_SCANCODE_ESCAPE] && (state == 1)) {
                    pressed = true;
                    state++;
                }
                
                break;
            case STATE_PAUSE:
                if (Mix_PlayingMusic()) {
                    Mix_PausedMusic();
                }
                text.DrawText(program, textTexture, "Paused", 0.1, 0, -0.23, 0);
                if (keys[SDL_SCANCODE_ESCAPE] && pressed) {
                    pressed = false;
                    state--;
                }
                break;
                
        }
        SDL_GL_SwapWindow(displayWindow);
    }
    Mix_FreeMusic(bgm);
    Mix_FreeChunk(missile);
    Mix_Quit();
    cleanup();
    return 0;
}
Exemple #18
0
// based on http://www.willusher.io/sdl2%20tutorials/2013/08/17/lesson-1-hello-world/
int main( int argc, char* args[] )
{
	if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
	{
		std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
		cleanExit(1);
	}
	std::cout << "SDL initialised OK!\n";

	// Initialise the audio mixer and also explained the variables.
	// 44100 - Common hertz level for these things
	// MIX_DEFAULT_FORMAT - Like the SDL_INIT_EVERYTHING, some init settings
	// 2 - Audio Channels for stereo play
	// 2048 - Sample size, can affect lag time for effect to play
	// != 0 - Same as other init stuff, not sure why, just needs it.
	if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) != 0)
	{
		std::cout << "SDL_Mixer init error: " << Mix_GetError() << std::endl;
		cleanExit(1);
	}
	std::cout << "SDP_Mixer Initialised OK!" << std::endl;
	//create window
	win = SDL_CreateWindow("SDL Hello World!", 100, 100, screenW, screenH, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);

	//error handling
	if (win == nullptr)	
	{
		std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
		cleanExit(1);
	}
	std::cout << "SDL CreatedWindow OK!\n";

	ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
	if (ren == nullptr)
	{
		std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl;
		cleanExit(1);
	}

	player = new sprite("./assets/spritesheet.png", 50.0f, 520.0f, 24.0f, 32.0f, ren);
	player->srcRect.x = 0.0f;
	player->srcRect.y = 96.0f;
	player->srcRect.w = 24.0f;
	player->srcRect.h = 32.0f;
	player->playerScore = 0;
	player->bufferMax = 5;

#pragma region Hens
	hen1 = new enemy("./assets/spritesheet.png", 500, 100, 24, 40, ren);
	hens.push_back(hen1);
	hen1->state = enemy::moveRight;
	hen1->flipDirection = true;
	hen1->xTarget1 = 200.0f;
	hen1->xTarget2 = 250.0f;
	hen1->srcRect.x = 0.0f;
	hen1->srcRect.y = 0.0f;
	hen1->srcRect.w = 24.0f;
	hen1->srcRect.h = 40.0f;

	hen2 = new enemy("./assets/spritesheet.png", 700, 530, 24, 40, ren);
	hens.push_back(hen2);
	hen2->state = enemy::moveLeft;
	hen2->xTarget1 = 100.0f;
	hen2->xTarget2 = 750.0f;
	hen2->srcRect.x = 0.0f;
	hen2->srcRect.y = 0.0f;
	hen2->srcRect.w = 24.0f;
	hen2->srcRect.h = 40.0f;

	hen3 = new enemy("./assets/spritesheet.png", 600, 280, 24, 40, ren);
	hens.push_back(hen3);
	hen3->state = enemy::moveRight;
	hen3->xTarget1 = 100.0f;
	hen3->xTarget2 = 750.0f;
	hen3->srcRect.x = 0.0f;
	hen3->srcRect.y = 0.0f;
	hen3->srcRect.w = 24.0f;
	hen3->srcRect.h = 40.0f;
#pragma endregion

#pragma region Audio stuff
	// This is formatted in the same way to the default code from John as it makes sense and I want to stick to it.
	jumpEffect = Mix_LoadWAV("./assets/jump.wav");
	if (jumpEffect == nullptr)
	{
		std::cout << "Mix_LoadWAV Error: " << Mix_GetError() << std::endl;
		cleanExit(1);
	}

	pickup1 = Mix_LoadWAV("./assets/pickup1.wav");
	if (pickup1 == nullptr)
	{
		std::cout << "Mix_LoadWAV Error: " << Mix_GetError() << std::endl;
		cleanExit(1);
	}

	pickup2 = Mix_LoadWAV("./assets/pickup2.wav");
	if (pickup2 == nullptr)
	{
		std::cout << "Mix_LoadWAV Error: " << Mix_GetError() << std::endl;
		cleanExit(1);
	}

	background = Mix_LoadMUS("./assets/background_music.wav");
	if (background == nullptr)
	{
		std::cout << "Mix_LoadWAV Error: " << Mix_GetError() << std::endl;
		cleanExit(1);
	}
#pragma endregion


	if( TTF_Init() == -1 )
	{
		std::cout << "TTF_Init Failed: " << TTF_GetError() << std::endl;
		cleanExit(1);
	}

	TTF_Font* sans = TTF_OpenFont("./assets/Hack-Regular.ttf", 96);
	if (sans == nullptr)
	{
		std::cout << "TTF_OpenFont Error: " << TTF_GetError() << std::endl;
		cleanExit(1);
	}
	SDL_Color White = { 255, 255, 255 };
	SDL_Color Purple = { 165, 0, 220 };
	
	std::string lives = "Lives: " + std::to_string(player->playerLives);
	const char* lifeCounts = lives.c_str();

	loading = new text(ren, "Loading...", 200, 200, 400, 130, sans, White);
	Load();

	scoreCount = new text(ren, player->playerScore, 0, 0, 180, 60, sans, Purple);
	lifeCount = new text(ren, lifeCounts, 600, 0, 180, 60, sans, Purple);

	drawTileMap();

	loading->isShowing = false;
	Mix_PlayMusic(background, -1);

	while (!done) //loop until done flag is set)
	{
		handleInput(); // this should ONLY SET VARIABLES

		updateSimulation(); // this should ONLY SET VARIABLES according to simulation

		render(); // this should render the world state according to VARIABLES

		SDL_Delay(20); // unless vsync is on??
	}

	cleanExit(0);
	return 0;
}
AudioHandle AudioManagerSDL::Play( string fName, bool bLooping /*= false*/, bool bIsMusic, bool bAddBasePath, bool bForceStreaming)
{

#ifdef _DEBUG
	//LogMsg("********** AudioSDL: Thinking of playing %s, music=%d", fName.c_str(), int(bIsMusic));
#endif

	if (!GetSoundEnabled() && !bIsMusic) return AUDIO_HANDLE_BLANK;
	if (!GetMusicEnabled() && bIsMusic)
	{
		m_bLastMusicLooping = bLooping;
		m_lastMusicFileName = fName;

		return AUDIO_HANDLE_BLANK;
	}

	if (bIsMusic && m_bLastMusicLooping == bLooping && m_lastMusicFileName == fName && m_bLastMusicLooping && IsPlaying((AudioHandle) m_pMusicChannel))
	{
		return (AudioHandle) m_pMusicChannel;
	}

	int loops = 0;
	if (bLooping) loops = -1;

	if (bIsMusic)
	{
		string basePath;

		if (bAddBasePath)
		{
			basePath = GetBaseAppPath();
		}

		m_lastMusicFileName = fName;

		StopMusic();
		m_pMusicChannel = Mix_LoadMUS( (basePath+fName).c_str());

		if (!m_pMusicChannel && !bAddBasePath)
		{
			LogError("Couldn't load %s, trying again with full path", (basePath+fName).c_str());

			basePath = GetBaseAppPath();
			//try again with the basepath added.. the SDL sound system on webos seems to require it
			m_pMusicChannel = Mix_LoadMUS((basePath+fName).c_str());
		}

		if (!m_pMusicChannel)
		{
			LogError("Unable to load music file %s. Missing?", (basePath+fName).c_str());
			return AUDIO_HANDLE_BLANK;
		}
		m_lastMusicID = (AudioHandle) m_pMusicChannel;
		m_bLastMusicLooping = bLooping;
		
		SetMusicVol(m_musicVol);

		int ret = Mix_PlayMusic(m_pMusicChannel, loops);
		if (ret == -1)
		{
			LogError("Unable to play music file %s.", (GetBaseAppPath()+fName).c_str());
		}

		return (AudioHandle) m_pMusicChannel;
	}

	//non music

	SoundObject *pObject = GetSoundObjectByFileName(fName);

	if (!pObject)
	{
		//create it
		Preload(fName, bLooping, bIsMusic, bAddBasePath, bForceStreaming);
		pObject = GetSoundObjectByFileName(fName);
		if (!pObject)
		{
			LogError("Unable to cache sound %s", fName.c_str());
			return AUDIO_HANDLE_BLANK;

		}
	}

#ifdef _DEBUG
	//LogMsg("AudioSDL: Playing sfx %s", fName.c_str());
#endif

	//play it
	
	int channel = Mix_PlayChannel(-1, pObject->m_pSound, loops);
	if (channel == -1)
	{
		pObject->m_pLastChannelToUse = AUDIO_HANDLE_BLANK;
		return AUDIO_HANDLE_BLANK;
	}
	pObject->m_pLastChannelToUse = channel + C_CHANNEL_OFFSET_SO_ZERO_ISNT_USED;

	//need this because sometimes it's set to nothing by default??
	SetVol(pObject->m_pLastChannelToUse, 1.0f);

	return (AudioHandle)pObject->m_pLastChannelToUse ;
}
Music::Music(const string & name, const string & fileName) : name_(name), mixMusic(Mix_LoadMUS(fileName.c_str())) {}
Exemple #21
0
void setup (void) {
	SDL_Surface * image;
	TTF_Font *temp1, *temp2;
	SDL_Color color;
	SDL_Rect rect, rect2;
	int g;
	char buffer_file[8192];
	char *systemdata_path = get_systemdata_path ();
	
	/* Inicializar el Video SDL */
	if (SDL_Init(SDL_INIT_VIDEO) < 0) {
		fprintf (stderr,
			_("Error: Can't initialize the video subsystem\n"
			"The error returned by SDL is:\n"
			"%s\n"), SDL_GetError());
		exit (1);
	}
	sprintf (buffer_file, "%simages/icon.png", systemdata_path);
	image = IMG_Load (buffer_file);
	if (image) {
		SDL_WM_SetIcon (image, NULL);
		SDL_FreeSurface (image);
	}
	SDL_WM_SetCaption (_("Paddle Puffle"), _("Paddle Puffle"));
	
	/* Crear la pantalla de dibujado */
	screen = set_video_mode (0);
	
	if (screen == NULL) {
		fprintf (stderr,
			_("Error: Can't setup 760x480 video mode.\n"
			"The error returned by SDL is:\n"
			"%s\n"), SDL_GetError());
		exit (1);
	}
	
	use_sound = 1;
	if (SDL_InitSubSystem (SDL_INIT_AUDIO) < 0) {
		fprintf (stdout,
			_("Warning: Can't initialize the audio subsystem\n"
			"Continuing...\n"));
		use_sound = 0;
	}
	
	if (use_sound) {
		/* Inicializar el sonido */
		if (Mix_OpenAudio (22050, AUDIO_S16, 2, 4096) < 0) {
			fprintf (stdout,
				_("Warning: Can't initialize the SDL Mixer library\n"));
			use_sound = 0;
		}
	}
	
	for (g = 0; g < NUM_IMAGES; g++) {
		sprintf (buffer_file, "%s%s", systemdata_path, images_names[g]);
		image = IMG_Load (buffer_file);
		
		if (image == NULL) {
			fprintf (stderr,
				_("Failed to load data file:\n"
				"%s\n"
				"The error returned by SDL is:\n"
				"%s\n"), buffer_file, SDL_GetError());
			SDL_Quit ();
			exit (1);
		}
		
		images[g] = image;
		/* TODO: Mostrar la carga de porcentaje */
	}
	
	/* Pre-Dibujar la pantalla gris */
	grey_screen = SDL_CreateRGBSurface (SDL_SWSURFACE | SDL_SRCALPHA, 760, 480, 32, 0, 0, 0, 0);
	SDL_FillRect (grey_screen, NULL,
	              SDL_MapRGB (grey_screen->format, 0, 0, 0)); /* Negro */
	SDL_SetAlpha (grey_screen, SDL_SRCALPHA, 128); /* Alpha al 50 % */
	
	if (use_sound) {
		for (g = 0; g < NUM_SOUNDS; g++) {
			sprintf (buffer_file, "%s%s", systemdata_path, sound_names[g]);
			sounds[g] = Mix_LoadWAV (buffer_file);
			
			if (sounds[g] == NULL) {
				fprintf (stderr,
					_("Failed to load data file:\n"
					"%s\n"
					"The error returned by SDL is:\n"
					"%s\n"), buffer_file, SDL_GetError ());
				SDL_Quit ();
				exit (1);
			}
			Mix_VolumeChunk (sounds[g], MIX_MAX_VOLUME / 2);
		}
		
		/* Cargar la música */
		sprintf (buffer_file, "%s%s", systemdata_path, MUS_CARNIE);
		mus_carnie = Mix_LoadMUS (buffer_file);
		
		if (mus_carnie == NULL) {
			fprintf (stderr,
				_("Failed to load data file:\n"
				"%s\n"
				"The error returned by SDL is:\n"
				"%s\n"), buffer_file, SDL_GetError ());
			SDL_Quit ();
			exit (1);
		}
		
	}
	
	if (TTF_Init () < 0) {
		fprintf (stderr,
			_("Error: Can't initialize the SDL TTF library\n"
			"%s\n"), TTF_GetError ());
		SDL_Quit ();
		exit (1);
	}
	
	/* Tipografias 10, 14, 16, 26 */
	sprintf (buffer_file, "%s%s", systemdata_path, "ccfacefront.ttf");
	ttf_facefront = SDL_RWFromFile (buffer_file, "rb");
	
	if (ttf_facefront == NULL) {
		fprintf (stderr,
			_("Failed to load font file 'CCFaceFront'\n"
			"The error returned by SDL is:\n"
			"%s\n"), TTF_GetError ());
		SDL_Quit ();
		exit (1);
	}
	
	SDL_RWseek (ttf_facefront, 0, RW_SEEK_SET);
	temp1 = TTF_OpenFontRW (ttf_facefront, 0, 10);
	SDL_RWseek (ttf_facefront, 0, RW_SEEK_SET);
	ttf14_normal = TTF_OpenFontRW (ttf_facefront, 0, 14);
	SDL_RWseek (ttf_facefront, 0, RW_SEEK_SET);
	ttf16_normal = TTF_OpenFontRW (ttf_facefront, 0, 16);
	SDL_RWseek (ttf_facefront, 0, RW_SEEK_SET);
	ttf26_normal = TTF_OpenFontRW (ttf_facefront, 0, 26);
	
	if (!temp1 || !ttf14_normal || !ttf16_normal || !ttf26_normal) {
		SDL_Quit ();
		exit (1);
	}
	
	SDL_RWseek (ttf_facefront, 0, RW_SEEK_SET);
	ttf20_normal = TTF_OpenFontRW (ttf_facefront, 0, 20);
	SDL_RWseek (ttf_facefront, 0, RW_SEEK_SET);
	ttf20_outline = TTF_OpenFontRW (ttf_facefront, 0, 20);
	SDL_RWseek (ttf_facefront, 0, RW_SEEK_SET);
	ttf16_outline = TTF_OpenFontRW (ttf_facefront, 1, 16);
	
	if (!ttf20_normal || !ttf20_outline || !ttf16_outline) {
		SDL_Quit ();
		exit (1);
	}
	
	TTF_SetFontStyle (temp1, TTF_STYLE_ITALIC);
	TTF_SetFontStyle (ttf14_normal, TTF_STYLE_ITALIC);
	TTF_SetFontStyle (ttf16_normal, TTF_STYLE_ITALIC);
	TTF_SetFontStyle (ttf26_normal, TTF_STYLE_ITALIC);
	TTF_SetFontStyle (ttf16_outline, TTF_STYLE_ITALIC);
	TTF_SetFontStyle (ttf20_outline, TTF_STYLE_ITALIC);
	TTF_SetFontStyle (ttf20_normal, TTF_STYLE_ITALIC);
	
	TTF_SetFontOutline (ttf16_outline, OUTLINE_TEXT);
	TTF_SetFontOutline (ttf20_outline, OUTLINE_TEXT);
	
	/* Generar textos */
	bind_textdomain_codeset (PACKAGE, "UTF-8");
	color.r = color.g = color.b = 0; /* Negro */
	
	for (g = 0; g < NUM_TEXTS; g++) {
		switch (text_info [g]) {
			case 10: temp2 = temp1; break;
			case 14: temp2 = ttf14_normal; break;
			case 16: temp2 = ttf16_normal; break;
			case 26: temp2 = ttf26_normal; break;
			default: temp2 = ttf16_normal;
		}
		
		texts[g] = draw_text (temp2, _(text_strings[g]), &color);
	}
	
	/* Copiar la palabra "Tickets" en el background */
	/* También copiar el nombre del juego al titulo y al fondo */
	rect.x = 607 + ((135 - texts[TEXT_TICKETS]->w) / 2); rect.y = 38;
	rect.w = texts[TEXT_TICKETS]->w; rect.h = texts[TEXT_TICKETS]->h;
	rect2.x = 191; rect2.y = 96;
	rect2.w = images[IMG_TITLE]->w; rect2.h = images[IMG_TITLE]->h;
	for (g = IMG_BACKGROUND_NORMAL; g <= IMG_BACKGROUND_FAIL_1; g++) {
		SDL_BlitSurface (texts[TEXT_TICKETS], NULL, images[g], &rect);
		SDL_BlitSurface (images[IMG_TITLE], NULL, images[g], &rect2);
	}
	
	/* X = 84.35, Y = 50.85 */
	rect2.x = 84; rect2.y = 51;
	SDL_BlitSurface (images[IMG_TITLE], NULL, images[IMG_TITLE_OPENING], &rect2);
	
	TTF_CloseFont (temp1);
	/* Generador de números aleatorios */
	srand ((unsigned int) getpid ());
}
Exemple #22
0
/**
 *  Läd ein Musikstück.
 *
 *  @param[in] type Typ der Daten
 *  @param[in] data Datenblock
 *  @param[in] size Größe des Datenblocks
 *
 *  @return Sounddeskriptor bei Erfolg, @p NULL bei Fehler
 *
 *  @author FloSoft
 */
Sound *AudioSDL::LoadMusic(unsigned int data_type, unsigned char *data, unsigned long size)
{
	SoundSDL_Music * sd = new SoundSDL_Music;

	char file[512];
	if(!tempname(file, 512))
		return false;

	switch(data_type)
	{
	default:
		return false;

	case AudioDriver::AD_MIDI:
		{
			strncat(file, ".mid", 512);
		} break;

	case AudioDriver::AD_WAVE:
		{
			strncat(file, ".wav", 512);
		} break;

	case AudioDriver::AD_OTHER:
		{
			const char *header = (const char*)data;
			if(strncmp(header, "OggS", 4) == 0)
				strncat(file, ".ogg", 512);
			else if (strncmp(header, "ID3", 3) == 0 || ((unsigned char)header[0] == 0xFF && (unsigned char)header[1] == 0xFB) )
				strncat(file, ".mp3", 512);
			else
				strncat(file, ".tmp", 512);
		} break;

	/// @todo Alle Formate die SDL mit LoadMUS laden kann angeben
	}

	FILE *dat = fopen(file, "wb");
	if(!dat)
		return false;

	if(fwrite(data, 1, size, dat) != size)
		return false;

	fclose(dat);

	sd->music = Mix_LoadMUS(file);

	unlink(file);

	if(sd->music == NULL)
	{
		fprintf(stderr, "%s\n", Mix_GetError());
		delete sd;
		return NULL;
	}
	
	sd->SetNr((int)sounds.size());
	sounds.push_back(sd);

	return sd;
}
Exemple #23
0
//Displays the menu of the game
void Application::menu()
{
    if (gWindow == NULL)
    {
        //Start up SDL and create window
        if (!init())
        {
            printf("Failed to initialize!\n");
        }
    }
    menuBackgroundSound = Mix_LoadMUS("sounds/menu_background.mp3");
    Mix_PlayMusic(menuBackgroundSound, 10);
    LTexture menuBackgroundTexture;
    int start = 0;

    //------------BUTTONS------------
    loadButtonMedia();

    //--------------TEXT LOADING---------
    loadText();

    SDL_Color textColor = { 0x00, 0xCC, 0xFF };

    //-------------BUTTON SET POS & BACKGROUND----------
    menuBackgroundTexture.loadFromFile("img/menu.png", gRenderer);


    lastTenGamesManager.createBlankFile();
    std::fstream gameFile("previousGames.txt", std::ios::out | std::ios::in);

    //Main loop flag
    bool quit = false;
    isMusicOn = true;
    //Event handler
    SDL_Event e;
    const int screenTicksPF = 1000 / screenFPS;
    Timer fpsTimer, capTimer;
    fpsTimer.start();

    //While application is running
    while (!quit)
    {
        capTimer.start();
        //Handle events on queue
        while (SDL_PollEvent(&e) != 0)
        {
            //User requests quit
            if (e.type == SDL_QUIT || e.key.keysym.sym == SDLK_ESCAPE || exitButton->handleEvent(&e))
            {
                quit = true;
                gameFile.close();
            }
            else if (onMusicButton->handleEvent(&e))
            {
                checkMusic();
            }
            else if (startButton->handleEvent(&e) && gameData.getPlayerBet() > 0)
            {
                moneyManager.setCredit(gameData.getStartCredit());
                startTimeTemp = SDL_GetTicks();
                this->deposit = 0;
                depositNum->loadFromRenderedText(std::to_string(this->deposit), textColor, *gRenderer);
                int chosenCar = chooseCar(gRenderer);
                if (chosenCar != 0)
                {
                    gameStart(gameFile, chosenCar);
                }
                else
                {
                    continue;//if escape is pressed returns to main loop
                }
                if (isMusicOn)
                {
                    Mix_PlayMusic(menuBackgroundSound, 10);
                }
                moneyManager.setCredit(gameData.getStartCredit());
                betNum->loadFromRenderedText(std::to_string((int)gameData.getPlayerBet()), textColor, *gRenderer);
                creditNumber->loadFromRenderedText(std::to_string((int)gameData.getStartCredit()), textColor, *gRenderer);
            }
            else if (instructionsButton->handleEvent(&e))
            {
                instructionsScreen();
            }
            else if (lastTenGamesButton->handleEvent(&e))
            {
                lastTenGamesScreen(gameFile);
            }
            else if (addDepositButton->handleEvent(&e))
            {
                moneyManager.addDeposit(this->deposit);
                depositNum->loadFromRenderedText(std::to_string(deposit), textColor, *gRenderer);
            }
            else if (removeDepositButton->handleEvent(&e))
            {
                moneyManager.removeDeposit(this->deposit);
                depositNum->loadFromRenderedText(std::to_string(deposit), textColor, *gRenderer);
            }
            else if (makeDepositButton->handleEvent(&e))
            {
                double startCredit = gameData.getStartCredit();
                moneyManager.makeDeposit(startCredit, this->deposit);
                gameData.setStartCredit(startCredit);
                creditNumber->loadFromRenderedText(std::to_string((int)gameData.getStartCredit()), textColor, *gRenderer);
                depositNum->loadFromRenderedText(std::to_string(this->deposit), textColor, *gRenderer);
            }
            else if (addBetButton->handleEvent(&e))
            {
                double playerBet = gameData.getPlayerBet();
                moneyManager.makeBet(gameData.getStartCredit(), playerBet);
                gameData.setPlayerBet(playerBet);
                betNum->loadFromRenderedText(std::to_string((int)gameData.getPlayerBet()), textColor, *gRenderer);
            }
            else if (removeBetButton->handleEvent(&e))
            {
                double playerBet = gameData.getPlayerBet();
                moneyManager.removeBet(playerBet);
                gameData.setPlayerBet(playerBet);
                betNum->loadFromRenderedText(std::to_string((int)gameData.getPlayerBet()), textColor, *gRenderer);
            }
        }
        //--------------CLEAR SCREEN-----------
        SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF);
        SDL_RenderClear(gRenderer);

        menuBackgroundTexture.render(*gRenderer, 0, 0);
        renderMenuTextures();

        if (gameData.getStartCredit() != 0)
        {
            creditText->render(*gRenderer, 50, 50);
            creditNumber->render(*gRenderer, 220, 50);
        }
        else
        {
            blinkingEffect(start);
            start++;
        }

        //------------- UPDATE SCREEN----------------
        SDL_RenderPresent(gRenderer);

        int frameTicks = capTimer.getTicks();
        if (frameTicks < screenTicksPF)
        {
            SDL_Delay(screenTicksPF - frameTicks);
        }
    }
}
void XMIPlayer::changeMusic(MUSICTYPE musicType)
{
	int musicNum = -1;
	std::string filename = "";

	if(currentMusicType == musicType && Mix_PlayingMusic()) {
		return;
	}

    /* currently unused:
        DUNE0.XMI/4
        DUNE1.XMI/2 and DUNE10.XMI/2
    */


	switch(musicType) {
		case MUSIC_ATTACK: {

            switch(getRandomInt(0, 5)) {
                case 0:     filename = "DUNE10.XMI";    musicNum = 7;   break;
                case 1:     filename = "DUNE11.XMI";    musicNum = 7;   break;
                case 2:     filename = "DUNE12.XMI";    musicNum = 7;   break;
                case 3:     filename = "DUNE13.XMI";    musicNum = 7;   break;
                case 4:     filename = "DUNE14.XMI";    musicNum = 7;   break;
                case 5:     filename = "DUNE15.XMI";    musicNum = 7;   break;
            }

		} break;

		case MUSIC_PEACE: {

            switch(getRandomInt(0, 8)) {
                case 0:     filename = "DUNE1.XMI";     musicNum = 6;   break;
                case 1:     filename = "DUNE2.XMI";     musicNum = 6;   break;
                case 2:     filename = "DUNE3.XMI";     musicNum = 6;   break;
                case 3:     filename = "DUNE4.XMI";     musicNum = 6;   break;
                case 4:     filename = "DUNE5.XMI";     musicNum = 6;   break;
                case 5:     filename = "DUNE6.XMI";     musicNum = 6;   break;
                case 6:     filename = "DUNE9.XMI";     musicNum = 4;   break;
                case 7:     filename = "DUNE9.XMI";     musicNum = 5;   break;
                case 8:     filename = "DUNE18.XMI";    musicNum = 6;   break;
            }

		} break;

		case MUSIC_INTRO: {
		    filename = "DUNE0.XMI";
		    musicNum = 2;
        } break;

		case MUSIC_MENU: {
		    filename = "DUNE7.XMI";
		    musicNum = 6;
        } break;

		case MUSIC_BRIEFING_H: {
		    filename = "DUNE7.XMI";
		    musicNum = 2;
        } break;

		case MUSIC_BRIEFING_A: {
		    filename = "DUNE7.XMI";
		    musicNum = 3;
        } break;

		case MUSIC_BRIEFING_O: {
		    filename = "DUNE7.XMI";
		    musicNum = 4;
        } break;

		case MUSIC_WIN_H: {
		    filename = "DUNE8.XMI";
		    musicNum = 3;
		} break;

		case MUSIC_WIN_A: {
		    filename = "DUNE8.XMI";
		    musicNum = 2;
		} break;

		case MUSIC_WIN_O: {
		    filename = "DUNE17.XMI";
		    musicNum = 4;
		} break;

		case MUSIC_LOSE: {
		    filename = "DUNE1.XMI";
		    musicNum = 4;
		} break;

        case MUSIC_GAMESTAT: {
            filename = "DUNE20.XMI";
            musicNum = 2;
		} break;

        case MUSIC_MAPCHOICE: {
		    filename = "DUNE16.XMI";
		    musicNum = 7;
		} break;

		case MUSIC_MEANWHILE: {
		    filename = "DUNE16.XMI";
		    musicNum = 8;
		} break;

        case MUSIC_FINALE_H: {
		    filename = "DUNE19.XMI";
		    musicNum = 4;
		} break;

        case MUSIC_FINALE_A: {
		    filename = "DUNE19.XMI";
		    musicNum = 2;
		} break;

        case MUSIC_FINALE_O: {
		    filename = "DUNE19.XMI";
		    musicNum = 3;
		} break;

		case MUSIC_RANDOM:
		default: {

            switch(getRandomInt(0, 14)) {
                // attack
                case 0:     filename = "DUNE10.XMI";    musicNum = 7;   break;
                case 1:     filename = "DUNE11.XMI";    musicNum = 7;   break;
                case 2:     filename = "DUNE12.XMI";    musicNum = 7;   break;
                case 3:     filename = "DUNE13.XMI";    musicNum = 7;   break;
                case 4:     filename = "DUNE14.XMI";    musicNum = 7;   break;
                case 5:     filename = "DUNE15.XMI";    musicNum = 7;   break;

                // peace
                case 6:     filename = "DUNE1.XMI";     musicNum = 6;   break;
                case 7:     filename = "DUNE2.XMI";     musicNum = 6;   break;
                case 8:     filename = "DUNE3.XMI";     musicNum = 6;   break;
                case 9:     filename = "DUNE4.XMI";     musicNum = 6;   break;
                case 10:    filename = "DUNE5.XMI";     musicNum = 6;   break;
                case 11:    filename = "DUNE6.XMI";     musicNum = 6;   break;
                case 12:    filename = "DUNE9.XMI";     musicNum = 4;   break;
                case 13:    filename = "DUNE9.XMI";     musicNum = 5;   break;
                case 14:    filename = "DUNE18.XMI";    musicNum = 6;   break;
            }

		} break;
	}

	currentMusicType = musicType;

	if((musicOn == true) && (filename != "")) {
        SDL_RWops* inputrwop = pFileManager->openFile(filename);
        if(inputrwop == NULL) {
            std::cerr << "Cannot open file " << filename << "!" << std::endl;
            return;
        }
        SDLDataSource input(inputrwop,1);

        std::string tmpFilename = getTmpFileName();

        SDL_RWops* outputrwop = SDL_RWFromFile(tmpFilename.c_str(),"wb");
        if(outputrwop == NULL) {
            std::cerr << "Cannot open file " << tmpFilename << "!" << std::endl;
            return;
        }
        SDLDataSource output(outputrwop,1);

        XMIDI myXMIDI(&input, XMIDI_CONVERT_NOCONVERSION);
        myXMIDI.retrieve(musicNum, &output );

        input.close();
        output.close();

        Mix_HaltMusic();
		if(music != NULL) {
			Mix_FreeMusic(music);
			music = NULL;
		}

		music = Mix_LoadMUS(tmpFilename.c_str());
		if(music != NULL) {
			printf("Now playing %s!\n", tmpFilename.c_str());
			Mix_PlayMusic(music, -1);
		} else {
			printf("Unable to play %s: %s!\n", filename.c_str(), Mix_GetError());
		}

	}
}
Exemple #25
0
int main(int argc, char *argv[])
{
	
	ShaderProgram program = setup();
	Mix_Music *music;
	music = Mix_LoadMUS("Dream Land.mp3");
	Mix_FadeInMusic(music, -1, 1000);
	Mix_Chunk *someSound;
	someSound = Mix_LoadWAV("Shell Hit 2.wav");
	Mix_Chunk *someSound2;
	someSound2 = Mix_LoadWAV("Bumper Hit.wav");
	Mix_Chunk *cheer;
	cheer = Mix_LoadWAV("Crowd Cheering.wav");
	Matrix paddle_left_matrix;
	Matrix paddle_right_matrix;
	Matrix ball_matrix;
	Matrix view_matrix;
	Matrix projection_matrix;

	GLuint chartreuse_texture_ID = load_texture_rgb("purple-suede.jpg");

	projection_matrix.setOrthoProjection(-3.55f, 3.55f, -2.0f, 2.0f, -1.0f, 1.0f);

	SDL_Event event;
	bool done = false;
	bool game_started = false;

	float lastFrameTicks = 0.0f;

	Paddle paddle_left(-3.5f, -3.4f, 0.5f, -0.5f);
	Paddle paddle_right(3.4f, 3.5f, 0.5f, -0.5f);
	Ball ball(0.0f, 0.0f, 0.05f, 0.0025f, (float)rand(), (float)rand());
	
	while (!done)
	{
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

		//Controls for the game
		while (SDL_PollEvent(&event))
		{
			if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE)
				done = true;
			if (event.type == SDL_KEYDOWN)
			{
				// left paddle
				if (event.key.keysym.scancode == SDL_SCANCODE_W)
				{
					if (paddle_left.top < 2.0f){
						paddle_left.top += 0.3f;
						paddle_left.bottom += 0.3f;
						paddle_left_matrix.Translate(0.0f, 0.3f, 0.0f);
					}
				}
				if (event.key.keysym.scancode == SDL_SCANCODE_S)
				{
					if (paddle_left.bottom > -2.0f){
						paddle_left.top -= 0.3f;
						paddle_left.bottom -= 0.3f;
						paddle_left_matrix.Translate(0.0f, -0.3f, 0.0f);
					}
				}

				// right paddle
				if (event.key.keysym.scancode == SDL_SCANCODE_UP)
				{
					if (paddle_right.top < 2.0f){
						paddle_right.top += 0.3f;
						paddle_right.bottom += 0.3f;
						paddle_right_matrix.Translate(0.0f, 0.3f, 0.0f);
					}
				}
				if (event.key.keysym.scancode == SDL_SCANCODE_DOWN)
				{
					if (paddle_right.bottom > -2.0f){
						paddle_right.top -= 0.3f;
						paddle_right.bottom -= 0.3f;
						paddle_right_matrix.Translate(0.0f, -0.3f, 0.0f);
					}
				}

				if (event.key.keysym.scancode == SDL_SCANCODE_SPACE || event.key.keysym.scancode == SDL_SCANCODE_RETURN)
				{
					if (!game_started)
						game_started = true;
				}
			}
		}
		float ticks = (float)SDL_GetTicks() / 1000.0f;
		float elapsed = ticks - lastFrameTicks;
		lastFrameTicks = ticks;
		glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT);

		program.setModelMatrix(paddle_left_matrix);
		program.setViewMatrix(view_matrix);
		program.setProjectionMatrix(projection_matrix);

		glUseProgram(program.programID);

		float texture_coords[] = { 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f }; // global texture coordinates

		// left paddle
		float paddle_left_coords[] = { -3.5f, -0.5f, -3.4f, -0.5f, -3.4f, 0.5f, -3.4f, 0.5f, -3.5f, 0.5f, -3.5f, -0.5f };
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, paddle_left_coords);
		glEnableVertexAttribArray(program.positionAttribute);
		glDrawArrays(GL_TRIANGLES, 0, 6);

		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texture_coords);
		glEnableVertexAttribArray(program.texCoordAttribute);
		glBindTexture(GL_TEXTURE_2D, chartreuse_texture_ID);

		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);

		// right paddle
		program.setModelMatrix(paddle_right_matrix);
		float paddle_right_coords[] = { 3.4f, -0.5f, 3.5f, -0.5f, 3.5f, 0.5f, 3.5f, 0.5f, 3.4f, 0.5f, 3.4f, -0.5f };
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, paddle_right_coords);
		glEnableVertexAttribArray(program.positionAttribute);
		glDrawArrays(GL_TRIANGLES, 0, 6);

		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texture_coords);
		glEnableVertexAttribArray(program.texCoordAttribute);
		glBindTexture(GL_TEXTURE_2D, chartreuse_texture_ID);

		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);

		// ball
		program.setModelMatrix(ball_matrix);
		float ball_coords[] = { -0.1f, -0.1f, 0.1f, -0.1f, 0.1f, 0.1f, 0.1f, 0.1f, -0.1f, 0.1f, -0.1f, -0.1f };
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, ball_coords);
		glEnableVertexAttribArray(program.positionAttribute);
		glDrawArrays(GL_TRIANGLES, 0, 6);

		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texture_coords);
		glEnableVertexAttribArray(program.texCoordAttribute);
		glBindTexture(GL_TEXTURE_2D, chartreuse_texture_ID);

		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);


		if (game_started)
		{
			//Mix_Chunk *start;
			//start = Mix_LoadWAV("Start.wav");
			//Mix_PlayChannel(-1, start, 0);
			

			// right wins
			if (ball.position_x - 0.1f <= paddle_left.left)
			{
				
				Mix_PlayChannel(-1, cheer, 0);
				
				game_started = false;
				ball_matrix.Translate(-ball.position_x, -ball.position_y, 0.0f);
				ball.position_x = 0.0f; // for some reason reset() doesn't work :-(
				ball.position_y = 0.0f;
				ball.direction_x = (float)rand() / (float)RAND_MAX;
				ball.direction_y = (float)rand() / (float)RAND_MAX;
				ball.speed = 0.0009f;
				std::cout << "Right player wins!\n"; 

			}

			// left wins
			else if (ball.position_x + 0.1f >= paddle_right.right)
			{


				
				game_started = false;
				ball_matrix.Translate(-ball.position_x, -ball.position_y, 0.0f);
				ball.position_x = 0.0f;
				ball.position_y = 0.0f;
				ball.direction_x = (float)rand() / (float)RAND_MAX;
				ball.direction_y = (float)rand() / (float)RAND_MAX;
				ball.speed = 0.0009f;
				if (ball.skip > 0)
				{
					Mix_PlayChannel(-1, cheer, 0);
					std::cout << "Left player wins!\n";
				}
				ball.skip++;
			}

			// hits top or bottom of screen
			else if (ball.position_y + 0.1f >= 2.0f || ball.position_y - 0.1f <= -2.0f)
			{
				
				Mix_PlayChannel(-1, someSound, 0);
				ball.direction_y *= -1;
				if (ball.speed < ball.max_speed)
				{
					ball.speed += ball.acceleration;
				}
				ball.move();
				ball_matrix.Translate(ball.speed * ball.direction_x, ball.speed * ball.direction_y, 0.0f);
			}

			// hits a paddle
			else if ((ball.position_x - 0.1f <= paddle_left.right && ball.position_y - 0.1f <= paddle_left.top && ball.position_y + 0.1f >= paddle_left.bottom) ||
				(ball.position_x + 0.1f >= paddle_right.left && ball.position_y - 0.1f <= paddle_right.top && ball.position_y + 0.1f >= paddle_right.bottom))
			{
				
				Mix_PlayChannel(-1, someSound2, 0);
				ball.direction_x *= -1;
				ball.speed += ball.acceleration;
				ball.move();
				ball_matrix.Translate((ball.speed * ball.direction_x), (ball.speed * ball.direction_y), 0.0f);
			}

			// general movement
			else
			{
				ball.move();
				ball_matrix.Translate((ball.speed * ball.direction_x), (ball.speed * ball.direction_y), 0.0f);
			}


		}
		
		
		SDL_GL_SwapWindow(displayWindow);
	}

	Mix_FreeChunk(someSound);
	Mix_FreeChunk(someSound2);
	Mix_FreeChunk(cheer);

	Mix_FreeMusic(music);
	SDL_Quit();
	return 0;
}
Exemple #26
0
int main(int argc, char* argv[]) {
    //initialize and loading variables
    char *bgmm[11] = { "l1.mp3", "l2.mp3", "l3.mp3", "l4.mp3", "l5.mp3", "l6.mp3", "l7.mp3", "l8.mp3", "l9.mp3", "l10.mp3", "l11.mp3" };
    char *bv[11] = { "can we live together.wav",
        "can't you just relax do you even remember.wav",
        "chage is good for you.wav",
        "grace and integrity are what define us.wav",
        "how do thrive and grow under pressure.wav",
        "i don't want you to keep going.wav",
        "i know sometimes it feels like you have no controle",
        "i want to help you but you need to let me.wav",
        "is there another way.wav",
        "once an action is done it cannot be undone.wav",
        "push any further and yu will  break.wav" };
    SDL_Color color;
    const point center = { 220.0, 350.0 };
    int currenttick, score=0;
    short circleradius = 44,musicselect=0;
    boolean mainmenu = yes;
    double theta = 0.0,speed=0.09;
    //Uint8 alpha;
    SDL_Renderer *rendertarget = NULL;
    
    SDL_Rect rectangle1 = { 320, 0, 100, 20 }, rectangle2 = { 230, rectangle1.y-80, 100, 20 };
    SDL_Rect littlerectangle1 = { 310, rectangle1.y - 165, 50, 20 };
    SDL_Rect cube1 = { 300, rectangle1.y - 270, 40, 40 }, cube2 = { 310, cube1.y - 90, 40, 40 }, cube3 = { 305, cube2.y - 90, 40, 40 };
    
    SDL_Rect redballposition = { center.x + circleradius*sin(theta), center.y + circleradius*cos(theta), 25, 25 };
    SDL_Rect blueballposition = { center.x - circleradius*sin(theta), center.y - circleradius*cos(theta), 25, 25 };
    
    const Uint8 *keystate;
    SDL_Window *window = NULL;
    SDL_Texture *redball = NULL, *blueball = NULL, *box = NULL; //gametexture
    
    // Initialize SDL2
    SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO);
    Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 2560);
    Mix_Music *bgm = Mix_LoadMUS("l1.mp3");
    
    Mix_Chunk *voice = Mix_LoadWAV("trust your instincts.wav"), *hitsound = Mix_LoadWAV("Samples/3816133910831170.wav");
    Mix_PlayChannel(2,voice,0);
    Mix_PlayMusic(bgm, -1);
    
    
    
    // Create an application window with the following settings:
    window = SDL_CreateWindow("An SDL2 window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 440, 480, SDL_WINDOW_SHOWN  );
    
    rendertarget = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    box = loadTexture("box.png", rendertarget);
    
    redball = loadTexture("redball.png", rendertarget);
    blueball = loadTexture("bleuball.png", rendertarget);
    
    
    //SDL_SetRenderDrawColor(rendertarget, 0x23, 0x23, 0x23, 0x23);
    SDL_SetRenderDrawColor(rendertarget, 0x99, 0x99, 0xF8, 0x23);
    color.r = 0x99;
    color.g = 0x99;
    color.b = 0xF8;
    color.a = 0x23;
    option select = exitgame;
    //gameloop
    
    boolean gamerunning = yes, programruns = yes;
    SDL_Event e;
    
    while (programruns == yes){
        while (gamerunning == yes && select == startgame){
            
            
            while (SDL_PollEvent(&e)) {
                if (e.type == SDL_QUIT)
                    gamerunning = no;
            };
            srand(time(0));
            
            currenttick = SDL_GetTicks();
            if (e.key.keysym.scancode == SDL_SCANCODE_ESCAPE){
                SDL_RenderClear(rendertarget);
                SDL_RenderPresent(rendertarget);
                //SDL_RenderCopy(rendertarget, gameTitle, NULL, &Gametitleposition);
                //update(gameTitle, Gametitleposition);
                
                SDL_RenderPresent(rendertarget);
                mainmenu = yes;
                break;
                //code to stop game and get back to menu
            }
            keystate = SDL_GetKeyboardState(NULL);
            
            if (keystate[SDL_SCANCODE_LEFT]) {
                theta += speed;
                redballposition.x = center.x + circleradius*sin(theta);
                redballposition.y = center.y + circleradius*cos(theta);
                blueballposition.x = center.x - circleradius*sin(theta);
                blueballposition.y = center.y - circleradius*cos(theta);
            }
            else if (keystate[SDL_SCANCODE_RIGHT]){
                
                theta -= speed;
                redballposition.x = center.x + circleradius*sin(theta);
                redballposition.y = center.y + circleradius*cos(theta);
                blueballposition.x = center.x - circleradius*sin(theta);
                blueballposition.y = center.y - circleradius*cos(theta);
                
            }
            else if (keystate[SDL_SCANCODE_UP]){
                
                
                circleradius += 2;
                redballposition.x = center.x + circleradius*sin(theta);
                redballposition.y = center.y + circleradius*cos(theta);
                blueballposition.x = center.x - circleradius*sin(theta);
                blueballposition.y = center.y - circleradius*cos(theta);
            }
            else if (keystate[SDL_SCANCODE_DOWN]){
                
                circleradius -= 2;
                redballposition.x = center.x + circleradius*sin(theta);
                redballposition.y = center.y + circleradius*cos(theta);
                blueballposition.x = center.x - circleradius*sin(theta);
                blueballposition.y = center.y - circleradius*cos(theta);
            }
            movebox(rectangle1);
            srand(currenttick);
            movebox(rectangle2);
            
            srand(currenttick);
            movebox(littlerectangle1);
            srand(currenttick);
            movebox(cube1);
            srand(currenttick);
            movebox(cube2);
            srand(currenttick);
            movebox(cube3);
            SDL_RenderClear(rendertarget);
            update(redball, redballposition);
            update(blueball, blueballposition);
            update(box, rectangle1);
            update(box, rectangle2);
            update(box, littlerectangle1);
            update(box, cube1);
            update(box, cube2);
            update(box, cube3);
            
            SDL_RenderPresent(rendertarget);
            
            
            
            
            if (aBallhit(rectangle1) || aBallhit(rectangle2) || aBallhit(littlerectangle1) || aBallhit(cube1) || aBallhit(cube2) || aBallhit(cube3)){
                
                Mix_PlayChannel(1, hitsound, 0);
                //reinitialize Game
                
                //rectangle1 = { 220, 0, 100, 20 };
                rectangle1.x= 220;
                rectangle1.y= 0;
                rectangle1.w= 100;
                rectangle1.h= 20;
                //rectangle2 = { 130, rectangle1.y - 80, 100, 20 };
                rectangle2.x= 130;
                rectangle2.y= rectangle1.y - 80;
                rectangle2.w= 100;
                rectangle2.h= 20;
                //littlerectangle1 = { 210, rectangle1.y - 165, 50, 20 };
                littlerectangle1.x= 210;
                littlerectangle1.y= rectangle1.y - 165;
                littlerectangle1.w= 50;
                littlerectangle1.h= 20;
                //cube1 = { 200, rectangle1.y - 270, 40, 40 };
                cube1.x= 200;
                cube1.y= rectangle1.y - 270;
                cube1.w= 40;
                cube1.h= 40;
                //cube2 = { 210, cube1.y - 90, 40, 40 };
                cube2.x= 210;
                cube2.y= cube1.y - 90;
                cube2.w= 40;
                cube2.h= 40;
                //cube3 = { 205, cube2.y - 90, 40, 40 };
                cube3.x= 205;
                cube3.y= cube2.y - 90;
                cube3.w= 40;
                cube3.h= 40;
                
                
                //redballposition = { center.x + circleradius*sin(theta), center.y + circleradius*cos(theta), 25, 25 };
                redballposition.x= center.x + circleradius*sin(theta);
                redballposition.y= center.y + circleradius*cos(theta);
                redballposition.w= 25;
                redballposition.h= 25;
                //blueballposition = { center.x - circleradius*sin(theta), center.y - circleradius*cos(theta), 25, 25 };
                blueballposition.x=  center.x - circleradius*sin(theta);
                blueballposition.y= center.y - circleradius*cos(theta);
                blueballposition.w= 25;
                blueballposition.h= 25;
                
                circleradius = 44;
                gamerunning = yes;
                mainmenu = yes;
                printf("\n your score is: %d", score);
                score = 0;
                Mix_HaltMusic();
                Mix_FreeMusic(bgm);
                if (musicselect == 10)
                    musicselect = 0;
                else
                    musicselect += 1;
                
                bgm = Mix_LoadMUS(bgmm[musicselect]);
                voice = Mix_LoadWAV(bv[musicselect]);
                Mix_PlayMusic(bgm,-1);
                Mix_PlayChannel(2, voice, 0);
                srand(currenttick);
                
                color.b = rand(); srand(currenttick*100);
                color.a = rand(); srand(currenttick*1000);
                color.g = rand(); srand(currenttick*10000);
                color.r = rand();
                
                SDL_SetRenderDrawColor(rendertarget, color.r, color.g, color.b, color.a);
                
                break;
                
                //insert code when collision happens
                
            }
            if (musicselect == 6 ){
                color.b = rand(); srand(currenttick * 100);
                color.r = rand(); srand(currenttick * 1000);
                color.g = rand();
                SDL_SetTextureColorMod(box, color.r, color.g, color.b);
            }
            else if (musicselect == 7){
                //SDL_SetTextureColorMod(box, 0, 0, 0);
            }
            //if (rectangle1.y >= 200){
            //	alpha = 20;
            //	SDL_SetTextureAlphaMod(box,alpha);
            //}
            //else
            //	alpha=100;
            
            if( (notout(redballposition,blueballposition))&&(rectangle1.y == 400 || rectangle2.y == 400 || littlerectangle1.y == 400 || cube1.y == 400 || cube2.y == 400 || cube3.y == 400)){
                score += 1;
                //	printf("\n score = %d", score);
                
                
            }
            
            if (SDL_GetTicks() - currenttick<1000.0 / 60)/*60 FPS*/
            {
                SDL_Delay(1000 / 60 - SDL_GetTicks() + currenttick);
            }
        }
        runmenu(&programruns,&mainmenu,rendertarget,&select);
    }
    // Close and destroy the window
    SDL_DestroyWindow(window);
    
    // Clean up
    SDL_Quit();
    IMG_Quit();
    Mix_Quit();
    SDL_DestroyTexture(redball);
    SDL_DestroyTexture(blueball);
    SDL_DestroyTexture(box);
    
    SDL_DestroyRenderer(rendertarget);
    
    redball = NULL;
    blueball = NULL;
    box = NULL;
    rendertarget = NULL;
    return 0;
}
Exemple #27
0
/* ------------------------------------------- */
int main(int argc, char *argv[]){

 Uint8* keys;
 char mes[100];

 if ( SDL_Init(SDL_INIT_AUDIO|SDL_INIT_VIDEO) < 0 ){
   printf("Unable to init SDL: %s\n", SDL_GetError());
   exit(1);
 }

 atexit(SDL_Quit);

if(Mix_OpenAudio(44100, AUDIO_S16SYS, 2, 2048) < 0)
  {
    printf("Warning: Couldn't set 44100 Hz 16-bit audio\n- Reason: %s\n",
							SDL_GetError());
  }
    music = Mix_LoadMUS("(sblu)moon6.xm");



 SDL_WM_SetCaption("arcanoid","arcanoid");
 SDL_WM_SetIcon(SDL_LoadBMP("icon.bmp"), NULL);


 screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE);
 if ( screen == NULL ){
   printf("Unable to set 640x480 video: %s\n", SDL_GetError());
   exit(1);
 }

 InitImages();
 InitGame();


CreateThread(NULL, 0, GoBall , (LPVOID)0, NULL, NULL);

DrawScene();
 int done=0;
 while(done == 0)
 {

   SDL_Event event;

   while ( SDL_PollEvent(&event) )
   {
     if ( event.type == SDL_QUIT ){ done = 1; }
     if ( event.type == SDL_KEYDOWN )
     {
       if ( event.key.keysym.sym == SDLK_ESCAPE ){ done = 1; }
     }
   }

    if (NewGame)
    {
        bool t= false;
        if ((Win1!=5)&&(Win2!=5))
        {
            InitGame();
            CreateThread(NULL, 0, GoBall , (LPVOID)0, NULL, NULL);
        }

        if (Win1==5)
        {
            strcpy(mes, "The first one wins!\nDo you want to play again?");
            t= true;
        } else
        if (Win2==5)
        {
            strcpy(mes, "The second one wins!\nDo you want to play again?");
            t=true;
        }
        if (t)
        if (MessageBoxA(NULL, mes, "Game Over", MB_YESNO)==IDYES)
        {
            InitGame();
            CreateThread(NULL, 0, GoBall , (LPVOID)0, NULL, NULL);
        } else
            break;

    }


   keys = SDL_GetKeyState(NULL);

   if(keys[SDLK_UP])
   {
       if (ypos-3>=VG)
        ypos -= 3;
   }
   if(keys[SDLK_DOWN])
   {
       if (ypos+3<=480-85)
        ypos += 3;
   }


   if(keys[SDLK_w])
   {
       if (ypos1-3>=VG)
        ypos1 -= 3;
   }

    if(keys[SDLK_s])
    {
        if (ypos1+3<=480-85)
         ypos1 += 3;
    }


    while (redraw)
    {

    }
    DrawScene();
 }
 CloseThread= true;
SDL_Quit();
 return 0;

}
static void *I_SDL_RegisterSong(void *data, int len)
{
    char *filename;
    Mix_Music *music;

    if (!music_initialized)
    {
        return NULL;
    }

    // MUS files begin with "MUS"
    // Reject anything which doesnt have this signature

    filename = M_TempFile("doom"); // [crispy] generic filename

    // [crispy] Reverse Choco's logic from "if (MIDI)" to "if (not MUS)"
    // MUS is the only format that requires conversion,
    // let SDL_Mixer figure out the others
/*
    if (IsMid(data, len) && len < MAXMIDLENGTH)
*/
    if (len < 4 || memcmp(data, "MUS\x1a", 4)) // [crispy] MUS_HEADER_MAGIC
    {
        M_WriteFile(filename, data, len);
    }
    else
    {
	// Assume a MUS file and try to convert

        ConvertMus(data, len, filename);
    }

    // Load the MIDI. In an ideal world we'd be using Mix_LoadMUS_RW()
    // by now, but Mix_SetMusicCMD() only works with Mix_LoadMUS(), so
    // we have to generate a temporary file.

#if defined(_WIN32)
    // [AM] If we do not have an external music command defined, play
    //      music with the MIDI server.
    if (midi_server_initialized)
    {
        music = NULL;
        if (!I_MidiPipe_RegisterSong(filename))
        {
            fprintf(stderr, "Error loading midi: %s\n",
                "Could not communicate with midiproc.");
        }
    }
    else
#endif
    {
        music = Mix_LoadMUS(filename);
        if (music == NULL)
        {
            // Failed to load
            fprintf(stderr, "Error loading midi: %s\n", Mix_GetError());
        }

        // Remove the temporary MIDI file; however, when using an external
        // MIDI program we can't delete the file. Otherwise, the program
        // won't find the file to play. This means we leave a mess on
        // disk :(

        if (strlen(snd_musiccmd) == 0)
        {
            remove(filename);
        }
    }

    free(filename);

    return music;
}
Exemple #29
0
Bgm::Bgm(const char* filename)
{
	m_Music = Mix_LoadMUS(filename);
	if (m_Music == NULL) printf("Failed to load music! Mix_GetError: %s\n", Mix_GetError());
}
Exemple #30
-1
int CMidi::PlaySong (char* pszSong, char* melodicBank, char* drumBank, int bLoop, int bD1Song)
{
#if (defined (_WIN32) || USE_SDL_MIXER)
	int	bCustom;

PrintLog ("DigiPlayMidiSong (%s)\n", pszSong);
audio.StopCurrentSong ();
if (!(pszSong && *pszSong))
	return 0;
if (m_nVolume < 1)
	return 0;

bCustom = ((strstr (pszSong, ".mp3") != NULL) || (strstr (pszSong, ".ogg") != NULL));
if (bCustom) {
	if (audio.Format () != AUDIO_S16LSB) {
		audio.Shutdown ();
		audio.Setup (1, AUDIO_S16LSB);
		}
	}
else if (!(m_hmp = hmp_open (pszSong, bD1Song)))
	return 0;

#	if USE_SDL_MIXER
if (gameOpts->sound.bUseSDLMixer) {
	char	fnSong [FILENAME_LEN], *pfnSong;

	if (bCustom) {
		pfnSong = pszSong;
		if (strstr (pszSong, ".mp3") && !songManager.MP3 ()) {
			audio.Shutdown ();
			songManager.SetMP3 (1);
			audio.Setup (1);
			}
		}
	else {
		if (!strstr (pszSong, ".mp3") && songManager.MP3 ()) {
			audio.Shutdown ();
			songManager.SetMP3 (0);
			audio.Setup (1);
			}
#if defined (_WIN32)
		sprintf (fnSong, "%s/d2x-temp.mid", *gameFolders.szCacheDir ? gameFolders.szCacheDir : gameFolders.szHomeDir);
#else
		sprintf (fnSong, "%s/d2x-temp.mid", *gameFolders.szCacheDir ? gameFolders.szCacheDir : gameFolders.szHomeDir);
#endif
		if (!hmp_to_midi (m_hmp, fnSong)) {
			PrintLog ("SDL_mixer failed to load %s\n(%s)\n", fnSong, Mix_GetError ());
			return 0;
			}
		pfnSong = fnSong;
		}
	if (!(m_music = Mix_LoadMUS (pfnSong))) {
		PrintLog ("SDL_mixer failed to load %s\n(%s)\n", fnSong, Mix_GetError ());
		return 0;
		}
	if (-1 == Mix_FadeInMusicPos (m_music, bLoop ? -1 : 1, songManager.Pos () ? 1000 : 1500, (double) songManager.Pos () / 1000.0)) {
		PrintLog ("SDL_mixer cannot play %s\n(%s)\n", pszSong, Mix_GetError ());
		songManager.SetPos (0);
		return 0;
		}
	PrintLog ("SDL_mixer playing %s\n", pszSong);
	if (songManager.Pos ())
		songManager.SetPos (0);
	else
		songManager.SetStart (SDL_GetTicks ());
	
	songManager.SetPlaying (1);
	SetVolume (m_nVolume);
	return 1;
	}
#	endif
#	if defined (_WIN32)
if (bCustom) {
	PrintLog ("Cannot play %s - enable SDL_mixer\n", pszSong);
	return 0;
	}
hmp_play (m_hmp, bLoop);
songManager.SetPlaying (1);
SetVolume (m_nVolume);
#	endif
#endif
return 1;
}