Beispiel #1
0
void SoundManager::PlayMusic(int num, bool loop)
{
	DestroyMusic();
	if(num==-1)
		return;
	else if(num==0)
		music = al_load_audio_stream("music/menu.ogg", 4, 2048);
	else if(num==1)
		music = al_load_audio_stream("music/level1.ogg", 4, 2048);

	if(music==NULL)
	{
		al_show_native_message_box(DisplayManager::GetInstance().GetDisplay(),
			"Error!", "SoundManager", "Couldn't load music", "ok sok", ALLEGRO_MESSAGEBOX_ERROR);
		return;
	}

	if(music==NULL)
		return;

	al_set_audio_stream_loop_secs(music, .0f, al_get_audio_stream_length_secs(music));
	if(loop)
		al_set_audio_stream_playmode(music, ALLEGRO_PLAYMODE_LOOP);
	else
		al_set_audio_stream_playmode(music, ALLEGRO_PLAYMODE_ONCE);
	al_attach_audio_stream_to_mixer(music, mixer);
	al_attach_mixer_to_voice(mixer,voice);

}
Beispiel #2
0
void Audio::PlayMusic( std::string Filename, bool Loop )
{
	if( audioVoice == 0 || audioMixer == 0 )
	{
		return;
	}

	if( musicStream != nullptr )
	{
		StopMusic();
	}

	// Only play if Music is set
	if( FRAMEWORK->Settings->GetQuickBooleanValue( "Audio.Music", true ) )
	{

#ifdef WRITE_LOG
		fprintf( FRAMEWORK->LogFile, "Framework: Start audio file %s\n", Filename.c_str() );
#endif
		musicStream = al_load_audio_stream( Filename.c_str(), 4, 2048 );
		if( musicStream != nullptr )
		{
			al_attach_audio_stream_to_mixer( musicStream, audioMixer );
			al_set_audio_stream_playmode( musicStream, ( Loop ? ALLEGRO_PLAYMODE_LOOP : ALLEGRO_PLAYMODE_ONCE ) );
			FRAMEWORK->RegisterEventSource( al_get_audio_stream_event_source( musicStream ) );
			al_set_audio_stream_playing( musicStream, true );
		} else {
#ifdef WRITE_LOG
			fprintf( FRAMEWORK->LogFile, "Framework: Could not load music '%s'\n", Filename.c_str() );
#endif
		}

	}
}
Beispiel #3
0
void initMenu(void)
{
    timer = al_create_timer(1.0 / 60);
    if (!timer)
        abort_game("Failed to create timer");

    background = al_load_bitmap(MENU_BACKGROUND_PATH);
    if (!background)
        abort_game("Failed to load background");

    eventMenuQueue = al_create_event_queue();
    if (!eventMenuQueue)
        abort_game("Failed to create event queue");

    font = al_load_ttf_font("font.ttf", 48, 0);
    if (!font)
        abort_game("failed to load font");

    music = al_load_audio_stream("musica.ogg", 4, 1024);
    if (!music)
        abort_game("failed to load audio");

    al_register_event_source(eventMenuQueue, al_get_keyboard_event_source());
    al_register_event_source(eventMenuQueue, al_get_timer_event_source(timer));

    menuDone = false;
    gState = Menu;
}
Beispiel #4
0
ALLEGRO_AUDIO_STREAM* SoundManager::GetMusic(std::string Filename)
{
	SoundCache* fc;

	if( !MusicCached.empty() )
	{
		for( std::list<SoundCache*>::iterator i = MusicCached.begin(); i != MusicCached.end(); i++ )
		{
			fc = (*i);
			if( fc->Path->compare( Filename ) == 0 )
			{
				fc->LastAccess = al_get_time();
				return (ALLEGRO_AUDIO_STREAM*)fc->Reference;
			}
		}
	}

	fc = (SoundCache*)malloc( sizeof(SoundCache) );
	fc->Path = new std::string(Filename);
	fc->Reference = al_load_audio_stream( Filename.c_str(), 4, 2048 );
	fc->LastAccess = al_get_time();
	MusicCached.push_front( fc );

	return (ALLEGRO_AUDIO_STREAM*)fc->Reference;
}
Beispiel #5
0
int main(int argc, char * argv[])
{
   ALLEGRO_CONFIG *config;
   ALLEGRO_EVENT event;
   unsigned buffer_count;
   unsigned samples;
   const char *s;

   initialize();

   if (argc < 2) {
      log_printf("This example needs to be run from the command line.\nUsage: %s {audio_files}\n", argv[0]);
      goto done;
   }

   buffer_count = 0;
   samples = 0;
   config = al_load_config_file("ex_stream_seek.cfg");
   if (config) {
      if ((s = al_get_config_value(config, "", "buffer_count"))) {
         buffer_count = atoi(s);
      }
      if ((s = al_get_config_value(config, "", "samples"))) {
         samples = atoi(s);
      }
      al_destroy_config(config);
   }
   if (buffer_count == 0) {
      buffer_count = 4;
   }
   if (samples == 0) {
      samples = 1024;
   }

   stream_filename = argv[1];
   music_stream = al_load_audio_stream(stream_filename, buffer_count, samples);
   if (!music_stream) {
      abort_example("Stream error!\n");
   }

   loop_start = 0.0;
   loop_end = al_get_audio_stream_length_secs(music_stream);
   al_set_audio_stream_loop_secs(music_stream, loop_start, loop_end);

   al_set_audio_stream_playmode(music_stream, ALLEGRO_PLAYMODE_LOOP);
   al_attach_audio_stream_to_mixer(music_stream, al_get_default_mixer());
   al_start_timer(timer);

   while (!exiting) {
      al_wait_for_event(queue, &event);
      event_handler(&event);
   }

done:
   myexit();
   al_destroy_display(display);
   close_log(true);
   return 0;
}
bool GameLogic::LoadAssets() {

    Bitmap.Logo = al_load_bitmap("assets/images/daklutz.png");
    Bitmap.Title = al_load_bitmap("assets/images/Bitmap.Title.png");
    if(!Bitmap.Title || !Bitmap.Logo) {
        fprintf(stderr, "Failed to load image files!\n");
        return false;
    }
	if(Debug) { fprintf(stderr, "Bitmaps loaded.\n"); }

	// actually load the font, I loaded the same font at different sizes.
    Font.Small = al_load_font("assets/fonts/Geo-Regular.ttf", 24, 0);
    Font.Medium = al_load_font("assets/fonts/Geo-Regular.ttf", 38, 0);
    Font.Big = al_load_font("assets/fonts/Geo-Regular.ttf", 70, 0);
	if(!Font.Small || !Font.Medium || !Font.Big) {
		fprintf(stderr, "Failed to load fonts!\n");
        return false;
    }

	if (!al_reserve_samples(2)) {
        fprintf(stderr, "Could not reserve samples!\n");
        return false;
    }
    if(Debug) { fprintf(stderr, "Samples reserved.\n"); }

	Sound.HitWall = al_load_sample("assets/sounds/wall_collision.ogg");
    Sound.HitPaddle = al_load_sample("assets/sounds/paddle_collision.ogg");
    Sound.BackgroundMusic = al_load_audio_stream("assets/sounds/Sound.BackgroundMusic-tech.ogg", 4, 2048);
    if (!Sound.HitWall || !Sound.HitPaddle || !Sound.BackgroundMusic) {
        fprintf(stderr, "Failed to load sound files!\n");
        return false;
    }
	if(Debug) { fprintf(stderr, "Sound files loaded.\n"); }

	if(!al_attach_audio_stream_to_mixer(Sound.BackgroundMusic, Mixer) ) {
        fprintf(stderr, "Failed to attach stream to default Mixer!\n");
        return 1;
    }
    if(Debug) { fprintf(stderr, "Stream attached to Mixer.\n"); }

    if(!al_set_mixer_playing(Mixer, true)) {
        fprintf(stderr, "Failed to play Mixer!\n");
    }
    if(Debug) { fprintf(stderr, "Mixer playing.\n"); }

    if(!al_set_audio_stream_playmode(Sound.BackgroundMusic, ALLEGRO_PLAYMODE_LOOP)) {
        fprintf(stderr, "Failed to loop stream!\n");
    }
    if(Debug) { fprintf(stderr, "Stream is set to loop.\n"); }

    if(!al_set_audio_stream_playing(Sound.BackgroundMusic, true)) {
        fprintf(stderr, "Failed to play stream!\n");
    }
    if(Debug) { fprintf(stderr, "Stream playing.\n"); }


	return true;
}
int main(int argc, char * argv[])
{
   ALLEGRO_CONFIG *config;
   ALLEGRO_EVENT event;
   unsigned buffer_count;
   unsigned samples;
   const char *s;

   if (argc < 2) {
      printf("Usage: ex_stream_seek <filename>\n");
      return -1;
   }

   if (!initialize())
      return 1;

   buffer_count = 0;
   samples = 0;
   config = al_load_config_file("ex_stream_seek.cfg");
   if (config) {
      if ((s = al_get_config_value(config, "", "buffer_count"))) {
         buffer_count = atoi(s);
      }
      if ((s = al_get_config_value(config, "", "samples"))) {
         samples = atoi(s);
      }
      al_destroy_config(config);
   }
   if (buffer_count == 0) {
      buffer_count = 4;
   }
   if (samples == 0) {
      samples = 1024;
   }

   stream_filename = argv[1];
   music_stream = al_load_audio_stream(stream_filename, buffer_count, samples);
   if (!music_stream) {
      printf("Stream error!\n");
      return 1;
   }

   loop_start = 0.0;
   loop_end = al_get_audio_stream_length_secs(music_stream);
   al_set_audio_stream_loop_secs(music_stream, loop_start, loop_end);

   al_set_audio_stream_playmode(music_stream, ALLEGRO_PLAYMODE_LOOP);
   al_attach_audio_stream_to_mixer(music_stream, al_get_default_mixer());
   al_start_timer(timer);

   while (!exiting) {
      al_wait_for_event(queue, &event);
      event_handler(&event);
   }

   myexit();
   return 0;
}
Beispiel #8
0
void playBGM_Stream(const char *str)
{
    if (!str)
        return;
    stream = al_load_audio_stream(str, 2, 1024);
    if (!stream)
        return;
    al_set_audio_stream_playing(stream, true);
    al_set_audio_stream_playmode(stream, ALLEGRO_PLAYMODE_LOOP);
    al_attach_audio_stream_to_mixer(stream, al_get_default_mixer());
}
bool AllegroMusicSample5::Load( const std::string & path )
{
	if ( m_pInstance )
	{
		al_detach_audio_stream( m_pInstance );
		al_destroy_audio_stream( m_pInstance );
	}

	m_pInstance = al_load_audio_stream( path.c_str(), 10, 1024 );
	if ( m_pInstance )
		al_attach_audio_stream_to_mixer( m_pInstance,  ((AllegroSound5&)GetSound()).GetMusicMixer() );

	return ( m_pInstance != 0 );
}
Beispiel #10
0
static int allua_audio_stream_load(lua_State * L)
{
   const char *filename = luaL_checkstring(L, 1);
   int buffer_count = luaL_checkint(L, 2);
   int samples = luaL_checkint(L, 3);

   ALLEGRO_AUDIO_STREAM *stream =
       al_load_audio_stream(filename, buffer_count, samples);
   if (stream)
      allua_pushaudio_stream(L, stream, true);
   else
      lua_pushnil(L);

   return 1;
}
Beispiel #11
0
AudioStream::AudioStream(const char *path, ALLEGRO_PLAYMODE playmode)
{
	// load stream from file
	m_stream = al_load_audio_stream(path, 4, 2048);
	assert(m_stream);

	// create voice for the stream
	m_voice = al_create_voice(44100, al_get_audio_stream_depth(m_stream), ALLEGRO_CHANNEL_CONF_2);


	al_attach_audio_stream_to_voice(m_stream, m_voice);

	this->playmode(playmode);

	//al_detach_voice(m_voice);
	//assert(m_stream != 0);
}
Beispiel #12
0
bool
reload_sound(sound_t* sound)
{
	ALLEGRO_AUDIO_STREAM* new_stream;

	if (!(new_stream = al_load_audio_stream(sound->path, 4, 1024)))
		return false;
	if (sound->stream != NULL) {
		al_set_audio_stream_playing(sound->stream, false);
		al_destroy_audio_stream(sound->stream);
	}
	sound->stream = new_stream;
	al_set_audio_stream_gain(sound->stream, 1.0);
	al_attach_audio_stream_to_mixer(sound->stream, al_get_default_mixer());
	al_set_audio_stream_playing(sound->stream, false);
	return true;
}
Beispiel #13
0
void playMusicOnce(const char *filename)
{

    /* play music only once in background, terminating old music */

    ALLEGRO_PLAYMODE loop = ALLEGRO_PLAYMODE_ONCE;
    al_stop_samples();
    if (music != NULL)
    {
      al_drain_audio_stream(music);
      al_destroy_audio_stream(music);
    }
    music = al_load_audio_stream(filename, 4, 2048);
    al_set_audio_stream_playmode(music, loop);
    al_attach_audio_stream_to_mixer(music, mixer);

}
Beispiel #14
0
void FillPage(struct Game *game, int page) {
	char filename[30] = { };
	sprintf(filename, "intro/%d.flac", page);

	game->intro.audiostream = al_load_audio_stream(GetDataFilePath(filename), 4, 1024);
	al_attach_audio_stream_to_mixer(game->intro.audiostream, game->audio.voice);
	al_set_audio_stream_playing(game->intro.audiostream, false);
	al_set_audio_stream_gain(game->intro.audiostream, 1.75);

	al_set_target_bitmap(game->intro.table);
	float y = 0.2;
	float oldx = -1;
	void draw_text(int page, char* text) {
		float x = 0.45;
		if (page!=oldx) { y=0.2; oldx=page; }
		al_draw_text_with_shadow(game->intro.font, al_map_rgb(255,255,255), game->viewportWidth*x, game->viewportHeight*y, ALLEGRO_ALIGN_LEFT, text);
		y+=0.07;
	}
Beispiel #15
0
bool Letter(struct Game *game, struct TM_Action *action, enum TM_ActionState state) {
	if (state == TM_ACTIONSTATE_INIT) {
		float* f = (float*)malloc(sizeof(float));
		*f = 0;
		ALLEGRO_AUDIO_STREAM** stream = (ALLEGRO_AUDIO_STREAM**)malloc(sizeof(ALLEGRO_AUDIO_STREAM*));
		*stream = al_load_audio_stream(GetDataFilePath(GetLevelFilename(game, "levels/?/letter.flac")), 4, 1024);
		al_attach_audio_stream_to_mixer(*stream, game->audio.voice);
		al_set_audio_stream_playing(*stream, false);
		al_set_audio_stream_gain(*stream, 2.00);
		action->arguments = TM_AddToArgs(action->arguments, (void*)f);
		action->arguments = TM_AddToArgs(action->arguments, (void*)stream);
		action->arguments->next->next = NULL;
	} else if (state == TM_ACTIONSTATE_DESTROY) {
		ALLEGRO_AUDIO_STREAM** stream = (ALLEGRO_AUDIO_STREAM**)action->arguments->next->value;
		al_set_audio_stream_playing(*stream, false);
		al_destroy_audio_stream(*stream);
		free(action->arguments->next->value);
		free(action->arguments->value);
		TM_DestroyArgs(action->arguments);
	} else if (state == TM_ACTIONSTATE_DRAW) {
		float* f = (float*)action->arguments->value;
		al_draw_tinted_bitmap(game->level.letter, al_map_rgba(*f,*f,*f,*f), (game->viewportWidth-al_get_bitmap_width(game->level.letter))/2.0, al_get_bitmap_height(game->level.letter)*-0.05, 0);
		return false;
	} else if (state == TM_ACTIONSTATE_PAUSE) {
		ALLEGRO_AUDIO_STREAM** stream = (ALLEGRO_AUDIO_STREAM**)action->arguments->next->value;
		al_set_audio_stream_playing(*stream, false);
	}	else if ((state == TM_ACTIONSTATE_RESUME) || (state == TM_ACTIONSTATE_START)) {
		ALLEGRO_AUDIO_STREAM** stream = (ALLEGRO_AUDIO_STREAM**)action->arguments->next->value;
		al_set_audio_stream_playing(*stream, true);
	}
	if (state != TM_ACTIONSTATE_RUNNING) return false;

	float* f = (float*)action->arguments->value;
	*f+=5;
	if (*f>255) *f=255;
	al_draw_tinted_bitmap(game->level.letter, al_map_rgba(*f,*f,*f,*f), (game->viewportWidth-al_get_bitmap_width(game->level.letter))/2.0, al_get_bitmap_height(game->level.letter)*-0.05, 0);
	struct ALLEGRO_KEYBOARD_STATE keyboard;
	al_get_keyboard_state(&keyboard);
	// FIXME: do it the proper way
	if (al_key_down(&keyboard, ALLEGRO_KEY_ENTER)) {
		return true;
	}
	return false;
}
bool StreamResource::load(void)
{
   if (!al_is_audio_installed()) {
      debug_message("Skipped loading stream %s\n", filename.c_str());
      return true;
   }

   stream = al_load_audio_stream(filename.c_str(), 4, 1024);
   if (!stream) {
       debug_message("Error creating stream\n");
       return false;
   }

   al_set_audio_stream_playing(stream, false);
   al_set_audio_stream_playmode(stream, ALLEGRO_PLAYMODE_LOOP);
   al_attach_audio_stream_to_mixer(stream, al_get_default_mixer());

   return true;
}
Beispiel #17
0
static bool load(DATA_ENTRY *d, int id, char const *type, char const *path,
   char const *subfolder, char const *name, char const *ext, int size)
{
   static char spath[1024];
   sprintf(spath, "%s/%s/%s.%s", path, subfolder, name, ext);
   printf("Loading %s...\n", spath);
   if (!strcmp(type, "font")) d[id].dat = al_load_font(spath, size, 0);
   if (!strcmp(type, "bitmap")) d[id].dat = al_load_bitmap(spath);
   if (!strcmp(type, "sample")) d[id].dat = al_load_sample(spath);
   if (!strcmp(type, "music")) d[id].dat = al_load_audio_stream(spath, 2, 4096);
   if (d[id].dat == NULL) {
      printf("Failed loading %s.\n", name);
   }
   d[id].type = type;
   d[id].path = strdup(path);
   d[id].subfolder = strdup(subfolder);
   d[id].name = strdup(name);
   d[id].ext = strdup(ext);
   d[id].size = size;
   return d[id].dat != NULL;
}
Beispiel #18
0
void playMusic(const char *filename)
{

    /* play music in background, on loop - unpause if music is already playing */
    if (isMusicPaused())
    {
        unPauseMusic();
        return;
    }

    /* music not playing, start over from beginning */
    ALLEGRO_PLAYMODE loop = ALLEGRO_PLAYMODE_LOOP;
    al_stop_samples();
    if (music != NULL)
    {
      al_drain_audio_stream(music);
      al_destroy_audio_stream(music);
    }
    music = al_load_audio_stream(filename, 4, 2048);
    al_set_audio_stream_playmode(music, loop);
    al_attach_audio_stream_to_mixer(music, mixer);

}
int main(int argc, char **argv)
{
   const char *filename = "../demos/cosmic_protector/data/sfx/title_music.ogg";
   ALLEGRO_VOICE *voice;
   ALLEGRO_MIXER *mixer;
   ALLEGRO_AUDIO_STREAM *stream;

   if (argc > 1) {
      filename = argv[1];
   }

   if (!al_init()) {
      abort_example("Could not init Allegro.\n");
      return 1;
   }

   al_init_primitives_addon();
   al_init_image_addon();
   al_init_acodec_addon();
   
   al_install_keyboard();

   display = al_create_display(640, 480);
   if (!display) {
      abort_example("Could not create display.\n");
      return 1;
   }

   dbuf = al_create_bitmap(640, 480);

   bmp = al_load_bitmap("data/mysha.pcx");
   if (!bmp) {
      abort_example("Could not load data/mysha.pcx\n");
      return 1;
   }

   if (!al_install_audio()) {
      abort_example("Could not init sound.\n");
      return 1;
   }

   voice = al_create_voice(44100, ALLEGRO_AUDIO_DEPTH_INT16,
      ALLEGRO_CHANNEL_CONF_2);
   if (!voice) {
      abort_example("Could not create voice.\n");
      return 1;
   }

   mixer = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32,
      ALLEGRO_CHANNEL_CONF_2);
   if (!mixer) {
      abort_example("Could not create mixer.\n");
      return 1;
   }

   if (!al_attach_mixer_to_voice(mixer, voice)) {
      abort_example("al_attach_mixer_to_voice failed.\n");
      return 1;
   }

   stream = al_load_audio_stream(filename, 4, 2048);
   if (!stream) {
      abort_example("Could not load '%s'\n", filename);
      return 1;
   }

   al_set_audio_stream_playmode(stream, ALLEGRO_PLAYMODE_LOOP);
   al_attach_audio_stream_to_mixer(stream, mixer);

   al_set_mixer_postprocess_callback(mixer, update_meter, NULL);

   main_loop();

   al_destroy_audio_stream(stream);
   al_destroy_mixer(mixer);
   al_destroy_voice(voice);
   al_uninstall_audio();

   al_destroy_bitmap(dbuf);
   al_destroy_bitmap(bmp);

   return 0;
}
stage *initStageWithNumber(int n){
	stage *temp = malloc(sizeof(stage));
    temp -> stageNum = n;
	temp -> stageBackground = NULL;
	temp -> stageAudio = NULL;
	temp -> bossAudio = NULL;
    int randomModifier = rand()%100;

	switch(n){
		case 1:
			temp -> stageBackground = al_load_bitmap("Graphics/BeachSide.png");
			if(!temp -> stageBackground)
				erro("Erro na alocação de stageBackground para stage 1\n");

			temp -> stageAudio = al_load_audio_stream("Sound/BeachSide.ogg", 4, 1024);
			if(!temp -> stageAudio)
				erro("Erro na alocação de stageAudio para stage 1\n");

			temp -> bossAudio = al_load_audio_stream("Sound/Marlingone.ogg", 4, 1024);
			if(!temp -> bossAudio)
				erro("Erro na alocação de bossAudio para stage 1\n");

			al_set_audio_stream_gain(temp -> bossAudio, 1.5);

            temp -> targetKills = 20;
            
            temp -> limitSpawn = 4;
            
			break;

		case 2:
			temp -> stageBackground = al_load_bitmap("Graphics/RuinedVillage.png");
			if(!temp -> stageBackground)
				erro("Erro na alocação de stageBackground para stage 2\n");

			temp -> stageAudio = al_load_audio_stream("Sound/RuinedVillage.ogg", 4, 1024);
			if(!temp -> stageAudio)
				erro("Erro na alocação de stageAudio para stage 2\n");

			temp -> bossAudio = al_load_audio_stream("Sound/Hueda.ogg", 4, 1024);
			if(!temp -> bossAudio)
				erro("Erro na alocação de bossAudio para stage 2\n");

            temp -> targetKills = 40;
            
            temp -> limitSpawn = 5;
            
            randomModifier += 30;
            
			break;

		case 3:
			temp -> stageBackground = al_load_bitmap("Graphics/Macalania.png");
			if(!temp -> stageBackground)
				erro("Erro na alocação de stageBackground para stage 3\n");

			temp -> stageAudio = al_load_audio_stream("Sound/IceLake.ogg", 4, 1024);
			if(!temp -> stageAudio)
				erro("Erro na alocação de stageAudio para stage 3\n");

			temp -> bossAudio = al_load_audio_stream("Sound/Cirno.ogg", 4, 1024);
			if(!temp -> bossAudio)
				erro("Erro na alocação de bossAudio para stage 3\n");

            temp -> targetKills = 70;
            
            temp -> limitSpawn = 6;
            
            randomModifier += 40;
            
			break;

		case 4:
			temp -> stageBackground = al_load_bitmap("Graphics/Drangleic.png");
			if(!temp -> stageBackground)
				erro("Erro na alocação de stageBackground para stage 4\n");

			temp -> stageAudio = al_load_audio_stream("Sound/DrangleicCastle.ogg", 4, 1024);
			if(!temp -> stageAudio)
				erro("Erro na alocação de stageAudio para stage 4\n");

			temp -> bossAudio = al_load_audio_stream("Sound/GuardianDragon.ogg", 4, 1024);
			if(!temp -> bossAudio)
				erro("Erro na alocação de bossAudio para stage 4\n");

            temp -> targetKills = 100;
            
            temp -> limitSpawn = 6;
            
            randomModifier += 80;
            
			break;

		case 5:
			temp -> stageBackground = al_load_bitmap("Graphics/Moria.png");
			if(!temp -> stageBackground)
				erro("Erro na alocação de stageBackground para stage 5\n");

			temp -> stageAudio = al_load_audio_stream("Sound/DwarvenRuins.ogg", 4, 1024);
			if(!temp -> stageAudio)
				erro("Erro na alocação de stageAudio para stage 5\n");

			temp -> bossAudio = al_load_audio_stream("Sound/Balrog.ogg", 4, 1024);
			if(!temp -> bossAudio)
				erro("Erro na alocação de bossAudio para stage 5\n");
            
            temp -> targetKills = 100;
            
            temp -> limitSpawn = 6;
            
            randomModifier += 70;
            
			break;

		case 6:
			//MISSING OCEAN PALACE!!!
			temp -> stageBackground = al_load_bitmap("Graphics/BeachSide.png");
			if(!temp -> stageBackground)
				erro("Erro na alocação de stageBackground para stage 6\n");

			//MISSING OCEAN PALACE HEME!!!
			temp -> stageAudio = al_load_audio_stream("Sound/BeachSide.ogg", 4, 1024);
			if(!temp -> stageAudio)
				erro("Erro na alocação de stageAudio para stage 6\n");

			temp -> bossAudio = al_load_audio_stream("Sound/Lavos.ogg", 4, 1024);
			if(!temp -> bossAudio)
				erro("Erro na alocação de bossAudio para stage 6\n");

            temp -> targetKills = 150;
            
            temp -> limitSpawn = 7;
            
            randomModifier += 60;
            
			break;
	}
    
    
    if(randomModifier > 100){
        temp -> darkPhantom = 30 + n;
        temp -> darkSpawn = rand()% temp -> targetKills + 1;
    }
    else{
        temp -> darkPhantom = 0;
        temp -> darkSpawn = -1;
    }
    //temp -> darkPhantom = 30 + n;
    //temp -> darkSpawn = 1;

    al_set_audio_stream_playmode(temp -> stageAudio, ALLEGRO_PLAYMODE_LOOP);
    al_set_audio_stream_playmode(temp -> bossAudio, ALLEGRO_PLAYMODE_LOOP);

	return temp;
}
Beispiel #21
0
int main(int argc, char *argv[])
{

// -------- VARIÁVEIS DO JOGO --------
ALLEGRO_EVENT_QUEUE *fila_eventos = NULL;
ALLEGRO_TIMER *timer = NULL;
ALLEGRO_FONT *font20 = NULL;
ALLEGRO_SAMPLE *ataque = NULL;
ALLEGRO_SAMPLE *morte_inimigo = NULL;
ALLEGRO_SAMPLE *morte_personagem = NULL;
ALLEGRO_SAMPLE *hit = NULL;
ALLEGRO_SAMPLE *item = NULL;
ALLEGRO_AUDIO_STREAM *musica = NULL;
ALLEGRO_AUDIO_STREAM *track_menu = NULL;
ALLEGRO_BITMAP *start = NULL;

bool fim = false;
bool menu = true;
int flag = 0;
bool desenha = true;
bool game_over = false;
bool teclas[] = {false, false, false, false, false, false, false};
int i;
int dificuldade;


// ___________________________________


// -------- INICIALIZAÇÃO DE OBJETOS --------
dificuldade = 0;
Personagem personagem_principal;
Projetil* balas = new Projetil [NUM_BALAS];
Projetil* balas_2 = new Projetil [NUM_BALAS];
Inimigo* inimigos = new Inimigo[NUM_INIMIGOS];
Inimigo* inimigos2 = new Inimigo [NUM_INIMIGOS];
Coracao* coracoes = new Coracao[NUM_ITENS];
Speed* speed = new Speed[NUM_ITENS];
ItemPontos* pontos = new ItemPontos[NUM_ITENS];
Estrelas estrelas_pf[NUM_PLANOS][NUM_ESTRELAS];
Selecionar select;


// __________________________________________

// -------- INICIALIZAÇÃO DA ALLEGRO E DO DISPLAY --------
    ALLEGRO_DISPLAY *display = NULL;

    if (!al_init())
    {
        al_show_native_message_box(NULL, "AVISO!", "ERRO!", "ERRO AO INICIALIZAR A ALLEGRO!", NULL, ALLEGRO_MESSAGEBOX_ERROR);
        return -1;
    }

    display = al_create_display(LARGURA_T, ALTURA_T);

    if (!display)
    {
        al_show_native_message_box(NULL, "AVISO!", "ERRO!", "ERRO AO CRIAR O DISPLAY!", NULL, ALLEGRO_MESSAGEBOX_ERROR);
        return -1;
    }

    al_set_window_title(display, "Cosmos Guardian");


// ____________________________________________________

// -------- INICIALIZAÇÃO DE ADDONS E INSTALAÇÕES --------
    al_init_primitives_addon();
    al_install_keyboard();
    al_init_image_addon();
    al_init_font_addon();
    al_init_ttf_addon();

    al_install_audio();
    al_init_acodec_addon();

    al_reserve_samples(100);

// _______________________________________________________

// -------- CRIAÇÃO DE FILAS E DEMAIS DISPOSITIVOS --------
    fila_eventos = al_create_event_queue();
    timer = al_create_timer(1.0 / FPS);
    font20 = al_load_font("BADABB__.ttf", 20, 0);


// ________________________________________________________

// -------- REGISTRO DE SOURCES --------
    al_register_event_source(fila_eventos, al_get_display_event_source(display));
    al_register_event_source(fila_eventos, al_get_keyboard_event_source());
    al_register_event_source(fila_eventos, al_get_timer_event_source(timer));

// _____________________________________


// -------- FUNÇÕES INICIAIS --------
    srand(time(NULL));
    personagem_principal.InitPersonagem();

    select.InitSelecionar();

    //Inicialização de projeteis
    for (i = 0; i < NUM_BALAS; i++)
    {
        balas[i].InitBalas();
        balas_2[i].InitBalas();
    }

    //Inicialização de inimigos
    for (i = 0; i < NUM_INIMIGOS; i++)
    {
        inimigos[i].InitInimigo(7, 46, 85, 1 , 0);
        inimigos2[i].InitInimigo(3, 55, 94, 3, 0);
    }

    //Inicialização de itens
    for (i = 0; i < NUM_ITENS; i++)
    {
        coracoes[i].InitItem();
        speed[i].InitItem();
        pontos[i].InitItem();
    }

    //Inicialização do Plano de Fundo
    InitPlanoFundo(estrelas_pf, NUM_PLANOS, NUM_ESTRELAS);

    //Setando Sons e Imagens
    select.bmp = al_load_bitmap("select.png");
    ataque = al_load_sample("laser.wav");
    morte_inimigo = al_load_sample("dead.wav");
    morte_personagem = al_load_sample("death.wav");
    hit = al_load_sample("hit.wav");
    item = al_load_sample("item.wav");
    musica = al_load_audio_stream("trilha_sonora.ogg", 4, 1024);
    track_menu = al_load_audio_stream("menu.ogg", 4, 1024);
    personagem_principal.bmp = al_load_bitmap("ship.png");


    for (i = 0; i < NUM_BALAS; i++)
    {
        balas[i].bmp = al_load_bitmap("bala.png");
        balas_2[i].bmp = al_load_bitmap("bala.png");
    }
    for (i = 0; i < NUM_INIMIGOS; i++){
        inimigos[i].bmp = al_load_bitmap("enemyRed.png");
        inimigos2[i].bmp = al_load_bitmap("enemyWhite.png");
    }
    start = al_load_bitmap("start.jpg");

    for (i = 0; i < NUM_ITENS; i++){
        coracoes[i].imagem = al_load_bitmap("heart.png");
        speed[i].imagem = al_load_bitmap("speed.png");
        pontos[i].imagem = al_load_bitmap("pontos.png");
    }
// __________________________________

// ----------------- LOOP PRINCIPAL -----------------
    al_start_timer(timer);

    while(!fim)
    {
        ALLEGRO_EVENT ev;
        al_wait_for_event(fila_eventos, &ev);
        // -------- EVENTOS E LÓGICA DO JOGO --------
        if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
        {
            fim = true;
        }

        else if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
        {
            switch(ev.keyboard.keycode)
            {
            case ALLEGRO_KEY_ESCAPE:
                fim = true;
                break;
            case ALLEGRO_KEY_UP:
                teclas[CIMA] = true;
                break;
            case ALLEGRO_KEY_DOWN:
                teclas[BAIXO] = true;
                break;
            case ALLEGRO_KEY_LEFT:
                teclas[ESQUERDA] = true;
                break;
            case ALLEGRO_KEY_RIGHT:
                teclas[DIREITA] = true;
                break;
            case ALLEGRO_KEY_SPACE:
                teclas[ESPACO] = true;
                AtiraBalas(balas, NUM_BALAS, personagem_principal, personagem_principal.y + 12);
                AtiraBalas(balas_2, NUM_BALAS, personagem_principal, personagem_principal.y + 70);
                al_play_sample(ataque, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, NULL);
                break;
            case ALLEGRO_KEY_ENTER:
                teclas[ENTER] = true;
                break;
            case ALLEGRO_KEY_BACKSPACE:
                teclas[BACKSPACE] = true;
                break;
            }
        }

        else if (ev.type == ALLEGRO_EVENT_KEY_UP)
        {
            switch(ev.keyboard.keycode)
            {
            case ALLEGRO_KEY_UP:
                teclas[CIMA] = false;
                break;
            case ALLEGRO_KEY_DOWN:
                teclas[BAIXO] = false;
                break;
            case ALLEGRO_KEY_LEFT:
                teclas[ESQUERDA] = false;
                break;
            case ALLEGRO_KEY_RIGHT:
                teclas[DIREITA] = false;
                break;
            case ALLEGRO_KEY_ENTER:
                teclas[ENTER] = false;
                break;
            case ALLEGRO_KEY_BACKSPACE:
                teclas[BACKSPACE] = false;
                break;
            }
        }

        else if (ev.type == ALLEGRO_EVENT_TIMER)
        {
            desenha = true;

            if (teclas[CIMA])
                personagem_principal.MoveCima();
            if (teclas[BAIXO])
                personagem_principal.MoveBaixo(ALTURA_T);
            if (teclas[ESQUERDA])
                personagem_principal.MoveEsquerda();
            if (teclas[DIREITA])
                personagem_principal.MoveDireita(LARGURA_T);
            if (teclas[ESPACO])
            {
                for (i = 0; i < NUM_BALAS; i++)
                {
                    balas[i].AtualizaBalas(0);
                    balas_2[i].AtualizaBalas(0);
                }

            }

            // Movimentação no menu
            if(menu)
            {
                al_attach_audio_stream_to_mixer(track_menu, al_get_default_mixer());
                al_set_audio_stream_playing(track_menu, true);
                if (teclas[CIMA] && select.y!=235)
                    select.y -= 70;
                if (teclas[BAIXO] && select.y!=305)
                    select.y += 70;
                if (teclas[ENTER] && select.y==235)
                {
                    menu = false;
                    al_set_audio_stream_playing(track_menu, false);
                }

            }

            // Acontecimentos do Jogo
            if(!game_over && !menu)
            {
                al_attach_audio_stream_to_mixer(musica, al_get_default_mixer());
                al_set_audio_stream_playing(musica, true);

                AtualizaPlanoFundo(estrelas_pf, NUM_PLANOS, NUM_ESTRELAS);
                {
                    //Gera e atualiza inimigos
                    for (i = 0; i < NUM_INIMIGOS; i++)
                    {
                        inimigos[i].GeraInimigos();
                        inimigos2[i].GeraInimigos();
                        inimigos[i].AtualizaInimigos();
                        inimigos[i].InimigoColidido(personagem_principal, hit);
                        inimigos2[i].AtualizaInimigos();
                        inimigos2[i].InimigoColidido(personagem_principal, hit);
                    }
                }

                //Checa colisões de projeteis

                BalaColidida(balas, NUM_BALAS, inimigos, NUM_INIMIGOS, personagem_principal, dificuldade, morte_inimigo);
                BalaColidida(balas_2, NUM_BALAS, inimigos, NUM_INIMIGOS, personagem_principal, dificuldade, morte_inimigo);

                BalaColidida(balas, NUM_BALAS, inimigos2, NUM_INIMIGOS, personagem_principal, dificuldade, morte_inimigo);
                BalaColidida(balas_2, NUM_BALAS, inimigos2, NUM_INIMIGOS, personagem_principal, dificuldade, morte_inimigo);

                // Faz os testes relacionado aos itens
                for (i = 0; i < NUM_ITENS; i++)
                {
                    coracoes[i].GeraItens(inimigos[i]);
                    coracoes[i].AtualizaItens();
                    coracoes[i].ItemColidido(personagem_principal, item);

                    speed[i].GeraItens(inimigos[i]);
                    speed[i].AtualizaItens();
                    speed[i].ItemColidido(personagem_principal, item);

                    pontos[i].GeraItens(inimigos[i]);
                    pontos[i].AtualizaItens();
                    pontos[i].ItemColidido(personagem_principal, item);
                }


                if ((dificuldade+1)%16 == 0) // Dificuldade aumenta a cada 15 pontos.
                {
                    for (i = 0; i < NUM_INIMIGOS; i++){
                        inimigos[i].velocidade++;
                        inimigos2[i].velocidade++;
                    }

                    dificuldade = 0;
                }

                if (personagem_principal.vidas <= 0)
                {
                    al_play_sample(morte_personagem, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, NULL);
                    game_over = true;
                }
            }

            // Reinicializa o jogo
            else if (!menu)
            {
                al_set_audio_stream_playing(musica, false);
                if (teclas[ENTER])
                {
                    al_destroy_audio_stream(musica);

                    personagem_principal.InitPersonagem();

                    for (i = 0; i < NUM_BALAS; i++)
                    {
                        balas[i].InitBalas();
                        balas_2[i].InitBalas();
                    }


                    for (i = 0; i < NUM_INIMIGOS; i++)
                    {
                        inimigos[i].InitInimigo(7, 46, 85, 1 , 0);
                        inimigos2[i].InitInimigo(3, 55, 94, 3, 0);
                    }

                    for (i = 0; i < NUM_ITENS; i++)
                    {
                        coracoes[i].InitItem();
                        speed[i].InitItem();
                        pontos[i].InitItem();
                    }


                    personagem_principal.bmp = al_load_bitmap("ship.png");
                    musica = al_load_audio_stream("trilha_sonora.ogg", 4, 1024);

                    for (i = 0; i < NUM_BALAS; i++)
                    {
                        balas[i].bmp = al_load_bitmap("bala.png");
                        balas_2[i].bmp = al_load_bitmap("bala.png");
                    }
                    for (i = 0; i < NUM_INIMIGOS; i++)
                    {
                        inimigos[i].bmp = al_load_bitmap("enemyRed.png");
                        inimigos2[i].bmp = al_load_bitmap("enemyWhite.png");
                        coracoes[i].imagem = al_load_bitmap("heart.png");
                        speed[i].imagem = al_load_bitmap("heart.png");
                    }

                    game_over = false;
                }
            }

        }


        // _________________________________________

        // ---------------- DESENHO ----------------

        if(desenha && al_is_event_queue_empty(fila_eventos))
        {
            desenha = false;
            // Desenhos da Tela do Menu
            if(menu)
            {
                al_draw_bitmap(start, 0, 0, 0);
                if (select.ativo)
                    al_draw_bitmap(select.bmp, select.x, select.y, 0);

                if (teclas[ENTER] && flag == 0)
                {
                    flag = 1;
                    teclas[BACKSPACE] = false;
                    select.ativo = false;
                    start = al_load_bitmap("como_jogar.jpg");
                    al_draw_bitmap(start, 0, 0, 0);
                }
                else if (teclas[BACKSPACE] && flag == 1)
                {
                    flag = 0;
                    select.ativo = true;
                    start = al_load_bitmap("start.jpg");
                    al_draw_bitmap(start, 0, 0, 0);
                }
            }
            // Jogo normal, desenho de todos os objetos
            if(!game_over && !menu)
            {
                DesenhaPlanoFundo(estrelas_pf, NUM_PLANOS, NUM_ESTRELAS);
                personagem_principal.DesenhaPersonagem();

                for (i = 0; i < NUM_BALAS; i++)
                {
                    balas[i].DesenhaBalas();
                    balas_2[i].DesenhaBalas();
                }

                for (i = 0; i < NUM_INIMIGOS; i++){
                    inimigos[i].DesenhaInimigos();
                    inimigos2[i].DesenhaInimigos();
                }

                for (i = 0; i < NUM_ITENS; i++)
                {
                    coracoes[i].DesenhaItens();
                    speed[i].DesenhaItens();
                    pontos[i].DesenhaItens();
                }


                al_draw_textf(font20, al_map_rgb(255, 255, 255), 0, 0, 0, "VIDAS: %d / PONTOS: %d", personagem_principal.vidas, personagem_principal.pontos);
            }

            //Tela de fim de jogo
            else if (!menu)
            {
                al_draw_textf(font20, al_map_rgb(255, 255, 255), LARGURA_T / 2, ALTURA_T / 2, ALLEGRO_ALIGN_CENTRE, "FIM DE JOGO. SEUS PONTOS FORAM: %d. TECLE ENTER PARA JOGAR NOVAMENTE OU ESC PARA SAIR DO JOGO.", personagem_principal.pontos);
            }

            al_flip_display();
            al_clear_to_color(al_map_rgb(0, 0, 0));
        }


        // _________________________________________
    }

// _________________________________________________

// -------- FINALIZAÇÕES DO PROGRAMA --------
    delete[] inimigos;
    delete[] inimigos2;
    delete[] balas;
    delete[] balas_2;
    delete[] coracoes;
    delete[] speed;
    delete[] pontos;

    al_destroy_bitmap(start);

    al_destroy_sample(ataque);
    al_destroy_sample(morte_inimigo);
    al_destroy_sample(morte_personagem);
    al_destroy_sample(hit);
    al_destroy_sample(item);
    al_destroy_audio_stream(musica);
    al_destroy_audio_stream(track_menu);

    al_destroy_display(display);
    al_destroy_timer(timer);
    al_destroy_font(font20);
    al_destroy_event_queue(fila_eventos);

//___________________________________________
    return 0;
}
Beispiel #22
0
int main(int argc, char *argv[])
{
   ALLEGRO_CONFIG *config;
   ALLEGRO_EVENT event;
   unsigned buffer_count;
   unsigned samples;
   const char *s;
   ALLEGRO_PLAYMODE playmode = ALLEGRO_PLAYMODE_LOOP;

   initialize();

   if (argc > 1) {
      stream_filename = argv[1];
   }

   buffer_count = 0;
   samples = 0;
   config = al_load_config_file("ex_stream_seek.cfg");
   if (config) {
      if ((s = al_get_config_value(config, "", "buffer_count"))) {
         buffer_count = atoi(s);
      }
      if ((s = al_get_config_value(config, "", "samples"))) {
         samples = atoi(s);
      }
      if ((s = al_get_config_value(config, "", "playmode"))) {
         if (!strcmp(s, "loop")) {
            playmode = ALLEGRO_PLAYMODE_LOOP;
         }
         else if (!strcmp(s, "once")) {
            playmode = ALLEGRO_PLAYMODE_ONCE;
         }
      }
      al_destroy_config(config);
   }
   if (buffer_count == 0) {
      buffer_count = 4;
   }
   if (samples == 0) {
      samples = 1024;
   }

   music_stream = al_load_audio_stream(stream_filename, buffer_count, samples);
   if (!music_stream) {
      abort_example("Stream error!\n");
   }
   al_register_event_source(queue, al_get_audio_stream_event_source(music_stream));

   loop_start = 0.0;
   loop_end = al_get_audio_stream_length_secs(music_stream);
   al_set_audio_stream_loop_secs(music_stream, loop_start, loop_end);

   al_set_audio_stream_playmode(music_stream, playmode);
   al_attach_audio_stream_to_mixer(music_stream, al_get_default_mixer());
   al_start_timer(timer);

   while (!exiting) {
      al_wait_for_event(queue, &event);
      event_handler(&event);
   }

   myexit();
   al_destroy_display(display);
   close_log(true);
   return 0;
}
int main() {
  bool menu = true;
  char pontuacao[100];
  char vida[100];
  ALLEGRO_COLOR  font_color;
  ALLEGRO_FONT *font,*font2;
  ALLEGRO_AUDIO_STREAM *musica = NULL;
  
  camera *cam = camera_inicializa(0);
  if(!cam)
    erro("erro na inicializacao da camera\n");
  int x = 0, y =  0;
  int largura = cam->largura;
  int altura = cam->altura;
  int fps = 0,tempo = 5;
  int ndisco = 9;
 
  if(!al_init())
    erro("erro na inicializacao do allegro\n");

  if(!al_init_image_addon())
    erro("erro na inicializacao do adicional de imagem\n");

  al_init_font_addon();
  al_init_ttf_addon();

    font_color = al_map_rgb(0, 0, 0);
    
    font = al_load_ttf_font("Fontes/Blokletters-Viltstift.ttf", 20, 0);
    font2 = al_load_ttf_font("Fontes/Blokletters-Viltstift.ttf", 50, 0);
    


  if(!al_init_primitives_addon())
    erro("erro na inicializacao do adicional de primitivas\n");

  ALLEGRO_TIMER *timer = al_create_timer(1.0 / FPS);
  if(!timer)
    erro("erro na criacao do relogio\n");

  ALLEGRO_DISPLAY *display = al_create_display(2 * largura,altura);
  if(!display)
    erro("erro na criacao da janela\n");

  ALLEGRO_EVENT_QUEUE *queue = al_create_event_queue();
  if(!queue)
    erro("erro na criacao da fila\n");

   if (!al_install_audio())
    {
        fprintf(stderr, "Falha ao inicializar áudio.\n");
        return false;
    }
 
    if (!al_init_acodec_addon())
    {
        fprintf(stderr, "Falha ao inicializar codecs de áudio.\n");
        return false;
    }
    if (!al_reserve_samples(1))
    {
        fprintf(stderr, "Falha ao alocar canais de áudio.\n");
        return false;
    }

  musica = al_load_audio_stream("Audio/elementary.ogg", 4, 1024);
  if(!musica)
        erro("Erro na alocação da musica de fundo\n");

  al_attach_audio_stream_to_mixer(musica, al_get_default_mixer());
  al_set_audio_stream_playing(musica, true);

  al_register_event_source(queue, al_get_timer_event_source(timer));
  al_register_event_source(queue, al_get_display_event_source(display));

  al_start_timer(timer);
  
  unsigned char ***matriz = camera_aloca_matriz(cam);
  ALLEGRO_BITMAP *buffer = al_get_backbuffer(display);
  ALLEGRO_BITMAP *fundo = al_load_bitmap("Imagens/Elementary2.png");

  if(!fundo)
    erro("erro ao carregar Elementary.png");

  ALLEGRO_BITMAP *esquerda = al_create_sub_bitmap(buffer, 0, 0, largura, altura);
  ALLEGRO_BITMAP *direita = al_create_sub_bitmap(buffer, largura, 0, largura, altura);

  /**********/
  Disco *discos[9];
  bool perdeu = false;
  carregarDiscos(discos);
  int pontos=0,velo = 1;
  int aux1 = 1;
  int vidas = 10;
  int ultimoDisco = 0;
  int distance = 0;
  int desenhar = 0;
  int terminar = 0;
  al_set_target_bitmap(esquerda);
  al_draw_bitmap(fundo,0,0,0);
  while(1) {

    ALLEGRO_EVENT event;

    al_wait_for_event(queue, &event);

    switch(event.type) {
    case ALLEGRO_EVENT_TIMER:
      desenhar = 1;
      break;
    case ALLEGRO_EVENT_DISPLAY_CLOSE:
      terminar = 1;
      break;
   
    }

    if(terminar)
      break;

    if(desenhar && al_is_event_queue_empty(queue)) {
      desenhar = 0;
      camera_atualiza(cam);
      mediana(cam);
      /**********/
      al_set_target_bitmap(esquerda);
      al_draw_bitmap(fundo,0,0,0);
      
      if(!menu){
        while(aux1 <= ndisco){
          if(discos[aux1]->status == false){
            if(distance > 50 || ultimoDisco==0  ){
              printf("%d\n",aux1 );
              al_draw_bitmap(discos[aux1]->elemento,discos[aux1]->pos_x,discos[aux1]->pos_y,0);
              discos[aux1]->status = true;
              distance = 0;
              ultimoDisco = aux1;
              break;
            }else
             aux1++;
          }else{
              discos[aux1]->pos_y+=(10+velo);
              al_draw_bitmap(discos[aux1]->elemento,discos[aux1]->pos_x,discos[aux1]->pos_y,0);
            aux1++;
              
            }
        }
        distance = discos[ultimoDisco]->pos_y;
        for(aux1 = 1;aux1<ndisco;aux1++){
          if(discos[aux1]->pos_x >= x-30 && discos[aux1]->pos_x <= x+30 && discos[aux1]->pos_y >= y-30 &&  discos[aux1]->pos_y <= y+30){
            if(discos[aux1]->tipo == 2){ // Tipo do fogo(Necessario para vencer o jogo)
            pontos +=10;
            velo += 1;
            discos[aux1]->pos_x = rand()%9 * 55;
            discos[aux1]->pos_y = 0;
            discos[aux1]->status = false;
          }else if(discos[aux1]->tipo == 1){ //Tipo da agua(Perde o jogo se destruir esse disco)
            discos[aux1]->pos_x = rand()%9 * 55;
            discos[aux1]->pos_y = 0;
            discos[aux1]->status = false;
            al_flip_display();
            vidas--;
          }else if(discos[aux1]->tipo == 3){//Tipo planta(Aumenta velocidade de queda das peças)
            velo *= 2;
            discos[aux1]->pos_x = rand()%9 * 55;
            discos[aux1]->pos_y = 0;
            discos[aux1]->status = false;
          }

        }else if( discos[aux1]->pos_y > 480){
          if(discos[aux1]->tipo == 2){ //Tipo da agua e Planta(Não perde se deixar cair)
               discos[aux1]->pos_x = rand()%9 * 55;
            discos[aux1]->pos_y = 0;
            discos[aux1]->status = false;
            al_flip_display();
            vidas--;
          }else{
            discos[aux1]->pos_x = rand()%9 * 55;
            discos[aux1]->pos_y = 0;
            discos[aux1]->status = false;
          }
        }
      }

        aux1 = 1;
      sprintf(pontuacao,"PONTUAÇÃO: %d",pontos);
      al_draw_text(font, al_map_rgb(255, 255, 255), 50, 5, 0,pontuacao);
       sprintf(vida,"VIDAS: %d",vidas);
      al_draw_text(font, al_map_rgb(255, 255, 255), 300, 5, 0,vida);
      al_flip_display();

      }
       if(perdeu){
        al_draw_text(font2, al_map_rgb(255, 0, 0), 50, 100, 0,"PONTUAÇÃO FINAL");
        sprintf(pontuacao,"%d",pontos);
        al_draw_text(font2, al_map_rgb(255, 0, 0), 250, 170, 0,pontuacao);
        al_flip_display();
        al_rest(3);
        break;
      }
       
      if(vidas == 0){
        perdeu = true;
      }

      if(menu){
        if(abrirJogo(x,y,&fps,&tempo,font,font2, font_color)){
          fundo = al_load_bitmap("Imagens/galaxia.png");
          menu = false;
        }
      }
      cameraRastreia(cam,&x,&y);
   

      al_set_target_bitmap(direita);
      camera_copia(cam, cam->quadro, direita);
      al_flip_display();
    }
  }
  al_destroy_bitmap(direita);
  al_destroy_bitmap(fundo);
  al_destroy_bitmap(esquerda);
  camera_libera_matriz(cam, matriz);
int fri = 9;
while(fri != 0){
  free(discos[fri]);
  fri--;

}


  al_stop_timer(timer);

  al_unregister_event_source(queue, al_get_display_event_source(display));
  al_unregister_event_source(queue, al_get_timer_event_source(timer));

  al_destroy_event_queue(queue);
  al_destroy_display(display);
  al_destroy_timer(timer);
  al_destroy_audio_stream(musica);
  al_shutdown_primitives_addon();
  al_shutdown_image_addon();
  al_uninstall_system();

  camera_finaliza(cam);

  return EXIT_SUCCESS;
}
void InvestigationScene::setupScene() {
    
    std::vector<Point> positions;
    positions.push_back(pointMake(32, 48));
    positions.push_back(pointMake(34, 48));
    positions.push_back(pointMake(36, 48));
    positions.push_back(pointMake(38, 48));
    positions.push_back(pointMake(40, 49));
    positions.push_back(pointMake(40, 51));
    positions.push_back(pointMake(40, 53));
    positions.push_back(pointMake(30, 49));
    positions.push_back(pointMake(30, 51));
    positions.push_back(pointMake(32, 52));
    
    const char *fontFile = "res/AveriaSerif-Regular.ttf";
    
    font = al_load_font(fontFile, 18, 0);
    if (!font) {
        Director::getInstance()->abortWithMessage("%s not found or failed to load\n", fontFile);
    }
    
    fontBig = al_load_font(fontFile, 26, 0);
    if (!fontBig) {
        Director::getInstance()->abortWithMessage("%s not found or failed to load\n", fontFile);
    }
    
    searchSound = al_load_sample("res/search.wav");
    if (!searchSound) {
        Director::getInstance()->abortWithMessage("%s not found or failed to load\n", "res/search.wav");
    }
    
    clickSound = al_load_sample("res/click.wav");
    if (!clickSound) {
        Director::getInstance()->abortWithMessage("%s not found or failed to load\n", "res/click.wav");
    }
    
    std::vector<TilemapLayer *> layers = TilemapLayer::parseTMXFile("res/mansion.tmx");
    std::vector<TilemapLayer *>::iterator it;
    
    TilemapLayer *firstLayer = layers[0];
    
    camera = new Camera(800, 600, firstLayer->getBoundsSize().width, firstLayer->getBoundsSize().height);
    
    for (it = layers.begin(); it < layers.end(); ++it) {
        
        TilemapLayer *layer = (TilemapLayer *) *it;
        layer->setCamera(camera);
        addToDisplayList(layer);
        
        if (layer->isCollision()) {
            collision = layer;
        }
    }
            
    playerSprite = new Spritesheet("res/professor_walk_cycle_no_hat.png", 64, 64);
    playerSprite->setTag(PLAYER_SPRITE_TAG);
    playerSprite->setCamera(camera);
    playerSprite->setPosition(pointMake(35 * 32, 50 * 32));
    playerSprite->setAnchorPoint(pointMake(0.5, 0.9));
    playerSprite->setAutoZOrder(true);
    addToDisplayList(playerSprite);
    
    mysterySeed = 0;
    
    do {
        
        mysteryTime = 0;
        mysterySeed = time(0);
        
        mystery = new Mystery("res/mansion.xml", mysterySeed, collision->getData(), collision->getSize().width, collision->getSize().height);
        
        while (!mystery->ended && mysteryTime < MAX_MYSTERY_DURATION) {
            mystery->step();
            mysteryTime++;
        }
        
        if (!mystery->ended) {
            delete mystery;
            mystery = NULL;
        }
        
    } while (mystery == NULL);
                    
    printf("Case seed: %d Total duration: %ld %s\n", mysterySeed, mysteryTime, timeToString(mysteryTime, true).c_str());
    
    std::vector<Character *> characters = mystery->getCharacters();
    std::vector<Character *>::iterator itChars;
    
    int i = 0;
    
    for (itChars = characters.begin(); itChars < characters.end(); ++itChars) {
        
        Character *character = (Character *) *itChars;
        
        int frame = i * 2;
        
        if (!character->dead) {
            int idx = rand() % positions.size();
            Point pos = positions[idx];
            
            character->position = pos;
            
            positions.erase(positions.begin() + idx);
        } else {
            frame++;
        }
        
        Spritesheet *sprite = new Spritesheet("res/characters.png", 64, 64);
        sprite->setTag(character->tag);
        sprite->setCamera(camera);
        sprite->setAnchorPoint(pointMake(0.5, 0.9));
        sprite->setAutoZOrder(true);
        sprite->setFrame(frame);
        
        Rect tileRect = collision->getTileRect(character->position.x, character->position.y);
        sprite->setPosition(rectMidPoint(tileRect));
        
        addToDisplayList(sprite);        
        
        i++;
    }
    
    std::vector<POI *>::iterator itWeapons;
    
    i = 0;
    
    for (itWeapons = mystery->weapons.begin(); itWeapons < mystery->weapons.end(); ++itWeapons) {
        
        POI *weapon = (POI *) *itWeapons;
        
        Spritesheet *sprite = new Spritesheet("res/weapons.png", 32, 32);
        sprite->setTag(i + 20);
        sprite->setFrame(i);
        sprite->setCamera(camera);
        sprite->setAnchorPoint(pointMake(0.5, 0.5));
        sprite->setZOrder(400);
        
        Rect tileRect = collision->getTileRect(weapon->position.x, weapon->position.y);
        sprite->setPosition(rectMidPoint(tileRect));
        
        addToDisplayList(sprite);
        
        i++;
    }
    
    actionButton = new Button("action", font, BTN_TXT_COLOR, "res/btn_action.png", "res/btn_action_pressed.png");
    actionButton->setZOrder(500);
    actionButton->setAnchorPoint(pointMake(0.5, 1));
    actionButton->setPosition(pointMake(400, 400));
    actionButton->setCamera(camera);
    actionButton->setHandler(this);
    
    addToDisplayList(actionButton);
    
    Spritesheet *bkgRoomLabel = new Spritesheet("res/bkg_room_name.png");
    bkgRoomLabel->setAnchorPoint(pointMake(0.5, 0.5));
    bkgRoomLabel->setPosition(pointMake(400, 40));
    bkgRoomLabel->setZOrder(501);
    
    addToDisplayList(bkgRoomLabel);
    
    currentRoomLabel = new Label("room", font, al_map_rgb(0, 0, 0));
    currentRoomLabel->setAnchorPoint(pointMake(0.5, 0.5));
    currentRoomLabel->setPosition(bkgRoomLabel->getPosition());
    currentRoomLabel->setZOrder(502);
    
    addToDisplayList(currentRoomLabel);
    
    Spritesheet *bkgWeaponLabel = new Spritesheet("res/bkg_room_name.png");
    bkgWeaponLabel->setAnchorPoint(pointMake(0.5, 0.5));
    bkgWeaponLabel->setPosition(pointMake(720, 40));
    bkgWeaponLabel->setZOrder(501);
    
    addToDisplayList(bkgWeaponLabel);
    
    crimeWeaponLabel = new Label("No weapon", font, al_map_rgb(0, 0, 0));
    crimeWeaponLabel->setAnchorPoint(pointMake(0.5, 0.5));
    crimeWeaponLabel->setPosition(bkgWeaponLabel->getPosition());
    crimeWeaponLabel->setZOrder(502);
    
    addToDisplayList(crimeWeaponLabel);
    
    Spritesheet *bkgAccusationLabel = new Spritesheet("res/bkg_room_name.png");
    bkgAccusationLabel->setAnchorPoint(pointMake(0.5, 0.5));
    bkgAccusationLabel->setPosition(pointMake(80, 40));
    bkgAccusationLabel->setZOrder(501);
    
    addToDisplayList(bkgAccusationLabel);
    
    char buf[100];
    sprintf(buf, "%d accusations left", MAX_ACCUSATIONS);
    
    accusationsLabel = new Label(buf, font, al_map_rgb(0, 0, 0), 120);
    accusationsLabel->setAnchorPoint(pointMake(0.5, 0.5));
    accusationsLabel->setPosition(bkgAccusationLabel->getPosition());
    accusationsLabel->setZOrder(502);
    
    addToDisplayList(accusationsLabel);
    
    bkgQuestion = new Spritesheet("res/bkg_question.png");
    bkgQuestion->setAnchorPoint(pointMake(0.5, 0.5));
    bkgQuestion->setPosition(pointMake(400, 300));
    bkgQuestion->setZOrder(503);
    bkgQuestion->setVisible(false);
        
    addToDisplayList(bkgQuestion);
    
    questionLabel = new Label("question", font, al_map_rgb(0, 0, 0), 350);
    questionLabel->setAnchorPoint(pointMake(0.5, 0.5));
    questionLabel->setPosition(pointMake(400, 120));
    questionLabel->setZOrder(504);
    questionLabel->setVisible(false);
    
    addToDisplayList(questionLabel);
    
    whenLabel = new Label("00:00 and 00:15", fontBig, al_map_rgb(0, 0, 0));
    whenLabel->setAnchorPoint(pointMake(0.5, 0.5));
    whenLabel->setPosition(pointMake(400, 300));
    whenLabel->setZOrder(504);
    whenLabel->setVisible(false);
    
    addToDisplayList(whenLabel);
    
    askQuestionButton = new Button("Ask", font, BTN_TXT_COLOR, "res/btn_med.png", "res/btn_med_pressed.png");
    askQuestionButton->setZOrder(504);
    askQuestionButton->setAnchorPoint(pointMake(0.5, 0.5));
    askQuestionButton->setPosition(pointMake(480, 490));
    askQuestionButton->setHandler(this);
    askQuestionButton->setVisible(false);
    askQuestionButton->setEnabled(false);
    
    addToDisplayList(askQuestionButton);
    
    cancelQuestionButton = new Button("Cancel", font, BTN_TXT_COLOR, "res/btn_med.png", "res/btn_med_pressed.png");
    cancelQuestionButton->setZOrder(504);
    cancelQuestionButton->setAnchorPoint(pointMake(0.5, 0.5));
    cancelQuestionButton->setPosition(pointMake(300, 490));
    cancelQuestionButton->setHandler(this);
    cancelQuestionButton->setVisible(false);
    cancelQuestionButton->setEnabled(false);
    
    addToDisplayList(cancelQuestionButton);
    
    bkgSpeech = new Spritesheet("res/speech.png");
    bkgSpeech->setAnchorPoint(pointMake(0.35, 1));
    bkgSpeech->setCamera(camera);
    bkgSpeech->setZOrder(503);
    bkgSpeech->setVisible(false);
    
    addToDisplayList(bkgSpeech);
    
    speechLabel = new Label("speech", font, al_map_rgb(0, 0, 0), 280);
    speechLabel->setAnchorPoint(pointMake(0.5, 0.5));
    speechLabel->setCamera(camera);
    speechLabel->setZOrder(504);
    speechLabel->setVisible(false);
    
    addToDisplayList(speechLabel);
    
    speechCountLabel = new Label("1/1", font, al_map_rgb(0, 0, 0));
    speechCountLabel->setAnchorPoint(pointMake(1, 0.5));
    speechCountLabel->setCamera(camera);
    speechCountLabel->setZOrder(504);
    speechCountLabel->setVisible(false);
    
    addToDisplayList(speechCountLabel);
    
    speechButton = new Button(bkgSpeech->getFrameSize());
    speechButton->setAnchorPoint(bkgSpeech->getAnchorPoint());
    speechButton->setCamera(camera);
    speechButton->setZOrder(504);
    speechButton->setEnabled(false);
    speechButton->setHandler(this);
    
    addToDisplayList(speechButton);
    
    camera->setCenter(playerSprite->getPosition());
    
    activeCharacter = NULL;
    activePOI = NULL;
    currentRoom = NULL;
    crimeWeapon = NULL;
    
    accusationsLeft = MAX_ACCUSATIONS;
    questionsAsked = 0;
    
    moving = pointMake(0, 0);
    moveDir = 0;
    curFrame = 0;
    
    endScene = false;
    debug = false;
    
    currentFilter.timeStart = 0;
    currentFilter.timeEnd = QUESTION_INTERVAL;
    
    std::string msg;
    msg.append(mystery->victim->name);
    msg.append("'s body was found around ");
    msg.append(timeToString(mystery->corpseFoundTime + START_TIME, false));
    msg.append(" in the ");
    msg.append(mystery->corpseFoundRoom->name);
    msg.append(".");
    
    ModalDialog *dialog = new ModalDialog(msg.c_str(), font, "OK", NULL);
    dialog->setHandler(this);
    dialog->showInScene(this, 1000);
    
    music = al_load_audio_stream("res/mystery.ogg", 4, 2048);
    al_set_audio_stream_playmode(music, ALLEGRO_PLAYMODE_LOOP);
    al_attach_audio_stream_to_mixer(music, al_get_default_mixer());
    
    inDialogue = false;
    inputLocked = true;
    
    investigationStartTime = time(0);
}
Beispiel #25
0
static void * t3f_play_music_thread(void * arg)
{
    const char * ext = NULL;
    ALLEGRO_PATH * path = NULL;
    int loop_points = 0;
    float loop_start = -1;
    float loop_end = -1;
    bool loop_disabled = false;
    const char * val = NULL;
    ALLEGRO_CONFIG * config = NULL;

    ALLEGRO_DEBUG("music thread start\n");
    t3f_music_gain = 1.0;
    al_lock_mutex(t3f_music_mutex);
    if(t3f_stream)
    {
        t3f_stop_music();
    }
    ALLEGRO_DEBUG("setting file interface\n");
    al_set_new_file_interface(t3f_music_thread_file_interface);
    t3f_stream = al_load_audio_stream(t3f_music_thread_fn, 4, 4096);
    if(!t3f_stream)
    {
        al_unlock_mutex(t3f_music_mutex);
        t3f_set_music_state(T3F_MUSIC_STATE_OFF);
        return NULL;
    }

    ALLEGRO_DEBUG("configuring music\n");
    /* look for loop data */
    path = al_create_path(t3f_music_thread_fn);
    if(path)
    {
        al_set_path_extension(path, ".ini");
        config = al_load_config_file(al_path_cstr(path, '/'));
        if(config)
        {
            val = al_get_config_value(config, "loop", "disabled");
            if(val && !strcasecmp(val, "true"))
            {
                loop_disabled = true;
            }
            if(!loop_disabled)
            {
                val = al_get_config_value(config, "loop", "start");
                if(val)
                {
                    loop_start = atof(val);
                    loop_points++;
                }
                val = al_get_config_value(config, "loop", "end");
                if(val)
                {
                    loop_end = atof(val);
                    loop_points++;
                }
            }
            val = al_get_config_value(config, "settings", "gain");
            if(val)
            {
                t3f_music_gain = atof(val);
                if(t3f_music_gain < 0.0)
                {
                    t3f_music_gain = 0;
                }
                if(t3f_music_gain > 10.0)
                {
                    t3f_music_gain = 10.0;
                }
            }
            al_destroy_config(config);
        }
        al_destroy_path(path);
    }

    if(loop_disabled)
    {
        al_set_audio_stream_playmode(t3f_stream, ALLEGRO_PLAYMODE_ONCE);
    }
    else
    {
        if(loop_points != 2)
        {
            /* loop entire song unless audio is MOD music */
            ext = t3f_get_music_extension(t3f_music_thread_fn);
            if(strcmp(ext, ".xm") && strcmp(ext, ".it") && strcmp(ext, ".mod") && strcmp(ext, ".s3m"))
            {
                al_set_audio_stream_loop_secs(t3f_stream, 0.0, al_get_audio_stream_length_secs(t3f_stream));
                al_set_audio_stream_playmode(t3f_stream, ALLEGRO_PLAYMODE_LOOP);
            }
            else
            {
                al_set_audio_stream_playmode(t3f_stream, ALLEGRO_PLAYMODE_LOOP);
            }
        }
        else
        {
            al_set_audio_stream_loop_secs(t3f_stream, loop_start, loop_end);
            al_set_audio_stream_playmode(t3f_stream, ALLEGRO_PLAYMODE_LOOP);
        }
    }
    ALLEGRO_DEBUG("start the music\n");
    t3f_music_volume = t3f_new_music_volume;
    al_set_audio_stream_gain(t3f_stream, t3f_music_volume * t3f_music_gain);
    al_attach_audio_stream_to_mixer(t3f_stream, al_get_default_mixer());
    al_unlock_mutex(t3f_music_mutex);
    t3f_set_music_state(T3F_MUSIC_STATE_PLAYING);
    return NULL;
}