コード例 #1
0
ファイル: Game.cpp プロジェクト: ferrolho/allegro-snake
/* starting game UI */
void start_game (bool Fullscreen) {
	/* creating display */
	ALLEGRO_DISPLAY * display;
	if (Fullscreen) {
		/* creating disp_data struct to store supported resolutions */
		ALLEGRO_DISPLAY_MODE disp_data;

		/* making it fullscreen */
		al_set_new_display_flags(ALLEGRO_FULLSCREEN);

		/* storing info */
		al_get_display_mode(al_get_num_display_modes() - 1, &disp_data);
		CurrentScreenWidth = disp_data.width;
		CurrentScreenHeight = disp_data.height;

		/* creating display with different resolutions for different screens */
		display = al_create_display(CurrentScreenWidth, CurrentScreenHeight);
	}
	else {
		al_set_new_display_flags(ALLEGRO_WINDOWED);

		display = al_create_display(CurrentScreenWidth, CurrentScreenHeight);
	}
	if (!display) {
		al_show_native_message_box(display, "Error", "Display Settings", "Couldn't create a display.", NULL, ALLEGRO_MESSAGEBOX_ERROR);
		exit(-1);
	}
	/* setting new window title */
	al_set_window_title(display, "Snake");

	// -----------------------

	/* creating fonts */
	ALLEGRO_FONT * font = al_load_font(MainFont, 36, ALLEGRO_ALIGN_CENTER);
	ALLEGRO_FONT * credits_font = al_load_font(CreditsFont, 20, NULL);
	if (!font) {
		al_show_native_message_box(display, "Error", "Could not load font file.", "Have you included the resources in the same directory of the program?", NULL, ALLEGRO_MESSAGEBOX_ERROR);
		exit(-1);
	}

	/* loading audio samples */
	ALLEGRO_SAMPLE * over_button_sound = al_load_sample(OverButton);
	ALLEGRO_SAMPLE * pressed_button_sound = al_load_sample(PressedButton);
	ALLEGRO_SAMPLE * eating_apple_sound = al_load_sample(EatApple);
	ALLEGRO_SAMPLE * game_over_sound = al_load_sample(GameOverSound);
	if (!over_button_sound || !pressed_button_sound) {
		al_show_native_message_box(display, "Error", "Could not load one or more sound files.", "Your resources folder must be corrupt, please download it again.", NULL, ALLEGRO_MESSAGEBOX_ERROR);
		exit(-1);
	}
	al_reserve_samples(2);

	/* creating timer */
	ALLEGRO_TIMER * timer = al_create_timer(1.0 / FPS);
	ALLEGRO_TIMER *frametimer = al_create_timer(1.0 / frameFPS);

	/* creating event queue */
	ALLEGRO_EVENT_QUEUE * event_queue = al_create_event_queue();
	al_register_event_source(event_queue, al_get_display_event_source(display));
	al_register_event_source(event_queue, al_get_timer_event_source(timer));
	al_register_event_source(event_queue, al_get_timer_event_source(frametimer));
	al_register_event_source(event_queue, al_get_mouse_event_source());
	al_register_event_source(event_queue, al_get_keyboard_event_source());
	ALLEGRO_KEYBOARD_STATE keystate;

	/* loading BITMAPS */
	ALLEGRO_BITMAP * SmallWallpaperBitmap = al_load_bitmap(SmallWallpaper);
	ALLEGRO_BITMAP * BigWallpaperBitmap = al_load_bitmap(BigWallpaper);
	ALLEGRO_BITMAP * mouse = al_load_bitmap(MouseCursor);
	ALLEGRO_BITMAP * applepng = al_load_bitmap(Apple_png);
	if (!mouse)
	{
		al_show_native_message_box(display, "Error", "Could not load one or more resource file.", "Your resources folder must be corrupt, please download it again.", NULL, ALLEGRO_MESSAGEBOX_ERROR);
		exit(-1);
	}
	al_hide_mouse_cursor(display);

	/* ---- VARIABLES ---- */
	bool done = false, change_resolution = false, draw = true;
	int mouse_x = CurrentScreenWidth, mouse_y = CurrentScreenHeight;
	/* mouse */
	bool left_mouse_button_down = false;
	bool left_mouse_button_up = false;
	/* MAIN MENU */
	int button_displacement;
	if (!Fullscreen)
	{
		button_displacement = 20;
	}
	else
	{
		button_displacement = 15;
	}
	Button play_button(50, 20, Blue, 0, -button_displacement);
	Button options_button(40, 15, Blue);
	Button exit_button(40, 15, Blue, 0, button_displacement);
	/* PLAY */
	string score;
	Direction new_direction;
	int speed_up, speed_up_anim_frame = 0;
	bool speed_up_anim = false;
	Snake snake;
	Apple apple;

	/* starting timers */
	al_start_timer(timer);
	al_start_timer(frametimer);

	while (!done)
	{
		/* actually defining our events */
		ALLEGRO_EVENT events;
		al_wait_for_event(event_queue, &events);
		al_get_keyboard_state(&keystate);

		switch (gameState)
		{
		case MainMenu:
			{
				/* WINDOW */
				if (events.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
				{
					done = true;
				}
				/* MOUSE */
				if (events.type == ALLEGRO_EVENT_MOUSE_AXES)
				{
					mouse_x = events.mouse.x;
					mouse_y = events.mouse.y;

					draw = true;
				}
				if (events.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN)
				{
					/* left button */
					if (events.mouse.button & 1)
					{
						left_mouse_button_down = true;
						draw = true;
					}
				}
				if (events.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP)
				{
					/* left button */
					if (events.mouse.button & 1)
					{
						left_mouse_button_down = false;
						left_mouse_button_up = true;
						draw = true;
					}
				}
				/* button conditions */
				if (play_button.MouseOverButton(mouse_x, mouse_y) && !play_button.StillOverButton)
				{
					play_button.play_over_button_sound = true;
				}
				if (options_button.MouseOverButton(mouse_x, mouse_y) && !options_button.StillOverButton)
				{
					options_button.play_over_button_sound = true;
				}
				if (exit_button.MouseOverButton(mouse_x, mouse_y) && !exit_button.StillOverButton)
				{
					exit_button.play_over_button_sound = true;
				}
				/* KEYBOARD */
				if (events.type == ALLEGRO_EVENT_KEY_UP)
				{
					switch (events.keyboard.keycode)
					{
					case ALLEGRO_KEY_ESCAPE:
						{
							done = true;
							break;
						}
					case ALLEGRO_KEY_SPACE:
					case ALLEGRO_KEY_ENTER:
						{
							/* STARTING GAME NOW */
							new_direction = RIGHT;
							speed_up = 0;
							snake.ResetSnakeDetails();
							apple.NewApple(snake.GetSnakeCells());
							gameState = PlayGame;
						}
					}
					break;
				}

				/* ------------ NOW DRAWING ------------ */
				if (draw)
				{
					/* drawing wallpaper */
					if (Fullscreen)
					{
						al_draw_scaled_bitmap(BigWallpaperBitmap, 0, 0, al_get_bitmap_width(BigWallpaperBitmap), al_get_bitmap_height(BigWallpaperBitmap), 0, 0, CurrentScreenWidth, CurrentScreenHeight, NULL);
					}
					else
					{
						al_draw_bitmap(SmallWallpaperBitmap, 0, 0, 0);
					}

					/* -- play button -- */
					if (play_button.MouseOverButton(mouse_x, mouse_y))
					{
						play_button.SetButtonColor(LightBlue);
						/* button pressed */
						if (left_mouse_button_down)
						{
							play_button.pressed_button = true;
							play_button.SetButtonColor(DarkBlue);
						}
						/* button released */
						else if (left_mouse_button_up)
						{
							play_button.pressed_button = false;
							play_button.StillPressingButton = false;
							play_button.SetButtonColor(Blue);

							/* STARTING GAME NOW */
							new_direction = RIGHT;
							speed_up = 0;
							snake.ResetSnakeDetails();
							apple.NewApple(snake.GetSnakeCells());
							gameState = PlayGame;
						}
						play_button.DisplayButton();
					}
					else
					{
						play_button.pressed_button = false;
						play_button.StillPressingButton = false;
						play_button.StillOverButton = false;
						play_button.SetButtonColor(Blue);
						play_button.DisplayButton();
					}
					/* -- options button -- */
					if (options_button.MouseOverButton(mouse_x, mouse_y))
					{
						options_button.SetButtonColor(LightBlue);
						/* button pressed */
						if (left_mouse_button_down)
						{
							options_button.pressed_button = true;
							options_button.SetButtonColor(DarkBlue);
						}
						/* button released */
						else if (left_mouse_button_up)
						{
							options_button.pressed_button = false;
							options_button.StillPressingButton = false;
							options_button.SetButtonColor(Blue);
							switch (Fullscreen)
							{
							case 0:
								{
									Fullscreen = 1;
									done = true;
									change_resolution = true;
									break;
								}
							case 1:
								{
									Fullscreen = 0;
									done = true;
									change_resolution = true;
									break;
								}
							}
						}
						options_button.DisplayButton();
					}
					else
					{
						options_button.pressed_button = false;
						options_button.StillPressingButton = false;
						options_button.StillOverButton = false;
						options_button.SetButtonColor(Blue);
						options_button.DisplayButton();
					}
					/* -- exit button -- */
					if (exit_button.MouseOverButton(mouse_x, mouse_y))
					{
						exit_button.SetButtonColor(LightBlue);
						/* button pressed */
						if (left_mouse_button_down)
						{
							exit_button.pressed_button = true;
							exit_button.SetButtonColor(DarkBlue);
						}
						/* button released */
						else if (left_mouse_button_up)
						{
							exit_button.pressed_button = false;
							exit_button.StillPressingButton = false;
							exit_button.SetButtonColor(Blue);
							done = true;
						}
						exit_button.DisplayButton();
					}
					else
					{
						exit_button.pressed_button = false;
						exit_button.StillPressingButton = false;
						exit_button.StillOverButton = false;
						exit_button.SetButtonColor(Blue);
						exit_button.DisplayButton();
					}

					/* -- sound -- */
					/* mouse over button */
					if (play_button.MouseOverButton(mouse_x, mouse_y) && !play_button.StillOverButton)
					{
						play_button.StillOverButton = true;
						al_play_sample(over_button_sound, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, 0);
					}
					if (options_button.MouseOverButton(mouse_x, mouse_y) && !options_button.StillOverButton)
					{
						options_button.StillOverButton = true;
						al_play_sample(over_button_sound, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, 0);
					}
					if (exit_button.MouseOverButton(mouse_x, mouse_y) && !exit_button.StillOverButton)
					{
						exit_button.StillOverButton = true;
						al_play_sample(over_button_sound, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, 0);
					}
					/* button pressed */
					if (play_button.pressed_button && !play_button.StillPressingButton)
					{
						play_button.StillPressingButton = true;
						al_play_sample(pressed_button_sound, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, 0);
					}
					else if (options_button.pressed_button && !options_button.StillPressingButton)
					{
						options_button.StillPressingButton = true;
						al_play_sample(pressed_button_sound, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, 0);
					}
					else if (exit_button.pressed_button && !exit_button.StillPressingButton)
					{
						exit_button.StillPressingButton = true;
						al_play_sample(pressed_button_sound, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, 0);
					}

					/* -- text -- */
					string fullscreenmode_string;
					if (Fullscreen)
					{
						fullscreenmode_string = "Fullscreen: On";
					}
					else
					{
						fullscreenmode_string = "Fullscreen: Off";
					}
					al_draw_text(font, White, CurrentScreenWidth / 2, play_button.GetButtonHeightCenter() - 23, ALLEGRO_ALIGN_CENTER, "New Game");
					al_draw_text(font, White, CurrentScreenWidth / 2, options_button.GetButtonHeightCenter() - 23, ALLEGRO_ALIGN_CENTER, fullscreenmode_string.c_str());
					al_draw_text(font, White, CurrentScreenWidth / 2, exit_button.GetButtonHeightCenter() - 23, ALLEGRO_ALIGN_CENTER, "Exit");
					al_draw_text(credits_font, White, 3, CurrentScreenHeight - 20, NULL, "FEUP 2013 - Henrique Ferrolho");

					/* -- mouse cursor -- */
					al_draw_bitmap(mouse, mouse_x, mouse_y, NULL);

					al_flip_display();
					al_clear_to_color(al_map_rgb(0, 0, 0));
					left_mouse_button_up = false;
					draw = false;
				}
				break;
			}
		case PlayGame:
			{
				if (events.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
				{
					done = true;
				}
				/* KEYBOARD */
				if (events.type == ALLEGRO_EVENT_KEY_UP)
				{
					switch (events.keyboard.keycode)
					{
					case ALLEGRO_KEY_ESCAPE:
						{
							/* going back to MAIN MENU */
							draw = true;
							gameState = MainMenu;
							break;
						}
					case ALLEGRO_KEY_ENTER:
					case ALLEGRO_KEY_SPACE:
						{
							/* pausing game */
							draw = true;
							gameState = PauseGame;
							break;
						}

					}
					break;
				}
				if (events.type == ALLEGRO_EVENT_TIMER)
				{
					if (events.timer.source == timer)
					{
						draw = true;

						/* navigation keys */
						if (al_key_down(&keystate, ALLEGRO_KEY_DOWN) || al_key_down(&keystate, ALLEGRO_KEY_S))
						{
							new_direction = DOWN;
						}
						else if (al_key_down(&keystate, ALLEGRO_KEY_UP) || al_key_down(&keystate, ALLEGRO_KEY_W))
						{
							new_direction = UP;
						}
						else if (al_key_down(&keystate, ALLEGRO_KEY_RIGHT) || al_key_down(&keystate, ALLEGRO_KEY_D))
						{
							new_direction = RIGHT;
						}
						else if (al_key_down(&keystate, ALLEGRO_KEY_LEFT) || al_key_down(&keystate, ALLEGRO_KEY_A))
						{
							new_direction = LEFT;
						}

						/* checking boundaries */
						if (!snake.IsInScreenBoundaries() || snake.EatedItself())
						{
							draw = true;
							al_play_sample(game_over_sound, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, 0);
							gameState = GameOver;
							break;
						}
					}
					else if (events.timer.source == frametimer)
					{
						/* moving snake */
						snake.SetSnakeDirection(new_direction);
						snake.MoveSnake();
						if (snake.EatedApple(apple.GetAppleX(), apple.GetAppleY()))
						{
							al_play_sample(eating_apple_sound, 0.5, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, 0);
							apple.NewApple(snake.GetSnakeCells());
							snake.IncreaseSnakeLength();
							draw = true;
						}
					}					
				}

				/* ------------ NOW DRAWING ------------ */
				if (draw)
				{	
					/* game frame */
					if (Fullscreen)
					{
						al_draw_rectangle(0, 0, CurrentScreenWidth, CurrentScreenHeight, DarkRed, 20);
						//al_draw_rectangle(0, 0, 1360, 760, DarkRed, 20);
					}
					else
					{
						al_draw_rectangle(0, 0, CurrentScreenWidth, CurrentScreenHeight, DarkRed, 20);
					}
					apple.DrawApple(applepng);
					snake.DrawSnake();

					/* increasing speed */
					if (snake.GetSnakeCells().size() < 5)
					{
						al_set_timer_speed(frametimer, 1.0 / frameFPS);
					}
					else if (snake.GetSnakeCells().size() < 10)
					{
						if (speed_up == 0)
						{
							speed_up++;
							speed_up_anim = true;
						}
						al_set_timer_speed(frametimer, 1.0 / 14);
					}
					else if (snake.GetSnakeCells().size() < 20)
					{
						if (speed_up == 1)
						{
							snake.SetColor(LightBlue);
							speed_up++;
							speed_up_anim = true;
						}
						al_set_timer_speed(frametimer, 1.0 / 16);
					}
					else if (snake.GetSnakeCells().size() < 30)
					{
						if (speed_up == 2)
						{
							speed_up++;
							speed_up_anim = true;
						}
						al_set_timer_speed(frametimer, 1.0 / 18);
					}
					else if (snake.GetSnakeCells().size() < 40)
					{
						if (speed_up == 3)
						{
							snake.SetColor(DarkRed);
							speed_up++;
							speed_up_anim = true;
						}
						al_set_timer_speed(frametimer, 1.0 / 20);
					}

					/* speed up animation */
					if (speed_up_anim)
					{
						if (speed_up_anim_frame < 10)
						{
							al_draw_text(font, White, CurrentScreenWidth / 2, (CurrentScreenHeight / 2) - 30, ALLEGRO_ALIGN_CENTER, "SPEED UP!");
							speed_up_anim_frame++;
						}
						else if (speed_up_anim_frame < 20)
						{
							al_draw_text(font, Yellow, CurrentScreenWidth / 2, (CurrentScreenHeight / 2) - 30, ALLEGRO_ALIGN_CENTER, "SPEED UP!");
							speed_up_anim_frame++;
						}
						else if (speed_up_anim_frame < 30)
						{
							al_draw_text(font, White, CurrentScreenWidth / 2, (CurrentScreenHeight / 2) - 30, ALLEGRO_ALIGN_CENTER, "SPEED UP!");
							speed_up_anim_frame++;
						}
						else if (speed_up_anim_frame < 40)
						{
							al_draw_text(font, Yellow, CurrentScreenWidth / 2, (CurrentScreenHeight / 2) - 30, ALLEGRO_ALIGN_CENTER, "SPEED UP!");
							speed_up_anim_frame++;
						}
						else if (speed_up_anim_frame < 50)
						{
							al_draw_text(font, White, CurrentScreenWidth / 2, (CurrentScreenHeight / 2) - 30, ALLEGRO_ALIGN_CENTER, "SPEED UP!");
							speed_up_anim_frame++;
						}
						else if (speed_up_anim_frame < 60)
						{
							speed_up_anim = false;
							speed_up_anim_frame = 0;
						}
					}

					/* printing score */
					stringstream ss;
					ss << "Score: " << snake.GetSnakeCells().size();
					score = ss.str();
					al_draw_text(credits_font, Yellow, 60, 15, ALLEGRO_ALIGN_CENTER, score.c_str());

					al_flip_display();
					al_clear_to_color(al_map_rgb(0, 0, 0));
					draw = false;
				}
				break;
			}
		case PauseGame:
			{
				if (events.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
				{
					done = true;
				}
				if (events.type == ALLEGRO_EVENT_KEY_UP)
				{
					switch (events.keyboard.keycode)
					{
					case ALLEGRO_KEY_SPACE:
					case ALLEGRO_KEY_ENTER:
						{
							/* resume game */
							draw = true;
							gameState = PlayGame;
							break;
						}
					}
					break;
				}

				/* ------------ NOW DRAWING ------------ */
				if (draw)
				{
					/* game frame */
					if (Fullscreen)
					{
						al_draw_rectangle(0, 0, CurrentScreenWidth, CurrentScreenHeight, DarkRed, 20);
						//al_draw_rectangle(0, 0, 1360, 760, DarkRed, 20);
					}
					else
					{
						al_draw_rectangle(0, 0, CurrentScreenWidth, CurrentScreenHeight, DarkRed, 20);
					}
					apple.DrawApple(applepng);
					snake.DrawSnake();
					
					/* printing score */
					stringstream ss;
					ss << "Score: " << snake.GetSnakeCells().size();
					score = ss.str();
					al_draw_text(credits_font, Yellow, 60, 15, ALLEGRO_ALIGN_CENTER, score.c_str());

					al_draw_text(font, Yellow, CurrentScreenWidth / 2, (CurrentScreenHeight / 2) - 30, ALLEGRO_ALIGN_CENTER, "GAME PAUSED");

					al_flip_display();
					draw = false;
				}
				break;
			}
		case GameOver:
			{
				if (events.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
				{
					done = true;
				}
				/* MOUSE */
				if (events.type == ALLEGRO_EVENT_MOUSE_AXES)
				{
					mouse_x = events.mouse.x;
					mouse_y = events.mouse.y;

					draw = true;
				}
				if (events.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN)
				{
					/* left button */
					if (events.mouse.button & 1)
					{
						left_mouse_button_down = true;
						draw = true;
					}
				}
				if (events.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP)
				{
					/* left button */
					if (events.mouse.button & 1)
					{
						left_mouse_button_down = false;
						left_mouse_button_up = true;
						draw = true;
					}
				}
				
				/* going to MAIN MENU */
				if (events.type == ALLEGRO_EVENT_KEY_UP)
				{
					switch (events.keyboard.keycode)
					{
					case ALLEGRO_KEY_SPACE:
					case ALLEGRO_KEY_ENTER:
						{
							draw = true;
							gameState = MainMenu;
							break;
						}
					}
					break;
				}
				if (left_mouse_button_up)
				{
					left_mouse_button_up = false;
					draw = true;
					gameState = MainMenu;
					break;
				}

				if (draw)
				{
					al_draw_filled_rectangle(0, 0, CurrentScreenWidth, CurrentScreenHeight, DarkRed);

					/* printing score */
					stringstream ss;
					ss << "Score: " << snake.GetSnakeCells().size();
					score = ss.str();
					al_draw_text(font, Yellow, CurrentScreenWidth / 2, (CurrentScreenHeight / 2) - 80, ALLEGRO_ALIGN_CENTER, score.c_str());

					al_draw_text(font, White, CurrentScreenWidth / 2, (CurrentScreenHeight / 2) - 30, ALLEGRO_ALIGN_CENTER, "Click to continue");
					/* -- mouse cursor -- */
					al_draw_bitmap(mouse, mouse_x, mouse_y, NULL);

					al_flip_display();
				}				
				break;
			}
		}
	}

	/* dealocating memory */
	al_destroy_display(display);
	al_destroy_font(font);
	al_destroy_timer(timer);
	al_destroy_bitmap(mouse);
	al_destroy_sample(over_button_sound);
	al_destroy_sample(pressed_button_sound);
	al_destroy_event_queue(event_queue);

	if (change_resolution)
	{
		CurrentScreenWidth = DefaultScreenWidth;
		CurrentScreenHeight = DefaultScreenHeight;
		start_game(Fullscreen);
	}
}
コード例 #2
0
ファイル: ex_resample_test.c プロジェクト: gitustc/d2imdev
static void mainloop(void)
{
   ALLEGRO_EVENT_QUEUE *queue;
   ALLEGRO_TIMER *timer;
   float *buf;
   double pitch = 440;
   int i, si;
   int n = 0;
   bool redraw = false;
   
   for (i = 0; i < N; i++) {
      frequency[i] = 22050 * pow(2, i / (double)N);
      stream[i] = al_create_audio_stream(4, SAMPLES_PER_BUFFER, frequency[i],
         ALLEGRO_AUDIO_DEPTH_FLOAT32, ALLEGRO_CHANNEL_CONF_1);
      if (!stream[i]) {
         abort_example("Could not create stream.\n");
      }

      if (!al_attach_audio_stream_to_mixer(stream[i], al_get_default_mixer())) {
         abort_example("Could not attach stream to mixer.\n");
      }
   }

   queue = al_create_event_queue();
   al_register_event_source(queue, al_get_keyboard_event_source());
   for (i = 0; i < N; i++) {
      al_register_event_source(queue,
         al_get_audio_stream_event_source(stream[i]));
   }
#ifdef ALLEGRO_POPUP_EXAMPLES
   if (textlog) {
      al_register_event_source(queue, al_get_native_text_log_event_source(textlog));
   }
#endif

   log_printf("Generating %d sine waves of different sampling quality\n", N);
   log_printf("If Allegro's resampling is correct there should be little variation\n", N);

   timer = al_create_timer(1.0 / 60);
   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);
   while (n < 60 * frequency[0] / SAMPLES_PER_BUFFER * N) {
      ALLEGRO_EVENT event;

      al_wait_for_event(queue, &event);

      if (event.type == ALLEGRO_EVENT_AUDIO_STREAM_FRAGMENT) {
         for (si = 0; si < N; si++) {
            buf = al_get_audio_stream_fragment(stream[si]);
            if (!buf) {
               continue;
            }

            for (i = 0; i < SAMPLES_PER_BUFFER; i++) {
               double t = samplepos[si]++ / (double)frequency[si];
               buf[i] = sin(t * pitch * ALLEGRO_PI * 2) / N;
            }

            if (!al_set_audio_stream_fragment(stream[si], buf)) {
               log_printf("Error setting stream fragment.\n");
            }

            n++;
            log_printf("%d", si);
            if ((n % 60) == 0)
               log_printf("\n");
         }
      }
      
      if (event.type == ALLEGRO_EVENT_TIMER) {
         redraw = true;
      }

      if (event.type == ALLEGRO_EVENT_KEY_DOWN &&
            event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) {
         break;
      }

      if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
         break;
      }

#ifdef ALLEGRO_POPUP_EXAMPLES
      if (event.type == ALLEGRO_EVENT_NATIVE_DIALOG_CLOSE) {
         break;
      }
#endif

      if (redraw &&al_is_event_queue_empty(queue)) {
         ALLEGRO_COLOR c = al_map_rgb(0, 0, 0);
         int i;
         al_clear_to_color(al_map_rgb_f(1, 1, 1));
        
         for (i = 0; i < 640; i++) {
            al_draw_pixel(i, 50 + waveform[i] * 50, c);
         }

         al_flip_display();
         redraw = false;
      }
   }

   for (si = 0; si < N; si++) {
      al_drain_audio_stream(stream[si]);
   }

   log_printf("\n");

   al_destroy_event_queue(queue);
}
コード例 #3
0
ファイル: framework.cpp プロジェクト: pmprog/TournamentHub
Framework::Framework()
{
#ifdef WRITE_LOG
  printf( "Framework: Startup\n" );
#endif

  // Init Allegro
	if( !al_init() )
	{
		return;
	}
	al_init_font_addon();
	if( !al_install_keyboard() || !al_install_mouse() || !al_init_primitives_addon() || !al_init_ttf_addon() || !al_init_image_addon() )
	{
		return;
	}
	if( al_install_joystick() )
  {
    al_reconfigure_joysticks();
  }

  audioInitialised = false;
  InitialiseAudioSystem();

  std::string selectedLanguage;
  quitProgram = false;
  ProgramStages = new StageStack();
  framesToProcess = 0;
  Settings = new ConfigFile( "settings.cfg" );

  eventQueue = al_create_event_queue();

  InitialiseDisplay();

	al_register_event_source( eventQueue, al_get_keyboard_event_source() );
	al_register_event_source( eventQueue, al_get_mouse_event_source() );

	fpsTimer = al_create_timer( 1.0 / (float)FRAMES_PER_SECOND );
	al_register_event_source( eventQueue, al_get_timer_event_source( fpsTimer ) );
	al_start_timer( fpsTimer );

	al_hide_mouse_cursor( displaySurface );


  imageMgr = new ImageManager( this );
  fontMgr = new FontManager( this );
  audioMgr = new AudioManager( this );
  int maxDownloads = 4;
  if( Settings->KeyExists( "Downloads.MaxConcurrentDownloads" ) )
  {
    Settings->GetIntegerValue( "Downloads.MaxConcurrentDownloads", &maxDownloads );
  }
  downloadMgr = new DownloadManager( this, maxDownloads );
  networkMgr = new NetworkManager( this );
  languageMgr = new LanguageManager();
  if( Settings->KeyExists( "Application.Language" ) )
  {
    Settings->GetStringValue( "Application.Language", &selectedLanguage );
    languageMgr->SetActiveLanguage( selectedLanguage );
  }

  NativePlatform = new Platform();

  SystemFramework = this;

  extraEventsMutex = al_create_mutex();
}
コード例 #4
0
ファイル: Renderer.cpp プロジェクト: Tomasu/mctools
bool Renderer::init(Minecraft *mc, const char *argv0)
{
	NBT_Debug("begin");

	al_set_org_name("mctools");
	al_set_app_name("viewer");

	if(!al_init())
	{
		NBT_Debug("al_init failed???");
		return false;
	}

	ALLEGRO_TIMER *tmr = nullptr;
	ALLEGRO_EVENT_QUEUE *queue = nullptr;
	ALLEGRO_DISPLAY *dpy = nullptr;
	ALLEGRO_BITMAP *bmp = nullptr;
	ALLEGRO_TRANSFORM *def_trans = nullptr;
	ALLEGRO_FONT *fnt = nullptr;

	if(!al_install_keyboard())
		goto init_failed;

   if(!al_install_mouse())
		goto init_failed;

	if(!al_init_primitives_addon())
		goto init_failed;

	if(!al_init_image_addon())
		goto init_failed;

	if(!al_init_font_addon())
		goto init_failed;

	tmr = al_create_timer(1.0/60.0);
	if(!tmr)
		goto init_failed;

	queue = al_create_event_queue();
	if(!queue)
		goto init_failed;

	// do display creation last so a display isn't created and instantly destroyed if any of the
	// preceeding initializations fail.
	al_set_new_display_flags(ALLEGRO_OPENGL | ALLEGRO_PROGRAMMABLE_PIPELINE | ALLEGRO_OPENGL_3_0);
	//al_set_new_display_option(ALLEGRO_SAMPLE_BUFFERS, 1, ALLEGRO_REQUIRE);
   //al_set_new_display_option(ALLEGRO_SAMPLES, 4, ALLEGRO_REQUIRE);
	al_set_new_display_option(ALLEGRO_DEPTH_SIZE, 24, ALLEGRO_REQUIRE);

	dpy = al_create_display(800, 600);

	if(!dpy)
	{
		NBT_Debug("display creation failed");
		goto init_failed;
	}

	if(!al_get_opengl_extension_list()->ALLEGRO_GL_EXT_framebuffer_object)
	{
		NBT_Debug("FBO GL extension is missing. bail");
		goto init_failed;
	}

	glGenVertexArrays(1, &vao_);
	glBindVertexArray(vao_);

	NBT_Debug("load shaders");
	if(!loadShaders("shaders/default.vtx", "shaders/default.pxl"))
	{
		NBT_Debug("shader init failed");
		goto init_failed;
	}

	NBT_Debug("load allegro shaders");
	if(!loadAllegroShaders())
	{
		NBT_Debug("allegro shader init failed");
		goto init_failed;
	}

	glBindVertexArray(0);

	NBT_Debug("create resource manager");
	resManager_ = new ResourceManager(this);
	if(!resManager_->init(mc, argv0))
	{
		NBT_Debug("failed to init resource manager");
		goto init_failed;
	}

	fnt = al_create_builtin_font();
	if(!fnt)
	{
		NBT_Debug("failed to create builtin font");
		goto init_failed;
	}

	al_register_event_source(queue, al_get_keyboard_event_source());
	al_register_event_source(queue, al_get_mouse_event_source());
	al_register_event_source(queue, al_get_display_event_source(dpy));
	al_register_event_source(queue, al_get_timer_event_source(tmr));

	def_trans = al_get_projection_transform(dpy);
	al_copy_transform(&al_proj_transform_, def_trans);

	al_identity_transform(&camera_transform_);

	rx_look = 0.0;

	queue_ = queue;
	tmr_ = tmr;
	dpy_ = dpy;
	bmp_ = bmp;
	fnt_ = fnt;
	grab_mouse_ = false;

	// initial clear display
	// make things look purdy
	al_clear_to_color(al_map_rgb(0,0,0));
   al_flip_display();

	NBT_Debug("end");
	return true;

init_failed:
	delete resManager_;
	resManager_ = nullptr;

	if(fnt)
		al_destroy_font(fnt);

	if(dpy)
		al_destroy_display(dpy);

	if(queue)
		al_destroy_event_queue(queue);

	al_uninstall_system();
	NBT_Debug("end");
	return false;
}
コード例 #5
0
ファイル: game.cpp プロジェクト: kotori/alMonopoly
int MonopolyGame::init() {

    // Now begin initializing the Allegro library.
    if(!al_init()) {
        fprintf(stderr, "Failed to initialize Allegro.\n");
        return -1;
    }

    if(!al_install_keyboard()) {
        fprintf(stderr, "Failed to initialize the Keyboard!\n");
        return -1;
    }

    m_alTimer = al_create_timer(1.0 / MAX_FPS);
    if(!m_alTimer) {
        fprintf(stderr, "Failed to create Timer!\n");
        return -1;
    }

    m_alFrameTimer = al_create_timer(1.0 / MAX_FRAME_FPS);
    if(!m_alFrameTimer) {
        fprintf(stderr, "Failed to create Timer!\n");
        al_destroy_timer(m_alTimer);
        return -1;
    }

    al_init_image_addon(); // Initialize the image addon.
    al_install_audio();
    al_init_acodec_addon();

    al_init_font_addon(); // Initialize the font addon.
    al_init_ttf_addon(); // Initialize the ttf (True Type Font) addon.

    // Setup the display device in windowed mode.
    al_set_new_display_flags(ALLEGRO_WINDOWED);
    m_alDisplayDevice = al_create_display(WINDOW_WIDTH, WINDOW_HEIGHT);
    if(!m_alDisplayDevice) {
        fprintf(stderr, "Failed to create Display: %i x %i\n", WINDOW_WIDTH, WINDOW_HEIGHT);
        al_destroy_timer(m_alTimer);
        al_destroy_timer(m_alFrameTimer);
        return -1;
    }

    // Create an event queue. This is where timed events, etc are pulled from.
    m_alEventQueue = al_create_event_queue();
    if(!m_alEventQueue) {
        fprintf(stderr, "Failed to create Event Queue!\n");
        al_destroy_display(m_alDisplayDevice);
        al_destroy_timer(m_alTimer);
        al_destroy_timer(m_alFrameTimer);
        return -1;
    }

    if( !al_reserve_samples( MAX_NUM_SAMPLES ) ) {
        fprintf(stderr, "Failed to reserve the required sound instances!\n");
        al_destroy_display(m_alDisplayDevice);
        al_destroy_timer(m_alTimer);
        al_destroy_timer(m_alFrameTimer);
        return -1;
    }

    // Register an event source per input.
    al_register_event_source(m_alEventQueue, al_get_display_event_source(m_alDisplayDevice));
    al_register_event_source(m_alEventQueue, al_get_timer_event_source(m_alTimer));
    al_register_event_source(m_alEventQueue, al_get_timer_event_source(m_alFrameTimer));
    al_register_event_source(m_alEventQueue, al_get_keyboard_event_source());

    // Ensure the mouse cursor is not visible.
    al_hide_mouse_cursor(m_alDisplayDevice);

    // Set some default values for the camera.
    m_alCamera.cameraPosition[Positions::X_POS] = 0;
    m_alCamera.cameraPosition[Positions::Y_POS] = 0;

    return 0;
}
コード例 #6
0
ファイル: blasteroids.c プロジェクト: pasoev/blasteroids
int main(int argc, char *argv[]) {

    int c;

    while((c = getopt(argc, argv, "hv")) != -1) {
        switch(c) {
        case 'h':
            puts(HELP);
            return 0;
        case 'v':
            printf("version %.1f\n", PROGRAM_VERSION);
            return 0;
        }
    }

    if(!al_init()) {
        fprintf(stderr, "failed to initialize allegro!\n");
        return -1;
    }

    if(argc == 2 && !strcmp(argv[1], "-v")) {
        printf("version %.1f\n", PROGRAM_VERSION);
        return 0;
    }

    bool key[5] = {false, false, false, false, false};
    bool doexit = false;
    bool redraw = true;

    timer = al_create_timer(1.0 / FPS);
    if(!timer) {
        fprintf(stderr, "couldn't initialize timer.\n");
        return -1;
    }

    display = al_create_display(SCREEN_W, SCREEN_H);
    if(!display) {
        fprintf(stderr, "failed to create the display.\n");
        al_destroy_timer(timer);

        return -1;
    }

    al_set_window_title(display, "blasteroids");

    al_init_primitives_addon();

    if(!al_install_keyboard()) {
        fprintf(stderr, "failed to initialize keyboard.\n");
        al_destroy_display(display);
        al_destroy_timer(timer);

        return -1;
    }

    /* Making the sky look like sky */

    colors[0] = al_map_rgba(255, 100, 255, 128);
    colors[1] = al_map_rgba(255, 100, 100, 255);
    colors[2] = al_map_rgba(100, 100, 255, 255);

    for (layer = 0; layer < 3; layer++) {
        for (star = 0; star < NUM_STARS/3; star++) {
            Point *p = &stars[layer][star];
            p->x = rand() % SCREEN_W;
            p->y = rand() % SCREEN_H;
        }
    }


    start = al_get_time() * 1000;
    now = start;
    elapsed = 0;
    frame_count = 0;
    program_start = al_get_time();


    /* done with the sky. Now making the ship. */
    Spaceship *ship = init_ship();
    List *a = (List *)summon_asteroids(NUMBER_ASTEROIDS);
    ListElmt *astElmt = list_head(a);


    if(!ship) {
        fprintf(stderr, "couldn't create bitmap.\n");
        al_destroy_timer(timer);
        al_destroy_display(display);
        return -1;
    }

    Blast *blast = init_blast(ship->sx, ship->sy, ship->heading);

    event_queue = al_create_event_queue();
    if(!event_queue) {
        fprintf(stderr, "failed to create event queue.\n");
        al_destroy_display(display);
        al_destroy_timer(timer);
        return -1;
    }

    al_register_event_source(event_queue, al_get_keyboard_event_source());
    al_register_event_source(event_queue, al_get_display_event_source(display));
    al_register_event_source(event_queue, al_get_timer_event_source(timer));

    al_start_timer(timer);

    while(!doexit) {
        /* animate the sky, just sky, starts, but NOT objects. */

        ALLEGRO_EVENT ev;
        al_wait_for_event(event_queue, &ev);

        if(ev.type == ALLEGRO_EVENT_TIMER) {

            if(key[UP])
                ship->speed += 0.04;

            if(key[RIGHT])
                ship->heading += 1.0f;

            if(key[DOWN])
                if(ship->speed > 0.05)
                    ship->speed -= 0.04;

            if(key[LEFT])
                ship->heading -= 1.0f;

            fly_ship(ship);
            // fire ze missile

            if(key[SPACE]) {
                blast->sx = ship->sx;
                blast->sy = ship->sy;
                blast->heading = ship->heading;
                blast->gone = 0;
            }

            float theta = head2theta(blast->heading);
            blast->sx += blast->speed * cos(theta);
            if(blast->sx <= 0 || blast->sx >= SCREEN_W) {
                blast->gone = 1;
            }

            blast->sy += blast->speed * sin(theta);
            if(blast->sy <= 0 || blast->sy >= SCREEN_H) {
                blast->gone = 1;
            }

            /* loop through the list of asteroids */

            astElmt = (astElmt->next)?astElmt->next : list_head(a);
            Asteroid *aster = astElmt->aster;

            /* asteroid eternity */
            if(aster->sx < 0 || aster->sx > SCREEN_W - 33)
                aster->sx = 0;

            if(aster->sy < 0 || aster->sy > SCREEN_H)
                aster->sy = 0;



            aster->twist += aster->rot_velocity;

            /* Fuzzy movement */
            if((int)aster->sx % 3 == 0)
                aster->sx += aster->speed;
            aster->sx += 0.9;
            if((int)aster->sy % 5 == 3)
                aster->sy += aster->speed;
            aster->sy += 0.9;

            aster->twist += 0.4;

            /* detect alteroid collision, but only if 5 seconds have
             passed since the last Death */

            Box s = {{ship->sx, ship->sy}, 16.0f, 20.0f};
            Box a = {{aster->sx, aster->sy}, 45.0f, 40.0f};

            if(ship->heading != -90.0f) {
                if(!aster->gone && !ship->gone && is_collision(&s, &a)) {
                    ship->color = al_map_rgb(0, 0, 255);
                }
            }

            /* detect asteroid being shot */

            Box b = {{blast->sx, blast->sy}, 120.0f, 3.0f};
            if(!(blast->gone) && !(aster->gone) && is_collision(&b, &a)) {
                aster->gone = 1;
            }
            redraw = true;
        }
        else if(ev.type == ALLEGRO_EVENT_KEY_DOWN) {

            switch(ev.keyboard.keycode) {
            case ALLEGRO_KEY_UP:
                key[UP] = true;
                break;
            case ALLEGRO_KEY_RIGHT:
                key[RIGHT] = true;
                break;
            case ALLEGRO_KEY_DOWN:
                key[DOWN] = true;
                break;
            case ALLEGRO_KEY_LEFT:
                key[LEFT] = true;
                break;
            case ALLEGRO_KEY_SPACE:
                key[SPACE] = true;
                break;
            }
        }
        else if(ev.type == ALLEGRO_EVENT_KEY_UP) {
            switch(ev.keyboard.keycode) {
            case ALLEGRO_KEY_UP:
                key[UP] = false;
                break;
            case ALLEGRO_KEY_RIGHT:
                key[RIGHT] = false;
                break;
            case ALLEGRO_KEY_DOWN:
                key[DOWN] = false;
                break;
            case ALLEGRO_KEY_LEFT:
                key[LEFT] = false;
                break;
            case ALLEGRO_KEY_SPACE:
                key[SPACE] = false;
                break;
            case ALLEGRO_KEY_Q:
            case ALLEGRO_KEY_ESCAPE:
                doexit = true;
                break;
            }
        }

        if(redraw && al_is_event_queue_empty(event_queue)) {
            redraw = false;
            al_clear_to_color(al_map_rgb(0, 0, 0));

            if (frame_count < (1000/TARGET_FPS)) {
                frame_count += elapsed;
            }
            else {
                int X, Y;

                frame_count -= (1000/TARGET_FPS);

                for (star = 0; star < NUM_STARS/3; star++) {
                    Point *p = &stars[0][star];
                    al_draw_pixel(p->x, p->y, colors[0]);
                }
                /*	al_lock_bitmap(al_get_backbuffer(display), ALLEGRO_PIXEL_FORMAT_ANY, 0); */

                for (layer = 1; layer < 3; layer++) {
                    for (star = 0; star < NUM_STARS/3; star++) {
                        Point *p = &stars[layer][star];
                        // put_pixel ignores blending
                        al_put_pixel(p->x, p->y, colors[layer]);
                    }
                }

                /* Check that dots appear at the window extremes. */
                X = SCREEN_W - 1;
                Y = SCREEN_H - 1;
                al_put_pixel(0, 0, al_map_rgb_f(1, 1, 1));
                al_put_pixel(X, 0, al_map_rgb_f(1, 1, 1));
                al_put_pixel(0, Y, al_map_rgb_f(1, 1, 1));
                al_put_pixel(X, Y, al_map_rgb_f(1, 1, 1));

                /* al_unlock_bitmap(al_get_backbuffer(display)); */
                total_frames++;
            }

            now = al_get_time() * 1000;
            elapsed = now - start;
            start = now;

            for (layer = 0; layer < 3; layer++) {
                for (star = 0; star < NUM_STARS/3; star++) {
                    Point *p = &stars[layer][star];
                    p->y -= speeds[layer] * elapsed;
                    if (p->y < 0) {
                        p->x = rand() % SCREEN_W;
                        p->y = SCREEN_H;
                    }
                }
            }
            draw_ship(ship);

            if(!blast->gone) {
                draw_blast(blast);
            }
            draw_asteroids(a);
            al_flip_display();
        }
    }

    length = al_get_time() - program_start;

    /* printf("Length = %f\n", length); */

    al_destroy_timer(timer);
    al_destroy_display(display);
    al_destroy_event_queue(event_queue);

    return 0;
}
コード例 #7
0
ファイル: main.c プロジェクト: fspacheco/ProjetoC
int main()
{
    bool quit = false;
    int gamestate = 0;
    srand(time(NULL));

    int change_bkg = 0;
    int stopwatch = 120;
    bool iddle = false;

    int bulletID=0;
    int bulletCount=0;

    ALLEGRO_DISPLAY*            display;
    ALLEGRO_TIMER*              timer_0p2;
    ALLEGRO_TIMER*              timer_1;
    ALLEGRO_TIMER*              timer_60;
    ALLEGRO_EVENT_QUEUE*        event_queue;
    ALLEGRO_EVENT               ev;

    ALLEGRO_BITMAP*             img_home_screen;
    ALLEGRO_BITMAP*             img_dica_h1n1;
    ALLEGRO_BITMAP*             img_background0;
    ALLEGRO_BITMAP*             img_game_over;
    ALLEGRO_BITMAP*             img_you_win;

    ALLEGRO_BITMAP*             img_heart;
    ALLEGRO_BITMAP*             img_medal;
    ALLEGRO_BITMAP*             img_clock;
    ALLEGRO_BITMAP*             img_block1;
    ALLEGRO_BITMAP*             img_block2;

    ALLEGRO_BITMAP*             img_player_walking;
    ALLEGRO_BITMAP*             img_player_walking_shoot;
    ALLEGRO_BITMAP*             img_player_immobile;
    ALLEGRO_BITMAP*             img_player_immobile_shoot;
    ALLEGRO_BITMAP*             img_player_jump;
    ALLEGRO_BITMAP*             img_player_jump_shoot;
    ALLEGRO_BITMAP*             img_player_bullet;

    ALLEGRO_BITMAP*             img_enemy1;
    ALLEGRO_BITMAP*             img_boss1;
    ALLEGRO_BITMAP*             img_enemy_bullet;

    ALLEGRO_SAMPLE*             spl_theme;
    ALLEGRO_SAMPLE*             spl_playerShoot;
    ALLEGRO_SAMPLE*             spl_mlk;

    ALLEGRO_SAMPLE_INSTANCE*    instance_theme;
    ALLEGRO_SAMPLE_INSTANCE*    instance_playerShoot;
    ALLEGRO_SAMPLE_INSTANCE*    instance_mlk;

    ALLEGRO_FONT*           fonte16;

    /* Estruturas */
    s_object player;
    s_object block[LINHA_MAX][COLUNA_MAX];
    s_object enemy1[LINHA_MAX][COLUNA_MAX];

    for (i=0; i<LINHA_MAX; i++)
    {
        for(j=0; j<COLUNA_MAX; j++)
        {
            /* Cria o player */
            if(mapa[i][j] == 1)
            {
                player.y = i*16 - 24;
                player.x = j*64 + 24;
                player.speed = 3;
                player.direction = 1;

                player.live = true;
                player.life = 100;

                block[i][j].live = false;
            }
            /* Cria os Blocos */
            if(mapa[i][j] == 2)
            {
                block[i][j].y = i*16;
                block[i][j].x = j*64;
                block[i][j].live = true;
            }
            if(mapa[i][j] == 3)
            {
                block[i][j].y = i*16;
                block[i][j].x = j*64;
                block[i][j].live = true;
            }
            if(mapa[i][j] == 4)
            {
                block[i][j].y = i*16;
                block[i][j].x = j*64;
                block[i][j].live = true;
            }
            if(mapa[i][j] == 5)
            {
                block[i][j].y = i*16;
                block[i][j].x = j*64;
                block[i][j].live = false;
            }
            /* Cria os Inimigos */
            if(mapa[i][j] == 6)
            {
                enemy1[i][j].y = i*16 - 24;
                enemy1[i][j].x = j*64;
                enemy1[i][j].speed = 2;
                enemy1[i][j].direction = -1;

                enemy1[i][j].life = 3;
                enemy1[i][j].live = true;

                block[i][j].live = false;
            }
            if(mapa[i][j] == 7 || mapa[i][j] == 8)
            {
                enemy1[i][j].y = i*16 - 24;
                enemy1[i][j].x = j*64;
                enemy1[i][j].speed = 2;
                enemy1[i][j].direction = 1;

                enemy1[i][j].life = 3;
                enemy1[i][j].live = false;

                block[i][j].live = false;
            }
            if(mapa[i][j] == 9)
            {
                enemy1[i][j].y = i*16 - 24;
                enemy1[i][j].x = j*64;
                enemy1[i][j].speed = 2;
                enemy1[i][j].direction = -1;

                enemy1[i][j].life = 25;
                enemy1[i][j].live = false;

                block[i][j].live = false;
            }
        }
    }

    s_bullet playerBullet[NUM_BULLET];
    s_bullet enemyBullet[NUM_BULLET];

    for(i=0; i<NUM_BULLET; i++)
    {
        playerBullet[i].x = 0;
        playerBullet[i].y = 0;
        playerBullet[i].speed = 5;
        playerBullet[i].direction = 1;
        playerBullet[i].live = false;

        enemyBullet[i].x = 0;
        enemyBullet[i].y = 0;
        enemyBullet[i].speed = 5;
        enemyBullet[i].direction = 0;
        enemyBullet[i].live = false;
    }
    s_animation walking;
    walking.maxFrame = 8;
    walking.frameDelay = 5;
    walking.frameCount = 0;
    walking.curFrame = 0;
    walking.frameHeight = 40;
    walking.frameWidth = 40;

    s_animation jumping;
    jumping.maxFrame = 7;
    jumping.frameDelay = 5;
    jumping.frameCount = 0;
    jumping.curFrame = 0;
    jumping.frameHeight = 52;
    jumping.frameWidth = 40;

    s_animation immobile;
    immobile.maxFrame = 7;
    immobile.frameDelay = 15;
    immobile.frameCount = 0;
    immobile.curFrame = 0;
    immobile.frameHeight = 40;
    immobile.frameWidth = 40;

    s_animation anim_enemy1;
    anim_enemy1.maxFrame = 3;
    anim_enemy1.frameDelay = 15;
    anim_enemy1.frameCount = 0;
    anim_enemy1.curFrame = 0;
    anim_enemy1.frameHeight = 40;
    anim_enemy1.frameWidth = 40;

    /* Faz com que as teclas comecem em false */
    for(i=0; i<KEY_MAX; i++)
    {
        keys[i] = false;
    }

    /* Carrega as configuracoes (teclado, audio, etc) */
    al_init();
    al_install_keyboard();
    al_init_image_addon();
    al_install_audio();
    al_init_acodec_addon();
    al_init_font_addon();
    al_init_ttf_addon();


    /* Erros ao criar algo */
    display = al_create_display(SCREEN_W, SCREEN_H);
    if(!display)
    {
        printf("Erro ao criar o display");
        exit(-1);
    }

    timer_0p2 = al_create_timer(5.0);
    timer_1 = al_create_timer(1.0);
    timer_60 = al_create_timer(1/60.0);

    if(!timer_0p2)
    {
        printf("Erro ao criar o timer de 0.2 FPS");
        exit(-1);
    }
    if(!timer_1)
    {
        printf("Erro ao criar o timer de 1 FPS");
        exit(-1);
    }
    if(!timer_60)
    {
        printf("Erro ao criar o timer de 60 FPS");
        exit(-1);
    }

    event_queue = al_create_event_queue();
    if(!event_queue)
    {
        printf("Erro ao criar o event_queue");
        exit(-1);
    }

    /* Carregando as Imagens */
    img_home_screen = al_load_bitmap("Sprites/Background/home_screen.png");
    img_dica_h1n1 = al_load_bitmap("Sprites/Background/dica_h1n1.png");
    img_background0 = al_load_bitmap("Sprites/Background/background_h1n1.png");
    img_you_win = al_load_bitmap("Sprites/Background/you_win.png");
    img_game_over = al_load_bitmap("Sprites/Background/game_over.png");

    img_heart = al_load_bitmap("Sprites/heart.png");
    img_medal = al_load_bitmap("Sprites/medal.png");
    img_clock = al_load_bitmap("Sprites/clock.png");
    img_block1 = al_load_bitmap("Sprites/block1.png");
    img_block2 = al_load_bitmap("Sprites/block2.png");

    img_player_walking = al_load_bitmap("Sprites/Player/player_walking.png");
    img_player_walking_shoot = al_load_bitmap("Sprites/Player/player_walking_shoot.png");
    img_player_immobile = al_load_bitmap("Sprites/Player/player_immobile.png");
    img_player_immobile_shoot = al_load_bitmap("Sprites/Player/player_immobile_shoot.png");
    img_player_jump = al_load_bitmap("Sprites/Player/player_jump.png");
    img_player_jump_shoot = al_load_bitmap("Sprites/Player/player_jump_shoot.png");
    img_player_bullet = al_load_bitmap("Sprites/Player/player_bullet.png");

    img_enemy1 = al_load_bitmap("Sprites/Enemies/enemy_h1n1.png");
    img_boss1 = al_load_bitmap("Sprites/Enemies/boss_h1n1.png");
    img_enemy_bullet = al_load_bitmap("Sprites/Enemies/enemy_bullet.png");

    /* Carregando os Samples */
    al_reserve_samples(10);
    spl_theme = al_load_sample("Sounds/theme.wav");
    spl_playerShoot = al_load_sample("Sounds/shoot.wav");
    spl_mlk = al_load_sample("Sounds/mlk.wav");

    instance_theme = al_create_sample_instance(spl_theme);
    instance_playerShoot = al_create_sample_instance(spl_playerShoot);
    instance_mlk = al_create_sample_instance(spl_mlk);

    al_set_sample_instance_gain(instance_playerShoot, 0.5);

    al_attach_sample_instance_to_mixer(instance_theme, al_get_default_mixer());
    al_attach_sample_instance_to_mixer(instance_playerShoot, al_get_default_mixer());
    al_attach_sample_instance_to_mixer(instance_mlk, al_get_default_mixer());

    /* Registra os Eventos */
    al_register_event_source(event_queue, al_get_display_event_source(display));
    al_register_event_source(event_queue, al_get_timer_event_source(timer_0p2));
    al_register_event_source(event_queue, al_get_timer_event_source(timer_1));
    al_register_event_source(event_queue, al_get_timer_event_source(timer_60));
    al_register_event_source(event_queue, al_get_keyboard_event_source());

    /* Carregando os timers */
    al_start_timer(timer_0p2);
    al_start_timer(timer_1);
    al_start_timer(timer_60);

    /* Carregando a fonte */
    fonte16 = al_load_ttf_font("Joystix.TTF", 16, 0);
    if (!fonte16) {
        printf("Erro ao carregar Joystix.TTF\n");
        exit(1);
    }

    while(!quit)
    {
        switch(gamestate)
        {
        case 0:
            al_wait_for_event(event_queue, &ev);

            if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) /* Faz com que o jogo feche ao clicar no botao "X" do display */
            {
                quit = true;
            }

            if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
            {
                if(ev.keyboard.keycode == ALLEGRO_KEY_ESCAPE) /* Faz com que o jogo feche ao pressionar esc */
                {
                    quit = true;
                }
                if(ev.keyboard.keycode == ALLEGRO_KEY_SPACE) /* Faz com que o jogo inicie ao pressionar space */
                {
                    change_bkg++;
                    if(change_bkg >= 2)
                    {
                        gamestate = 1;
                    }
                }
            }
            if(ev.type == ALLEGRO_EVENT_TIMER) /* Mostrar mensagens na tela */
            {
                if(ev.timer.source == timer_60)
                {
                    al_clear_to_color(al_map_rgb(0,0,0));
                    if(change_bkg == 0)
                    {
                        al_draw_bitmap(img_home_screen, 0, 0, 0);
                    }
                    if(change_bkg == 1)
                    {
                        al_draw_bitmap(img_dica_h1n1, 0, 0, 0);

                        if(++anim_enemy1.frameCount >= anim_enemy1.frameDelay)
                        {
                            if(++anim_enemy1.curFrame >= anim_enemy1.maxFrame)
                            {
                                anim_enemy1.curFrame = 0;
                            }
                            anim_enemy1.frameCount = 0;
                        }

                        al_draw_bitmap_region(img_enemy1, anim_enemy1.curFrame * anim_enemy1.frameWidth, 0, anim_enemy1.frameWidth, anim_enemy1.frameHeight, 330, 320, 0);
                        al_draw_bitmap_region(img_boss1, anim_enemy1.curFrame * anim_enemy1.frameWidth, 0, anim_enemy1.frameWidth, anim_enemy1.frameHeight, 450, 320, 0);
                    }
                    al_flip_display();
                }
            }
            break;
        case 1:

            if(force>= -7.5)
            {
                force-=0.5; /* Queda */
            }

            /* Toca a música de fundo */
            if(!al_get_sample_instance_playing(instance_theme) && !al_get_sample_instance_playing(instance_mlk))
            {
                al_play_sample_instance(instance_theme);
            }

            /* Fechar o display */
            al_wait_for_event(event_queue, &ev);

            if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
            {
                quit = true;
            }

            /* Evento de quando a tecla eh pressionada */
            if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
            {
                switch(ev.keyboard.keycode)
                {
                case ALLEGRO_KEY_ESCAPE:
                    quit = true;
                    break;
                case ALLEGRO_KEY_SPACE:
                    keys[KEY_SPACE]=true;
                    break;
                case ALLEGRO_KEY_UP:
                    keys[KEY_UP] = true;
                    if(jump == false)
                    {
                        jump = true;
                        force = gravity;
                    }
                    break;
                case ALLEGRO_KEY_LEFT:
                    keys[KEY_RIGHT]=false;
                    keys[KEY_LEFT]=true;
                    break;
                case ALLEGRO_KEY_RIGHT:
                    keys[KEY_LEFT]=false;
                    keys[KEY_RIGHT]=true;
                    break;
                case ALLEGRO_KEY_F1:
                    if(!al_get_sample_instance_playing(instance_mlk))
                    {
                        al_play_sample_instance(instance_mlk);
                        al_stop_sample_instance(instance_theme);
                    }
                    break;
                case ALLEGRO_KEY_M:
                    if(al_get_sample_instance_playing(instance_mlk))
                    {
                        al_stop_sample_instance(instance_mlk);
                    }
                    break;
                }
            }

            /* Evento de quando a tecla eh solta */
            if(ev.type == ALLEGRO_EVENT_KEY_UP)
            {
                switch(ev.keyboard.keycode)
                {
                case ALLEGRO_KEY_SPACE:
                    keys[KEY_SPACE]=false;
                    break;
                case ALLEGRO_KEY_UP:
                    keys[KEY_UP] = false;
                    break;
                case ALLEGRO_KEY_LEFT:
                    keys[KEY_LEFT]=false;
                    break;
                case ALLEGRO_KEY_RIGHT:
                    keys[KEY_RIGHT]=false;
                    break;
                }
            }

            if(ev.type == ALLEGRO_EVENT_TIMER)
            {
                if(ev.timer.source == timer_0p2)
                {
                    if((iddle == false) && (keys[KEY_RIGHT] == false) && (keys[KEY_LEFT] == false) && (jump == false))
                    {
                        iddle = true;
                    }
                }
                if(ev.timer.source == timer_1)
                {
                    stopwatch--;
                }
                if(ev.timer.source == timer_60)
                {
                    /* Posicionamento do player*/
                    player.y-=force;

                    if(keys[KEY_RIGHT])
                    {
                        player.direction = 1;
                        player.x+=player.speed;
                    }
                    if(keys[KEY_LEFT])
                    {
                        player.direction = -1;
                        player.x-=player.speed;
                    }

                    if(keys[KEY_SPACE])
                    {
                        for(i=0; i<NUM_BULLET; i++)
                        {
                            if(!al_get_sample_instance_playing(instance_playerShoot))
                            {
                                playerShoot(&player, &playerBullet[i], instance_playerShoot);
                            }
                        }
                    }


                    /*Posicionamento do Inimigo */

                    for (i=0; i<LINHA_MAX; i++)
                    {
                        for(j=0; j<COLUNA_MAX; j++)
                        {
                            if(player.x > enemy1[i][j].x + 40)
                            {
                                enemy1[i][j].direction = 1;
                            }
                            else if(player.x + 40 <= enemy1[i][j].x)
                            {
                                enemy1[i][j].direction = -1;
                            }
                        }
                    }

                    /* ~~Posicionamento do projetil~~ */

                    /* Chance do Inimigo Atirar */
                    chance_enemy_shoot = rand() % 40;
                    for (i=0; i<LINHA_MAX; i++)
                    {
                        for(j=0; j<COLUNA_MAX; j++)
                        {
                            enemyShoot(&player, &enemy1[i][j], enemyBullet, &bulletID, &bulletCount);
                        }
                    }
                    for(i=0; i<NUM_BULLET; i++)
                    {
                        if(!playerBullet[i].live)
                        {
                            playerBullet[i].direction = player.direction;
                        }

                        if(playerBullet[i].live)
                        {
                            if(playerBullet[i].direction == -1)
                            {
                                playerBullet[i].x-=playerBullet[i].speed;
                            }
                            else if(playerBullet[i].direction == 1)
                            {
                                playerBullet[i].x+=playerBullet[i].speed;
                            }
                        }
                        if(enemyBullet[i].live)
                        {
                            if(enemyBullet[i].direction == -1)
                            {
                                enemyBullet[i].x-=enemyBullet[i].speed;
                            }
                            if(enemyBullet[i].direction == 1)
                            {
                                enemyBullet[i].x+=enemyBullet[i].speed;
                            }

                        }
                    }

                    /* Prende a Camera no Personagem */
                    cameraX = player.x-(SCREEN_W/2);
                    cameraY = player.y-(SCREEN_H/2);

                    /* Fazer com que a camera nao passe dos limites do mapa */
                    if (cameraX < 0) cameraX = 0;
                    if (cameraY < 0) cameraY = 0;
                    if (cameraX > WORLD_W - SCREEN_W) cameraX = WORLD_W - SCREEN_W;
                    if (cameraY > WORLD_H - SCREEN_H) cameraY = WORLD_H - SCREEN_H;

                    /* Colisoes + check trap */
                    for (i = 0; i<LINHA_MAX; i++)
                    {
                        for(j = 0; j<COLUNA_MAX; j++)
                        {
                            for(k=0; k<NUM_BULLET; k++)
                            {
                                collision_bullet_player(&player, &enemyBullet[k], img_enemy_bullet, &bulletCount, 40, 40);
                            }
                            if(block[i][j].live == true)
                            {
                                if(mapa[i][j] == 2)
                                {
                                    collision_player_tiles(&player, &block[i][j], &jumping, img_block2);
                                }
                                if(mapa[i][j] == 3)
                                {
                                    collision_player_tiles(&player, &block[i][j], &jumping, img_block2);
                                }
                                if(mapa[i][j] == 4)
                                {
                                    check_trap(&player, &block[i][j], &enemy1[i][j], 4);
                                    collision_player_tiles(&player, &block[i][j], &jumping, img_block2);
                                }
                                if(mapa[i][j] == 5)
                                {
                                    collision_player_tiles(&player, &block[i][j], &jumping, img_block2);
                                }
                                for(k=0; k<NUM_BULLET; k++)
                                {
                                    collision_bullet_tiles(&playerBullet[k], &block[i][j], img_player_bullet, img_block2, 0, &bulletCount);
                                    collision_bullet_tiles(&enemyBullet[k], &block[i][j], img_player_bullet, img_block2, 1, &bulletCount);
                                }
                            }
                            if(block[i][j].live == false)
                            {
                                if(mapa[i][j] == 5)
                                {
                                    check_trap(&player, &block[i][j], &enemy1[i][j], 5);
                                }
                                if(mapa[i][j] == 6)
                                {
                                    collision_player_enemy(&player, &enemy1[i][j], 40, 40);

                                    for(k=0; k<NUM_BULLET; k++)
                                    {
                                        collision_bullet_enemy(&playerBullet[k], &enemy1[i][j], img_player_bullet, 40, 40);
                                    }
                                }
                                if(mapa[i][j] == 7)
                                {
                                    check_trap(&player, &block[i][j], &enemy1[i][j], 7);
                                    collision_player_enemy(&player, &enemy1[i][j], 40, 40);

                                    for(k=0; k<NUM_BULLET; k++)
                                    {
                                        collision_bullet_enemy(&playerBullet[k], &enemy1[i][j], img_player_bullet, 40, 40);
                                    }
                                }
                                if(mapa[i][j] == 8)
                                {
                                    check_trap(&player, &block[i][j], &enemy1[i][j], 8);
                                    collision_player_enemy(&player, &enemy1[i][j], 40, 40);

                                    for(k=0; k<NUM_BULLET; k++)
                                    {
                                        collision_bullet_enemy(&playerBullet[k], &enemy1[i][j], img_player_bullet, 40, 40);
                                    }
                                }
                                if(mapa[i][j] == 9)
                                {
                                    check_trap(&player, &block[i][j], &enemy1[i][j], 9);
                                    collision_player_enemy(&player, &enemy1[i][j], 40, 40);

                                    for(k=0; k<NUM_BULLET; k++)
                                    {
                                        collision_bullet_enemy(&playerBullet[k], &enemy1[i][j], img_player_bullet, 40, 40);
                                    }
                                }
                            }
                        }
                    }

                    collision_player_wall(&player, &jumping, img_block1);

                    /* ~~Desenha o Background~~ */
                    al_draw_bitmap(img_background0, 0 - cameraX, 0 - cameraY, 0);

                    /* ~~Animação dos inimigos~~ */
                    if(++anim_enemy1.frameCount >= anim_enemy1.frameDelay)
                    {
                        if(++anim_enemy1.curFrame >= anim_enemy1.maxFrame)
                        {
                            anim_enemy1.curFrame = 0;
                        }
                        anim_enemy1.frameCount = 0;
                    }

                    /* ~~Desenha os Blocos/Inimigos~~ */
                    for (i = 0; i<LINHA_MAX; i++)
                    {
                        for(j = 0; j<COLUNA_MAX; j++)
                        {
                            if(mapa[i][j] == 2 && block[i][j].live == true)
                            {
                                al_draw_bitmap(img_block1, block[i][j].x - cameraX, block[i][j].y - cameraY, 0);
                            }
                            if(mapa[i][j] == 3 && block[i][j].live == true)
                            {
                                al_draw_bitmap(img_block2, block[i][j].x - cameraX, block[i][j].y - cameraY, 0);
                            }
                            if(mapa[i][j] == 4 && block[i][j].live == true)
                            {
                                al_draw_bitmap(img_block2, block[i][j].x - cameraX, block[i][j].y - cameraY, 0);
                            }
                            if(mapa[i][j] == 5 && block[i][j].live == true)
                            {
                                al_draw_bitmap(img_block2, block[i][j].x - cameraX, block[i][j].y - cameraY, 0);
                            }
                            if((mapa[i][j] == 6 || mapa[i][j] == 7 || mapa[i][j] == 8) && (enemy1[i][j].direction == -1) && (enemy1[i][j].live == true))
                            {
                                al_draw_bitmap_region(img_enemy1, anim_enemy1.curFrame * anim_enemy1.frameWidth, 0, anim_enemy1.frameWidth, anim_enemy1.frameHeight, enemy1[i][j].x - cameraX, enemy1[i][j].y - cameraY, 0);
                            }
                            if((mapa[i][j] == 6 || mapa[i][j] == 7 || mapa[i][j] == 8) && (enemy1[i][j].direction == 1) && (enemy1[i][j].live == true))
                            {
                                al_draw_bitmap_region(img_enemy1, anim_enemy1.curFrame * anim_enemy1.frameWidth, 0, anim_enemy1.frameWidth, anim_enemy1.frameHeight, enemy1[i][j].x - cameraX, enemy1[i][j].y - cameraY, ALLEGRO_FLIP_HORIZONTAL);
                            }
                            if(mapa[i][j] == 9 && enemy1[i][j].live == true)
                            {
                                al_draw_bitmap_region(img_boss1, anim_enemy1.curFrame * anim_enemy1.frameWidth, 0, anim_enemy1.frameWidth, anim_enemy1.frameHeight, enemy1[i][j].x - cameraX, enemy1[i][j].y - cameraY, 0);
                            }
                        }
                    }

                    /* ~~Desenho do player~~ */

                    /* Player parado */
                    if(iddle == true)
                    {
                        if(++immobile.frameCount >= immobile.frameDelay)
                        {
                            if(++immobile.curFrame >= immobile.maxFrame)
                            {
                                immobile.curFrame = 0;
                                iddle = false;
                            }
                            immobile.frameCount = 0;
                        }
                    }
                    if((keys[KEY_SPACE] == false) && (jump == false) && ((!keys[KEY_LEFT] && player.direction == -1) || player.x == 64))
                    {
                        al_draw_bitmap_region(img_player_immobile, immobile.curFrame * immobile.frameWidth, 0, immobile.frameWidth, immobile.frameHeight, player.x - cameraX, player.y - cameraY, ALLEGRO_FLIP_HORIZONTAL);
                    }
                    if((keys[KEY_SPACE] == false) && (jump == false) && ((!keys[KEY_RIGHT] && player.direction == 1) || player.x == WORLD_W - (64-immobile.frameWidth)))
                    {
                        al_draw_bitmap_region(img_player_immobile, immobile.curFrame * immobile.frameWidth, 0, immobile.frameWidth, immobile.frameHeight, player.x - cameraX, player.y - cameraY, 0);
                    }
                    if((keys[KEY_SPACE] == true) && (jump == false) && ((!keys[KEY_LEFT] && player.direction == -1)))
                    {
                        al_draw_bitmap(img_player_immobile_shoot, player.x - cameraX, player.y - cameraY, ALLEGRO_FLIP_HORIZONTAL);
                    }
                    if((keys[KEY_SPACE] == true) && (jump == false) && ((!keys[KEY_RIGHT] && player.direction == 1)))
                    {
                        al_draw_bitmap(img_player_immobile_shoot, player.x - cameraX, player.y - cameraY, 0);
                    }

                    /* Player andando */
                    if(++walking.frameCount >= walking.frameDelay)
                    {
                        if(++walking.curFrame >= walking.maxFrame)
                        {
                            walking.curFrame = 0;
                        }
                        walking.frameCount = 0;
                    }

                    if(keys[KEY_SPACE] == false)
                    {
                        if(jump == false && keys[KEY_LEFT] && player.direction == -1)
                        {
                            al_draw_bitmap_region(img_player_walking, walking.curFrame * walking.frameWidth, 0, walking.frameWidth, walking.frameHeight, player.x - cameraX, player.y - cameraY, ALLEGRO_FLIP_HORIZONTAL);
                        }
                        if(jump == false && keys[KEY_RIGHT] && player.direction == 1)
                        {
                            al_draw_bitmap_region(img_player_walking, walking.curFrame * walking.frameWidth, 0, walking.frameWidth, walking.frameHeight, player.x - cameraX, player.y - cameraY, 0);
                        }
                    }
                    if(keys[KEY_SPACE] == true)
                    {
                        if(jump == false && keys[KEY_LEFT] && player.direction == -1)
                        {
                            al_draw_bitmap_region(img_player_walking_shoot, walking.curFrame * walking.frameWidth, 0, walking.frameWidth, walking.frameHeight, player.x - cameraX, player.y - cameraY, ALLEGRO_FLIP_HORIZONTAL);
                        }
                        if(jump == false && keys[KEY_RIGHT] && player.direction == 1)
                        {
                            al_draw_bitmap_region(img_player_walking_shoot, walking.curFrame * walking.frameWidth, 0, walking.frameWidth, walking.frameHeight, player.x - cameraX, player.y - cameraY, 0);
                        }
                    }

                    /* Player pulando */
                    if(jump == true)
                    {
                        if(++jumping.frameCount >= jumping.frameDelay)
                        {
                            if(++jumping.curFrame >= jumping.maxFrame)
                            {
                                jumping.curFrame = 0;
                            }
                            jumping.frameCount = 0;
                        }

                        if(keys[KEY_SPACE] == false)
                        {
                            if(player.direction == -1)
                            {
                                al_draw_bitmap_region(img_player_jump, jumping.curFrame * jumping.frameWidth, 0, jumping.frameWidth, jumping.frameHeight, player.x - cameraX, player.y - cameraY, ALLEGRO_FLIP_HORIZONTAL);
                            }
                            if(player.direction == 1)
                            {
                                al_draw_bitmap_region(img_player_jump, jumping.curFrame * jumping.frameWidth, 0, jumping.frameWidth, jumping.frameHeight, player.x - cameraX, player.y - cameraY, 0);
                            }
                        }
                        else if(keys[KEY_SPACE] == true)
                        {
                            if(player.direction == -1)
                            {
                                al_draw_bitmap_region(img_player_jump_shoot, jumping.curFrame * jumping.frameWidth, 0, jumping.frameWidth, jumping.frameHeight, player.x - cameraX, player.y - cameraY, ALLEGRO_FLIP_HORIZONTAL);
                            }
                            if(player.direction == 1)
                            {
                                al_draw_bitmap_region(img_player_jump_shoot, jumping.curFrame * jumping.frameWidth, 0, jumping.frameWidth, jumping.frameHeight, player.x - cameraX, player.y - cameraY, 0);
                            }
                        }

                    }

                    /* ~~Desenho dos projeteis~~ */
                    for(i=0; i<NUM_BULLET; i++)
                    {
                        if(playerBullet[i].live)
                        {
                            al_draw_bitmap(img_player_bullet, playerBullet[i].x - cameraX, playerBullet[i].y - cameraY, 0);
                        }
                        if(enemyBullet[i].live)
                        {
                            al_draw_bitmap(img_enemy_bullet, enemyBullet[i].x - cameraX, enemyBullet[i].y - cameraY, 0);
                        }
                    }

                    /* Pontuacao e Porcentagem de Vida */
                    al_draw_bitmap(img_heart, 0, 0, 0);
                    al_draw_textf(fonte16, al_map_rgb(255, 255, 255), 20, 0, ALLEGRO_ALIGN_LEFT, ("%03d"), player.life);

                    al_draw_bitmap(img_medal, 64, 0, 0);
                    al_draw_textf(fonte16, al_map_rgb(255, 255, 255), 80, 0, ALLEGRO_ALIGN_LEFT, ("%04d"), scores);

                    al_draw_bitmap(img_clock, 144, 0, 0);
                    al_draw_textf(fonte16, al_map_rgb(255, 255, 255), 160, 0, ALLEGRO_ALIGN_LEFT, ("%03d"), stopwatch);
                }

                /* Termino da Fase */
                if(enemyKilled == ENEMY_MAX) /* You Win! */
                {
                    scores = scores + (25 * stopwatch) + (10*player.life);
                    gamestate = 2;
                }
                if(player.life <= 0 || stopwatch == 0) /* Game Over! */
                {
                    gamestate = 3;
                }

                /* Troca o display */
                al_flip_display();
            }
            break;
        case 2:
            al_wait_for_event(event_queue, &ev);

            if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) /* Faz com que o jogo feche ao clicar no botao "X" do display */
            {
                quit = true;
            }

            if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
            {
                if(ev.keyboard.keycode == ALLEGRO_KEY_ESCAPE) /* Faz com que o jogo feche ao pressionar esc */
                {
                    quit = true;
                }
            }
            if(ev.type == ALLEGRO_EVENT_TIMER) /* Mostrar mensagens na tela */
            {
                if(ev.timer.source == timer_60)
                {
                    al_clear_to_color(al_map_rgb(0,0,0));
                    al_draw_bitmap(img_you_win, 0, 0, 0);
                    al_draw_textf(fonte16, al_map_rgb(0, 0, 0), SCREEN_W/2, SCREEN_H - 48, ALLEGRO_ALIGN_CENTRE, "Seus pontos: %d", scores);
                    al_draw_textf(fonte16, al_map_rgb(0, 0, 0), SCREEN_W/2, SCREEN_H - 32, ALLEGRO_ALIGN_CENTRE, "Pressione Esc para sair");
                    al_flip_display();
                }
            }
            break;

        case 3:
            al_wait_for_event(event_queue, &ev);

            if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) /* Faz com que o jogo feche ao clicar no botao "X" do display */
            {
                quit = true;
            }

            if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
            {
                if(ev.keyboard.keycode == ALLEGRO_KEY_ESCAPE) /* Faz com que o jogo feche ao pressionar esc */
                {
                    quit = true;
                }
            }
            if(ev.type == ALLEGRO_EVENT_TIMER) /* Mostrar mensagens na tela */
            {
                if(ev.timer.source == timer_60)
                {
                    al_clear_to_color(al_map_rgb(0,0,0));
                    al_draw_bitmap(img_game_over, 0, 0, 0);
                    al_draw_textf(fonte16, al_map_rgb(255, 0, 0), SCREEN_W/2, SCREEN_H - 48, ALLEGRO_ALIGN_CENTRE, "Seus pontos: %d", scores);
                    al_draw_textf(fonte16, al_map_rgb(255, 0, 0), SCREEN_W/2, SCREEN_H - 32, ALLEGRO_ALIGN_CENTRE, "Pressione Esc para sair");
                    al_flip_display();
                }
            }
            break;
        }
    }
    /* Destruindo as variaveis */
    al_destroy_display(display);
    al_destroy_event_queue(event_queue);
    al_destroy_timer(timer_0p2);
    al_destroy_timer(timer_1);
    al_destroy_timer(timer_60);

    al_destroy_bitmap(img_home_screen);
    al_destroy_bitmap(img_dica_h1n1);
    al_destroy_bitmap(img_background0);

    al_destroy_bitmap(img_heart);
    al_destroy_bitmap(img_medal);
    al_destroy_bitmap(img_clock);
    al_destroy_bitmap(img_block1);
    al_destroy_bitmap(img_block2);

    al_destroy_bitmap(img_player_walking);
    al_destroy_bitmap(img_player_walking_shoot);
    al_destroy_bitmap(img_player_immobile);
    al_destroy_bitmap(img_player_immobile_shoot);
    al_destroy_bitmap(img_player_jump);
    al_destroy_bitmap(img_player_jump_shoot);
    al_destroy_bitmap(img_player_bullet);

    al_destroy_bitmap(img_enemy1);
    al_destroy_bitmap(img_boss1);
    al_destroy_bitmap(img_enemy_bullet);

    al_destroy_sample(spl_theme);
    al_destroy_sample(spl_playerShoot);
    al_destroy_sample(spl_mlk);

    return 0;
}
コード例 #8
0
int main(int argc, char **argv) {
	ALLEGRO_DISPLAY *display = NULL;
	ALLEGRO_EVENT_QUEUE *event_queue = NULL;
	ALLEGRO_TIMER *timer = NULL;
	bool redraw = true;
	bool doexit = false;
	bool key[4] = { false, false, false, false };

	if (!al_init()) {
		fprintf(stderr, "failed to initialize allegro!\n");
		return -1;
	}
	if (!al_init_image_addon()) {
		al_show_native_message_box(display, "Error", "Error", "Failed to initialize al_init_image_addon!",
			NULL, ALLEGRO_MESSAGEBOX_ERROR);
		return 0;
	}
	if (!al_install_keyboard()) {
		fprintf(stderr, "failed to initialize the keyboard!\n");
		return -1;
	}

	collider collide;
	std::vector<bouncer *> balls;
	std::vector<tile*> tiles;
	std::vector<move *> moveVector;
	ALLEGRO_BITMAP *image = NULL;
	image = al_load_bitmap("megamanss.png");
	
	if (!image) {
		al_show_native_message_box(display, "Error", "Error", "Failed to load image!",
			NULL, NULL);
		al_destroy_display(display);
		return 0;
	}
	
	for (int i = 0; i < NUM_BALLS; i++)
	{
		bouncer* a;
		a = new bouncer(30 * i, 30 * i, 10, i / 5.0, i);

		balls.push_back(a);
		//  collide.add(a);
	}
	for (int i = 0; i < NUM_TILES; i++)
	{
		tile * a;
		//     std::cout << i%16 << "\t" << i/12 << "\n";
		a = new tile(TILE_SIZE * (i % 16), TILE_SIZE * (i / 16), TILE_SIZE);
		tiles.push_back(a);
		//  collide.add(a);
	}
	animator *anim = new animator("megamanss.png", "Source/megamanss.txt");
	//ballGenerator *bg = new ballGenerator(100,100,&collide,&balls);
	//PokemonFactory pf;

	pokemon * p = new pokemon("treeko", 1, 2, 3, 4);
	MoveFactory *mf = new MoveFactory();
	move *m = mf->Create(SWAG, "swag", p, p, 0, 400, 200);
	moveVector.push_back(m);
	collide.add(p);
	collide.add(m);
	//    bouncer b(20,20,32,3,4);
	//   bouncer c(30,30,32,4,4);
	timer = al_create_timer(1.0 / FPS);
	if (!timer) {
		fprintf(stderr, "failed to create timer!\n");
		return -1;
	}

	display = al_create_display(SCREEN_W, SCREEN_H);
	if (!display) {
		fprintf(stderr, "failed to create display!\n");
		al_destroy_timer(timer);
		return -1;
	}
	

	al_set_target_bitmap(al_get_backbuffer(display));

	event_queue = al_create_event_queue();
	if (!event_queue) {
		fprintf(stderr, "failed to create event_queue!\n");

		al_destroy_display(display);
		al_destroy_timer(timer);
		return -1;
	}

	al_register_event_source(event_queue, al_get_display_event_source(display));

	al_register_event_source(event_queue, al_get_timer_event_source(timer));

	al_register_event_source(event_queue, al_get_keyboard_event_source());

	al_clear_to_color(al_map_rgb(0, 0, 0));

	al_flip_display();

	al_start_timer(timer);



	std::cout << "\nDONE WITH INIT\n";
	while (!doexit)
	{
		ALLEGRO_EVENT ev;
		al_wait_for_event(event_queue, &ev);

		if (ev.type == ALLEGRO_EVENT_TIMER) {
			collide.update();
			anim->update();
			for (int i = 0; i < moveVector.size(); i++)
			{
				std::cout << "moveVector.size()" << moveVector.size() << "\n";
				if (moveVector[i]->markForDeath == true)
				{

					delete moveVector[i];
					moveVector.erase(moveVector.begin() + i);
					i--;

				}
				else
				{
					moveVector[i]->update();
				}
			}
			/*
			if (m != NULL && m->markForDeath == true)
			{
			std::cout << "deleting object";
			delete m;
			m = NULL;
			}
			else if (m!= NULL)

			m->update();
			*/
			for (int i = 0; i < balls.size(); i++)
			{
				if (balls[i]->markForDeath == true)
				{
					collide.remove(balls[i]);
					delete balls[i];
					balls.erase(balls.begin() + i);
					i--;
				}
				else
				{
					balls[i]->update();
				}

			}
			
			if (key[KEY_UP]) {
				anim->switchAnimations(1);
			}

			if (key[KEY_DOWN]) {
				anim->switchAnimations(2);
			}

			if (key[KEY_LEFT]) {
				anim->switchAnimations(3);
			}

			if (key[KEY_RIGHT]) {
				anim->switchAnimations(4);
			}
			
			// for (int i = 0; i < tiles.size(); i++)
			//   tiles[i]->update();

			p->update();
			//bg->update();
			redraw = true;
		}



		else if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
			break;
		}
		else if (ev.type == ALLEGRO_EVENT_KEY_DOWN) {
			switch (ev.keyboard.keycode) {
			case ALLEGRO_KEY_UP:
				key[KEY_UP] = true;
				break;

			case ALLEGRO_KEY_DOWN:
				key[KEY_DOWN] = true;
				break;

			case ALLEGRO_KEY_LEFT:
				key[KEY_LEFT] = true;
				break;

			case ALLEGRO_KEY_RIGHT:
				key[KEY_RIGHT] = true;
				break;
			}
		}
		else if (ev.type == ALLEGRO_EVENT_KEY_UP) {
			switch (ev.keyboard.keycode) {
			case ALLEGRO_KEY_UP:
				key[KEY_UP] = false;
				break;

			case ALLEGRO_KEY_DOWN:
				key[KEY_DOWN] = false;
				break;

			case ALLEGRO_KEY_LEFT:
				key[KEY_LEFT] = false;
				break;

			case ALLEGRO_KEY_RIGHT:
				key[KEY_RIGHT] = false;
				break;

			case ALLEGRO_KEY_ESCAPE:
				doexit = true;
				break;
			}
		}
		if (redraw && al_is_event_queue_empty(event_queue)) {
			redraw = false;
			al_set_target_bitmap(al_get_backbuffer(display));
			al_clear_to_color(al_map_rgb(0, 0, 0));
			// al_draw_bitmap(image,200,200,0);

			for (int i = 0; i < moveVector.size(); i++)
				moveVector[i]->draw();
			/*
			for (int i = 0; i < tiles.size(); i++)
			tiles[i]->draw();
			for (int i = 0; i < balls.size(); i++)
			balls[i]->draw();*/
			anim->draw(100, 100);
			p->draw();

			
		
			al_flip_display();
		}
	}
	for (int i = 0; i < tiles.size(); i++)
		delete tiles[i];
	for (int i = 0; i < balls.size(); i++)
		delete balls[i];


	al_destroy_timer(timer);
	al_destroy_display(display);
	al_destroy_event_queue(event_queue);

	return 0;
}
コード例 #9
0
ファイル: musica.c プロジェクト: nahuelaguilar93/TELEFONO
void corrermusica(void){
    const int CANTICANCIONES=5;
    ALLEGRO_TIMER *timer = NULL;
    ALLEGRO_EVENT_QUEUE *queue=NULL;
    ALLEGRO_BITMAP *icons[CANTICANCIONES];
    boton items[CANTICANCIONES];
    void (*p2buttonf[CANTICANCIONES])(void);
    ALLEGRO_FONT *font=NULL;
    
    queue = al_create_event_queue(); 
    timer = al_create_timer(1.0/FPS); //genero un timer para trabajar en 60 fps
    bool redraw=false;
    
    //pajaros
    icons[0]=al_load_bitmap("pajaros.png");
    botones(&items[0],30,70, 150, 200);
    p2buttonf[0]=pajaros;
    
    //clorofila
    icons[1]=al_load_bitmap("clorofila.png");
    botones(&items[1],230,70, 150, 200);
    p2buttonf[1]=clorofila;
    
    //brisa
    icons[2]=al_load_bitmap("brisa.png");
    botones(&items[2],30,330, 150, 200);
    p2buttonf[2]=brisa;
    
    //alfred
    icons[3]=al_load_bitmap("graciasalfred.png");
    botones(&items[3],230,330, 150, 200);
    p2buttonf[3]=graciasalfred;

    //mute
    icons[4]=al_load_bitmap("mute.png");
    botones(&items[4],340,OFFSETDOWN-70, 64, 64);
    p2buttonf[4]=mute;
    
    //font 
    font=al_load_font("font.ttf",30,0);
    
    //register events
    al_register_event_source(queue, al_get_display_event_source(display));
    al_register_event_source(queue, al_get_mouse_event_source());
    al_register_event_source(queue, al_get_timer_event_source(timer));
    //timer starts
    al_start_timer(timer);
    
    while(!doexit && !exitmenu) //  loop
    {
        ALLEGRO_EVENT ev;
        al_wait_for_event(queue, &ev); // espero a timer, salida o keyboard
        if(ev.type == ALLEGRO_EVENT_TIMER) 
            redraw = true; // si es el timer de refresco, redibujo
        salio(ev);
        inicio(ev);
        presionobotones(ev, items, p2buttonf,CANTICANCIONES);
        if(redraw && !exitmenu){ // si hay que redibujar
            drawfondo();
            al_draw_text(font, al_map_rgb(171,130,255), 10, OFFSETDOWN-55, ALLEGRO_ALIGN_LEFT,"Musica por Motoneta");
            drawbotones(items, icons,CANTICANCIONES);
            redraw=false;
            al_flip_display(); //flipeo 
        }
    }
    
    al_destroy_event_queue(queue);
    al_destroy_timer(timer);
    al_destroy_bitmap(icons[0]);
    al_destroy_bitmap(icons[1]);
    al_destroy_bitmap(icons[2]);
    al_destroy_bitmap(icons[3]);
    
    exitmenu=false;
}
コード例 #10
0
ファイル: ex_threads2.c プロジェクト: BorisCarvajal/allegro5
int main(int argc, char **argv)
{
   ALLEGRO_THREAD *thread[NUM_THREADS];
   ALLEGRO_DISPLAY *display;
   ALLEGRO_TIMER *timer;
   ALLEGRO_EVENT_QUEUE *queue;
   ALLEGRO_EVENT event;
   bool need_draw;
   int i;

   (void)argc;
   (void)argv;

   for (i = 0; i < 256; i++) {
      sin_lut[i] = 128 + (int) (127.0 * sin(i / 8.0));
   }

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

   al_install_keyboard();
   al_install_mouse();
   display = al_create_display(W * IMAGES_PER_ROW,
      H * NUM_THREADS / IMAGES_PER_ROW);
   if (!display) {
      abort_example("Error creating display\n");
   }
   timer = al_create_timer(1.0/3);
   if (!timer) {
      abort_example("Error creating timer\n");
   }
   queue = al_create_event_queue();
   if (!queue) {
      abort_example("Error creating event queue\n");
   }
   al_register_event_source(queue, al_get_display_event_source(display));
   al_register_event_source(queue, al_get_keyboard_event_source());
   al_register_event_source(queue, al_get_mouse_event_source());
   al_register_event_source(queue, al_get_timer_event_source(timer));

   /* Note:
    * Right now, A5 video displays can only be accessed from the thread which
    * created them (at least for OpenGL). To lift this restriction, we could
    * keep track of the current OpenGL context for each thread and make all
    * functions accessing the display check for it.. not sure it's worth the
    * additional complexity though.
    */
   al_set_new_bitmap_format(ALLEGRO_PIXEL_FORMAT_RGB_888);
   al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP);
   for (i = 0; i < NUM_THREADS; i++) {
      thread_info[i].bitmap = al_create_bitmap(W, H);
      if (!thread_info[i].bitmap) {
         goto Error;
      }
      thread_info[i].mutex = al_create_mutex();
      if (!thread_info[i].mutex) {
         goto Error;
      }
      thread_info[i].cond = al_create_cond();
      if (!thread_info[i].cond) {
         goto Error;
      }
      thread_info[i].is_paused = false;
      thread_info[i].random_seed = i;
      thread[i] = al_create_thread(thread_func, &thread_info[i]);
      if (!thread[i]) {
         goto Error;
      }
   }
   set_target(0, -0.56062033041600878303, -0.56064322926933807256);
   set_target(1, -0.57798076669230014080, -0.63449861991138123418);
   set_target(2,  0.36676836392830602929, -0.59081385302214906030);
   set_target(3, -1.48319283039401317303, -0.00000000200514696273);
   set_target(4, -0.74052910500707636032,  0.18340899525730713915);
   set_target(5,  0.25437906525768350097, -0.00046678223345789554);
   set_target(6, -0.56062033041600878303,  0.56064322926933807256);
   set_target(7, -0.57798076669230014080,  0.63449861991138123418);
   set_target(8,  0.36676836392830602929,  0.59081385302214906030);

   for (i = 0; i < NUM_THREADS; i++) {
      al_start_thread(thread[i]);
   }
   al_start_timer(timer);

   need_draw = true;
   while (true) {
      if (need_draw && al_is_event_queue_empty(queue)) {
         show_images();
         need_draw = false;
      }

      al_wait_for_event(queue, &event);
      if (event.type == ALLEGRO_EVENT_TIMER) {
         need_draw = true;
      }
      else if (event.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) {
         int n = (event.mouse.y / H) * IMAGES_PER_ROW + (event.mouse.x / W);
         if (n < NUM_THREADS) {
            double x = event.mouse.x - (event.mouse.x / W) * W;
            double y = event.mouse.y - (event.mouse.y / H) * H;
            /* Center to the mouse click position. */
            if (thread_info[n].is_paused) {
               thread_info[n].target_x = x / W - 0.5;
               thread_info[n].target_y = y / H - 0.5;
            }
            toggle_pausedness(n);
         }
      }
      else if (event.type == ALLEGRO_EVENT_DISPLAY_EXPOSE) {
         need_draw = true;
      }
      else if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
         break;
      }
      else if (event.type == ALLEGRO_EVENT_KEY_DOWN) {
         if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) {
            break;
         }
         need_draw = true;
      }
   }

   for (i = 0; i < NUM_THREADS; i++) {
      /* Set the flag to stop the thread.  The thread might be waiting on a
       * condition variable, so signal the condition to force it to wake up.
       */
      al_set_thread_should_stop(thread[i]);
      al_lock_mutex(thread_info[i].mutex);
      al_broadcast_cond(thread_info[i].cond);
      al_unlock_mutex(thread_info[i].mutex);

      /* al_destroy_thread() implicitly joins the thread, so this call is not
       * strictly necessary.
       */
      al_join_thread(thread[i], NULL);
      al_destroy_thread(thread[i]);
   }

   al_destroy_event_queue(queue);
   al_destroy_timer(timer);
   al_destroy_display(display);

   return 0;

Error:

   return 1;
}
コード例 #11
0
ファイル: main.cpp プロジェクト: kruci/Juicy-Plebs
int main(int argc, char *argv[])
{
    bool windowed = false;
    float rescale = 1.0f;
    std::string arg;
    if(argc > 1)
    {
        arg = argv[1];
        if(arg == "--help")
        {
            std::cout << "-s {scale} for running in windowed mode and scaled (standart size is 1440*810)" << std::endl;
            return 0;
        }
        else if(arg == "-s")
        {
            if( argc > 2)
            {
                arg = argv[2];
                rescale = atof(argv[2]);
            }
            windowed = true;
        }
    }


    /**initialize allegro*/
    if(!al_init()){error_message("al_init()");return 33;}
    if(!al_init_primitives_addon()){error_message("al_init_primitives_addon()");return 33;}
    //if(!al_install_keyboard()){error_message("al_install_keyboard()");return 33;} //no use for keyboard in this game
    if(!al_install_mouse()){error_message("al_install_mouse()");return 33;}
    if(!al_init_image_addon()){error_message("al_init_image_addon()");return 33;}
    al_init_font_addon(); // returns void
    if(!al_init_ttf_addon()){error_message("al_init_ttf_addon()");return 33;}
    //audio
    if(al_install_audio() == true)
    {
        if(al_init_acodec_addon() == true){}
        else
        {
            error_message("al_init_acodec_addon() - cant initialize audio codec");
            global::audio = false;
            global::sound_card = false;
        }
    }
    else
    {
        error_message("al_install_audio() - cant found sound device");
        global::audio = false;
        global::sound_card = false;
    }

    /**Some allegro variables*/
    ALLEGRO_DISPLAY *display = nullptr;
    ALLEGRO_EVENT_QUEUE *event_queue = nullptr;
    ALLEGRO_TIMER *timer = nullptr;
    ALLEGRO_BITMAP *logo = nullptr;

    /**Display preparation*/
    bool supported_ratio = true;
    ALLEGRO_MONITOR_INFO mon_info;
    al_get_monitor_info(0, &mon_info);
    global::sHeight = mon_info.y2 - mon_info.y1; //gets monitor size in pixels
    global::sWidth = mon_info.x2 - mon_info.x1;
    global::aspectratio = round( ((float)global::sWidth / (float)global::sHeight) * 100.0f) / 100.0f; //gets aspectratio
    if(global::aspectratio == 1.78f){global::xratio = 16; global::yratio = 9;}      // 16:9 screen ration
    else if(global::aspectratio == 1.6f){global::xratio = 16; global::yratio = 10;} // 16:10
    else if(global::aspectratio == 1.33f){global::xratio = 4; global::yratio = 3;}  // 4:3
    else{supported_ratio = false;}
    global::dHeight = global::dWidth  / global::xratio * global::yratio;
    global::xscale = (float)global::sWidth / (float)global::dWidth;
    global::yscale = (float)global::sHeight / (float)global::dHeight;

    /**display creation*/
    al_set_new_bitmap_flags(ALLEGRO_MAG_LINEAR | ALLEGRO_MIN_LINEAR); // Thanks to this, magnified fonts dont look retarted, and game is fast (hopefully) :D
    if(windowed == true || supported_ratio == false)
    {
        supported_ratio = true;
        al_set_new_display_flags(ALLEGRO_WINDOWED | ALLEGRO_OPENGL);
        global::xscale = rescale;
        global::yscale = rescale;
        global::dWidth = 1440;
        global::dHeight = 810;
        display = al_create_display(global::dWidth*rescale, global::dHeight*rescale);
    }
    else
    {
        al_set_new_display_flags(ALLEGRO_FULLSCREEN_WINDOW | ALLEGRO_OPENGL);
        display = al_create_display(global::dWidth, global::dHeight);
    }
    if(display == nullptr){error_message("al_create_display()"); return 1;}
    al_set_window_title(display, "Este neviem meno, ale asi neco so zemiakom");

    /**logo*/
    logo = al_load_bitmap("resources/graphics/logo.png");
    if(logo == nullptr){error_message("resources/graphics/logo.png not found");}
    else{ al_set_display_icon(display, logo);}


    /**Transformation*/
    al_identity_transform(&global::trans);
    if(supported_ratio == true)
    {
        al_scale_transform(&global::trans, global::xscale, global::yscale);
    }
    else
    {
        error_message("Unsupported monitor type - upgrade you monitor pls");
        float scale_backup_plan = (global::xscale > global::yscale ? global::yscale : global::xscale);
        global::xscale = scale_backup_plan;
        global::yscale = scale_backup_plan;
        al_scale_transform(&global::trans, global::xscale, global::yscale);
    }
    al_use_transform(&global::trans);

    /**timer*/
    timer = al_create_timer(1.0f/global::FPS);
    if(timer == nullptr){error_message("al_create_timer()"); return 44;}
    bool redraw = true;

    /**even que*/
    event_queue = al_create_event_queue();
    if(event_queue == nullptr){error_message("al_create_event_queue()"); return 44;}

    /**registering event sources*/
    al_register_event_source(event_queue, al_get_display_event_source(display));
    al_register_event_source(event_queue, al_get_timer_event_source(timer));
    al_register_event_source(event_queue, al_get_mouse_event_source());

    al_start_timer(timer);

    rguil::mouse_state = &global::mouse_state;

    global::audio_player = new AudioHandler(10);

    #ifdef _SOUND_TEST
    ALLEGRO_SAMPLE *s = al_load_sample("resources/music/Fuck_This_Shit_Im_Out.wav");
    ALLEGRO_SAMPLE_INSTANCE *si = al_create_sample_instance(s);
    global::audio_player->global_sounds.push_back(si);
    global::audio_player->Play_sample_instance(&si, ALLEGRO_PLAYMODE_LOOP);
    #endif // _SOUND_TEST

    #ifdef _FPS
    ALLEGRO_FONT *fps_font = nullptr;
    fps_font = al_load_font("resources/fonts/Asimov.otf", 12,0);
    int counter = 0;
    time_t tsttme2 = time(nullptr), tsttme = time(nullptr);
    int fps = 0;
    #endif // FPS

    global::save = new GameSave();
    ScreenMain *SCMain = new ScreenMain();
    global::audio_b = new Button("resources/fonts/Calibri.ttf", 1240, global::dHeight -65, 1240 + 40, global::dHeight - 25,
                                 "", al_map_rgba(0,0,0,0),
                                 ( global::audio == true ? MusicON : MusicOFF));

    /**Main loop*/ //forced 30 FPS, drawing and computing in same thread
    while(global::loop == true)
    {
        ALLEGRO_EVENT ev;
        al_wait_for_event(event_queue, &ev);

        al_get_mouse_state(&global::mouse_state);

        if(ev.type == ALLEGRO_EVENT_TIMER)
        {
            redraw = true;
        }
        else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
        {
            break;
        }

        /**Take event input here*/
        if(global::audio_b->Input(ev, global::xscale, global::yscale) == 2)
        {
            global::audio_b->unclick();
            global::audio = (global::audio == true ? false : true);

            if(global::audio == true)
            {
                al_destroy_bitmap(global::audio_b->bmp);
                global::audio_b->bmp = al_load_bitmap(MusicON);
                global::audio_player->Mute_sample_instances(false);
            }
            else
            {
                al_destroy_bitmap(global::audio_b->bmp);
                global::audio_b->bmp = al_load_bitmap(MusicOFF);
                global::audio_player->Mute_sample_instances(true);
            }
        }

        SCMain->Input(ev, global::xscale, global::yscale);
        /**---------------------*/

        #ifdef _FPS
        tsttme2 = time(&tsttme2);
        if(difftime(tsttme2,tsttme) >= 1.0f)
        {
            tsttme = time(&tsttme);
            fps = counter;
            counter = 0;
        }
        #endif // FPS


        if(redraw == true && al_is_event_queue_empty(event_queue))
        {
            redraw = false;
            al_clear_to_color(al_map_rgb(0,0,0));


            /**Draw and compute here*/
            SCMain->Print();
            global::audio_b->Print();
            /**---------------------*/

            #ifdef _FPS
            counter++;
            al_draw_text(fps_font, al_map_rgb(255,0,0), 0.0f,0.0f, 0, std::to_string(fps).c_str());
            #endif // FPS
            al_flip_display();
        }
    }
    #ifdef _SOUND_TEST
    global::audio_player->Stop_sample_instances();
    global::audio_player->global_sounds.erase(global::audio_player->global_sounds.begin());
    al_destroy_sample_instance(si);
    al_destroy_sample(s);
    #endif // _SOUND_TEST

    delete global::audio_b;
    delete SCMain;
    delete global::save;
    delete global::audio_player;

    al_destroy_timer(timer);
    al_destroy_display(display);
    al_destroy_event_queue(event_queue);
    if(logo != nullptr)
        al_destroy_bitmap(logo);
    #ifdef _FPS
    al_destroy_font(fps_font);
    #endif // FPS

    return 0;
}
コード例 #12
0
int main()
{
	ALLEGRO_DISPLAY* display = NULL;
	ALLEGRO_DISPLAY_MODE disp;
	ALLEGRO_EVENT_QUEUE* eq = NULL;

	ALLEGRO_TIMER* timer = NULL;
	ALLEGRO_TIMER* ball_timer = NULL;

	bool run = true;
	bool draw = false;

	if (!al_init())
	{
		return -1;
	}

	al_get_display_mode(al_get_num_display_modes() - 1, &disp);

	std::cout << disp.height << " " << height << std::endl;
	std::cout << disp.width << " " << width << std::endl;

	height = disp.height / 3 * 2;
	width = height / 9 * 16;

	std::cout << disp.height << " " << height << std::endl;
	std::cout << disp.width << " " << width << std::endl;

	al_set_new_display_flags(ALLEGRO_FULLSCREEN);
	display = al_create_display(width, height);
	al_set_window_title(display, "PONG V2");

	if (display == NULL)
	{
		return -1;
	}

	init(&player1, &player2, &ball);

	eq = al_create_event_queue();
	timer = al_create_timer(1.0 / FPS);
	ball_timer = al_create_timer(15.0);

	al_install_keyboard();
	al_init_primitives_addon();
	al_init_font_addon();
	al_init_ttf_addon();

	font = al_load_ttf_font("./arial.ttf", 18, 0);
	scorefont = al_load_ttf_font("./arial.ttf", (height * width) / 36000, 0);

	al_register_event_source(eq, al_get_keyboard_event_source());
	al_register_event_source(eq, al_get_display_event_source(display));
	al_register_event_source(eq, al_get_timer_event_source(timer));

	al_hide_mouse_cursor(display);
	al_start_timer(timer);

	while (run)
	{
		ALLEGRO_EVENT ev;
		al_wait_for_event(eq, &ev);
		if (ev.type == ALLEGRO_EVENT_TIMER)
		{
			draw = true;
		}
		else if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
		{
			run = false;
		}
		else if (ev.type == ALLEGRO_EVENT_KEY_DOWN)
		{
			switch (ev.keyboard.keycode)
			{
				case ALLEGRO_KEY_S:
					keys[P1][DOWN] = true;
					break;
				case ALLEGRO_KEY_W:
					keys[P1][UP] = true;
					break;
				case ALLEGRO_KEY_DOWN:
					keys[P2][DOWN] = true;
					break;
				case ALLEGRO_KEY_UP:
					keys[P2][UP] = true;
					break;
				case ALLEGRO_KEY_SPACE:
					start = true;
					firstGame = false;
					break;
				case ALLEGRO_KEY_ESCAPE:
					run = false;
					break;
				case ALLEGRO_KEY_P:
					if (pause == true) pause = false;
					else if (pause == false) pause = true;
					break;
			}
		}
		else if (ev.type == ALLEGRO_EVENT_KEY_UP)
		{
			switch (ev.keyboard.keycode)
			{
				case ALLEGRO_KEY_S:
					keys[P1][DOWN] = false;
					break;
				case ALLEGRO_KEY_W:
					keys[P1][UP] = false;
					break;
				case ALLEGRO_KEY_DOWN:
					keys[P2][DOWN] = false;
					break;
				case ALLEGRO_KEY_UP:
					keys[P2][UP] = false;
					break;
			}
		}
		if (draw && al_event_queue_is_empty(eq))
		{
			if (!pause)
			{
				if (keys[P1][UP])update(&player1, -1);
				if (keys[P1][DOWN])update(&player1, 1);
				if (keys[P2][UP])update(&player2, -1);
				if (keys[P2][DOWN])update(&player2, 1);

				update(&ball);
				updateGame(&player1, &player2, &ball);
				render();
				draw = false;
			}
		}
	}

	al_destroy_display(display);
	al_destroy_event_queue(eq);

	return 0;
}
コード例 #13
0
ファイル: outrun.cpp プロジェクト: DaniCF/Programs-in-C
int main(int argc, char **argv)

{
	ALLEGRO_DISPLAY *display = NULL;
	ALLEGRO_EVENT_QUEUE *event_queue = NULL;
	ALLEGRO_TIMER *timer = NULL;
	ALLEGRO_BITMAP *pared2 = NULL;
	ALLEGRO_BITMAP *carretera = NULL;
	ALLEGRO_BITMAP *fondo = NULL;
	ALLEGRO_BITMAP *tierra = NULL;
	ALLEGRO_BITMAP *coche = NULL;
	ALLEGRO_BITMAP *coche2 = NULL;
	ALLEGRO_BITMAP *otros = NULL;
	ALLEGRO_BITMAP *porche1 = NULL;
	ALLEGRO_BITMAP *porche2 = NULL;
	ALLEGRO_BITMAP *porche3 = NULL;
	ALLEGRO_BITMAP *porche4 = NULL;
	ALLEGRO_BITMAP *porche5 = NULL;
	ALLEGRO_BITMAP *porche6 = NULL;
	ALLEGRO_BITMAP *freno = NULL;
	ALLEGRO_BITMAP *ciudad = NULL;
	ALLEGRO_BITMAP *ganas = NULL;
	ALLEGRO_BITMAP *pierdes = NULL;
	ALLEGRO_FONT *font = NULL;
	int i = 3;
	int objetivo = 10000;
	int tiempo = 3600;
	float velocidad = 0;
	float carreteray = 0;
	float carreteray2 = 720;
	float bouncer_x = 360;
	float bouncer_y = (SCREEN_H / 10) * 9;
	int camaraX;
	float carreterax1;
	float carreterax2;
	float angulo = 1.571;
	float velocidadt = -10;
	float veltraficox, veltraficoy;
	float centro = 695;
	float ladoizq = 620;
	float ladoder = 790;
	float frenosi = 3;
	float hasganao = 5000;
	float hasperdio = 5000;
	bool key[5] = { false, false, false, false, false};
	bool redraw = true;
	bool doexit = false;

	struct Trafico trafico1 = {1000, 300, 1000, 5, 1};
	struct Trafico trafico2 = {850, 200, 850, 5 , 2};
	struct Trafico trafico3 = {1170, 0, 1170, 5, 3};
	struct Trafico trafico4 = {1000, 400, 1000, 5, 4};
	struct Trafico trafico5 = {850, 100, 850, 5, 1};
	struct Trafico trafico6 = {1170, 500, 1170, 5, 2};


	if (!al_init()) {
		fprintf(stderr, "failed to initialize allegro!\n");
		return -1;
	}

	if (!al_init_image_addon()) {
		al_show_native_message_box(display, "Error", "Error", "No carga lo de imagen", NULL, ALLEGRO_MESSAGEBOX_ERROR);

	}

	if (!al_init_primitives_addon()) {
		al_show_native_message_box(display, "Error", "Error", "No carga lo de primitivos", NULL, ALLEGRO_MESSAGEBOX_ERROR);

	}

	if (!al_install_keyboard()) {
		fprintf(stderr, "failed to initialize the keyboard!\n");
		return -1;
	}

	timer = al_create_timer(1.0 / FPS);
	if (!timer) {
		fprintf(stderr, "failed to create timer!\n");
		return -1;
	}

	display = al_create_display(SCREEN_W, SCREEN_H);
	if (!display) {
		fprintf(stderr, "failed to create display!\n");
		al_destroy_timer(timer);
		return -1;
	}

	al_init_font_addon();
	al_init_ttf_addon();

	font = al_load_ttf_font("djc2.otf", 60, 0);

	pared2 = al_create_bitmap(PARED2_X, PARED2_Y);

	carretera = al_load_bitmap("road22.png");

	if (!carretera) {
		fprintf(stderr, "failed to create bouncer bitmap!\n");
		al_destroy_display(display);
		al_destroy_timer(timer);
		return -1;
	}

	fondo = al_load_bitmap("cielo2.png");
	tierra = al_load_bitmap("camino4.png");
	coche = al_load_bitmap("outrun2.png");
	otros = al_load_bitmap("outruntrprueba5.png");
	ciudad = al_load_bitmap("ciudad3.png");
	freno = al_load_bitmap("freno.png");

	ganas = al_load_bitmap("youwin.png");
	pierdes = al_load_bitmap("youlose.png");
	
	al_convert_mask_to_alpha(coche, al_map_rgb(186, 254, 202));
	al_convert_mask_to_alpha(otros, al_map_rgb(186, 254, 202));

	
	if (!fondo) {
		al_show_native_message_box(display, "Error", "Error", "Falla la carga de imagen", NULL, ALLEGRO_MESSAGEBOX_ERROR);
		al_destroy_display(display);
		return 0;
	}

	if (!coche) {
		al_show_native_message_box(display, "Error", "Error", "Falla la carga de imagen", NULL, ALLEGRO_MESSAGEBOX_ERROR);
		al_destroy_display(display);
		return 0;
	}

	al_set_target_bitmap(pared2);

	al_clear_to_color(al_map_rgb(150, 150, 150));

	al_set_target_bitmap(al_get_backbuffer(display));

	event_queue = al_create_event_queue();
	if (!event_queue) {
		fprintf(stderr, "failed to create event_queue!\n");
		al_destroy_bitmap(pared2);
		al_destroy_display(display);
		al_destroy_timer(timer);
		return -1;
	}

	al_register_event_source(event_queue, al_get_display_event_source(display));

	al_register_event_source(event_queue, al_get_timer_event_source(timer));

	al_register_event_source(event_queue, al_get_keyboard_event_source());

	al_clear_to_color(al_map_rgb(0, 0, 0));

	al_flip_display();

	al_start_timer(timer);

	while (!doexit)
	{
		ALLEGRO_EVENT ev;
		al_wait_for_event(event_queue, &ev);

		if (ev.type == ALLEGRO_EVENT_TIMER) {

			tiempo -= 1;

			/*Spawn del trafico*/

			srand(time(NULL));
			int distancia = rand() % (950 - 750) + 750;
			int distancia2 = rand() % (950 - 750) + 750;
			int distancia3 = rand() % (950 - 750) + 750;
			int distancia4 = rand() % (1201 - 1050) + 1050;
			int distancia5 = rand() % (1201 - 1050) + 1050;
			int distancia6 = rand() % (1201 - 1050) + 1050;

			/*Teclas, movimiento y cambio de sprites en coche principal*/

			if (key[KEY_UP] && velocidad < 25) {
				velocidad += 0.5;
				velocidadt += 0.5;
			}
			else if (velocidad > 0) {
				velocidad -= 0.1;
				velocidadt -= 0.1;
			}

			if (key[KEY_DOWN]) {
				velocidad -= 0.3;
				velocidadt -= 0.3;
				frenosi = SCREEN_W / 2;
			}
			else{
				frenosi = 3000;
			}

			if (key[KEY_LEFT] && velocidad > 0) {
				bouncer_x -= 4;
				frenosi = frenosi + 3;
			}
			if (key[KEY_LEFT] && i > 1 && velocidad > 0) {
				i -= 1;
			}
			else if (!key[KEY_LEFT] && i < 4) {
				i += 1;
			}

			if (key[KEY_RIGHT] && velocidad > 0) {
				bouncer_x += 4;
				frenosi = frenosi - 3;
			}
			if (key[KEY_RIGHT] && i < 5 && velocidad > 0) {
				i += 1;
			}
			else if (!key[KEY_RIGHT] && i > 3) {
				i -= 1;
			}

			objetivo -= velocidad / 10;

			/*Carretera*/

			carreteray += velocidad;
			carreteray2 += velocidad;

			if (carreteray > 1080) {
				carreteray = carreteray2 - 720;
			}
			if (carreteray2 > 1080) {
				carreteray2 = carreteray -720;
			}
			
			/*Limites de sprite y velocidad segun posición*/

			if (velocidad < 0){
				velocidad = 0;
				i = 3;
			}

			if (bouncer_x < 140 && velocidad > 4) {
				velocidad -= 0.6;
				velocidadt -= 0.6;
			}

			if (bouncer_x > 590 && velocidad > 4) {
				velocidad -= 0.6;
				velocidadt -= 0.6;
			}

			/*Formulas para velocidad y posicion del trafico*/

			veltraficox = (velocidadt / 5) * cos(angulo);
			veltraficoy = (velocidadt / 5) * sin(angulo);
			trafico1.traficox += veltraficox;
			trafico1.traficoy += veltraficoy;
			trafico2.traficox += veltraficox;
			trafico2.traficoy += veltraficoy - 1;
			trafico3.traficox += veltraficox;
			trafico3.traficoy += veltraficoy - 1;
			trafico4.traficox += veltraficox;
			trafico4.traficoy += veltraficoy;
			trafico5.traficox += veltraficox;
			trafico5.traficoy += veltraficoy - 1;
			trafico6.traficox += veltraficox;
			trafico6.traficoy += veltraficoy - 1;

			/*Reaparicion del trafico.*/

			if (trafico1.traficoy > distancia) {
				trafico1.traficoy = 200;
				trafico1.traficox = trafico1.spawnp;
				trafico1.otrosi = 5;
				trafico1.otrosy = rand() % 4;
			}
			if (trafico2.traficoy > distancia2) {
				trafico2.otrosi = 5;
				trafico2.traficoy = 200;
				trafico2.traficox = trafico2.spawnp;
				trafico2.otrosy = rand() % 4;
			}

			if (trafico3.traficoy > distancia3) {
				trafico3.otrosi = 5;
				trafico3.traficoy = 200;
				trafico3.traficox = trafico3.spawnp;
				trafico3.otrosy = rand() % 4;
			}

			if (trafico4.traficoy > distancia4) {
				trafico4.otrosi = 5;
				trafico4.traficoy = 200;
				trafico4.traficox = trafico4.spawnp;
				trafico4.otrosy = rand() % 4;
			}
			if (trafico5.traficoy > distancia5) {
				trafico5.otrosi = 5;
				trafico5.traficoy = 200;
				trafico5.traficox = trafico5.spawnp;
				trafico5.otrosy = rand() % 4;
			}

			if (trafico6.traficoy > distancia6) {
				trafico6.otrosi = 5;
				trafico6.traficoy = 200;
				trafico6.traficox = trafico6.spawnp;
				trafico6.otrosy = rand() % 4;
			}


			/*Perspectiva - Falso 3D*/

			camaraX = bouncer_x;

			carreterax1 = 650 - (camaraX / 2);
			carreterax2 = 1130 - (camaraX / 2);

			if (carreterax1 < 820 - camaraX){
				carreterax1 = 820 - camaraX;
			}

			if (carreterax1 > 860 - camaraX) {
				carreterax1 = 860 - camaraX;
			}

			if (carreterax2 > 1320 - camaraX) {
				carreterax2 = 1320 - camaraX;
			}

			if (carreterax2 < 1280 - camaraX) {
				carreterax2 = 1280 - camaraX;
			}

			/*Creacion de sprites*/

			coche2 = al_create_sub_bitmap(coche, i * 130, 0, 130, 74);
			porche1 = al_create_sub_bitmap(otros, trafico1.otrosi * 130, trafico1.otrosy * 62, 130, 62);
			porche2 = al_create_sub_bitmap(otros, trafico2.otrosi * 130, trafico2.otrosy * 62, 130, 62);
			porche3 = al_create_sub_bitmap(otros, trafico3.otrosi * 130, trafico3.otrosy * 62, 130, 62);
			porche4 = al_create_sub_bitmap(otros, trafico4.otrosi * 130, trafico4.otrosy * 62, 130, 62);
			porche5 = al_create_sub_bitmap(otros, trafico5.otrosi * 130, trafico5.otrosy * 62, 130, 62);
			porche6 = al_create_sub_bitmap(otros, trafico6.otrosi * 130, trafico6.otrosy * 62, 130, 62);

			/*Cambio de sprites en Trafico*/

			/*porche1*/
			if (trafico1.traficoy > 370) {
				if (trafico1.traficox - camaraX < centro) {
					trafico1.otrosi = 5;
				}

				if (trafico1.traficox - camaraX > centro) {
					trafico1.otrosi = 6;
				}
			}

			if (trafico1.traficoy > 420){
				if (trafico1.traficox - camaraX < centro) {
					trafico1.otrosi = 4;
				}

				if (trafico1.traficox - camaraX > centro) {
					trafico1.otrosi = 7;
				}
			}

			if (trafico1.traficoy > 470) {
				if (trafico1.traficox - camaraX < centro) {
					trafico1.otrosi = 3;
				}

				if (trafico1.traficox - camaraX > centro) {
					trafico1.otrosi = 8;
				}
			}

			if (trafico1.traficoy > 520) {
				if (trafico1.traficox - camaraX < centro) {
					trafico1.otrosi = 2;
				}

				if (trafico1.traficox - camaraX > centro) {
					trafico1.otrosi = 9;
				}
			}

			if (trafico1.traficoy > 570) {
				if (trafico1.traficox - camaraX < centro) {
					trafico1.otrosi = 1;
				}

				if (trafico1.traficox - camaraX > centro) {
					trafico1.otrosi = 10;
				}

			}
			if (trafico1.traficoy > 620) {
				if (trafico1.traficox - camaraX < centro) {
					trafico1.otrosi = 0;
				}

				if (trafico1.traficox - camaraX > centro) {
					trafico1.otrosi = 11;
				}

			}

			/*porche2*/
			if (trafico2.traficoy > 370) {
				if (trafico2.traficox - camaraX < centro) {
					trafico2.otrosi = 5;
				}

				if (trafico2.traficox - camaraX > centro) {
					trafico2.otrosi = 6;
				}
			}

			if (trafico2.traficoy > 420) {
				if (trafico2.traficox - camaraX < centro) {
					trafico2.otrosi = 4;
				}

				if (trafico2.traficox - camaraX > centro) {
					trafico2.otrosi = 7;
				}
			}

			if (trafico2.traficoy > 470) {
				if (trafico2.traficox - camaraX < centro) {
					trafico2.otrosi = 3;
				}

				if (trafico2.traficox - camaraX > centro) {
					trafico2.otrosi = 8;
				}
			}

			if (trafico2.traficoy > 520) {
				if (trafico2.traficox - camaraX < centro) {
					trafico2.otrosi = 2;
				}

				if (trafico2.traficox - camaraX > centro) {
					trafico2.otrosi = 9;
				}
			}

			if (trafico2.traficoy > 570) {
				if (trafico2.traficox - camaraX < centro) {
					trafico2.otrosi = 1;
				}

				if (trafico2.traficox - camaraX > centro) {
					trafico2.otrosi = 10;
				}

			}
			if (trafico2.traficoy > 620) {
				if (trafico2.traficox - camaraX < centro) {
					trafico2.otrosi = 0;
				}

				if (trafico2.traficox - camaraX > centro) {
					trafico2.otrosi = 11;
				}

			}

			/*porche3*/
			if (trafico3.traficoy > 370) {
				if (trafico3.traficox - camaraX < centro) {
					trafico3.otrosi = 5;
				}

				if (trafico3.traficox - camaraX > centro) {
					trafico3.otrosi = 6;
				}
			}

			if (trafico3.traficoy > 420) {
				if (trafico3.traficox - camaraX < centro) {
					trafico3.otrosi = 4;
				}

				if (trafico3.traficox - camaraX > centro) {
					trafico3.otrosi = 7;
				}
			}

			if (trafico3.traficoy > 470) {
				if (trafico3.traficox - camaraX < centro) {
					trafico3.otrosi = 3;
				}

				if (trafico3.traficox - camaraX > centro) {
					trafico3.otrosi = 8;
				}
			}

			if (trafico3.traficoy > 520) {
				if (trafico3.traficox - camaraX < centro) {
					trafico3.otrosi = 2;
				}

				if (trafico3.traficox - camaraX > centro) {
					trafico3.otrosi = 9;
				}
			}

			if (trafico3.traficoy > 570) {
				if (trafico3.traficox - camaraX < centro) {
					trafico3.otrosi = 1;
				}

				if (trafico3.traficox - camaraX > centro) {
					trafico3.otrosi = 10;
				}

			}
			if (trafico3.traficoy > 620) {
				if (trafico3.traficox - camaraX < centro) {
					trafico3.otrosi = 0;
				}

				if (trafico3.traficox - camaraX > centro) {
					trafico3.otrosi = 11;
				}

			}

			/*porche4*/
			if (trafico4.traficoy > 370) {
				if (trafico4.traficox - camaraX < centro) {
					trafico4.otrosi = 5;
				}

				if (trafico4.traficox - camaraX > centro) {
					trafico4.otrosi = 6;
				}
			}

			if (trafico4.traficoy > 420) {
				if (trafico4.traficox - camaraX < centro) {
					trafico4.otrosi = 4;
				}

				if (trafico4.traficox - camaraX > centro) {
					trafico4.otrosi = 7;
				}
			}

			if (trafico4.traficoy > 470) {
				if (trafico4.traficox - camaraX < centro) {
					trafico4.otrosi = 3;
				}

				if (trafico4.traficox - camaraX > centro) {
					trafico4.otrosi = 8;
				}
			}

			if (trafico4.traficoy > 520) {
				if (trafico4.traficox - camaraX < centro) {
					trafico4.otrosi = 2;
				}

				if (trafico4.traficox - camaraX > centro) {
					trafico4.otrosi = 9;
				}
			}

			if (trafico4.traficoy > 570) {
				if (trafico4.traficox - camaraX < centro) {
					trafico4.otrosi = 1;
				}

				if (trafico4.traficox - camaraX > centro) {
					trafico4.otrosi = 10;
				}

			}
			if (trafico4.traficoy > 620) {
				if (trafico4.traficox - camaraX < centro) {
					trafico4.otrosi = 0;
				}

				if (trafico4.traficox - camaraX > centro) {
					trafico4.otrosi = 11;
				}

			}

			/*porche5*/
			if (trafico5.traficoy > 370) {
				if (trafico5.traficox - camaraX < centro) {
					trafico5.otrosi = 5;
				}

				if (trafico5.traficox - camaraX > centro) {
					trafico5.otrosi = 6;
				}
			}

			if (trafico5.traficoy > 420) {
				if (trafico5.traficox - camaraX < centro) {
					trafico5.otrosi = 4;
				}

				if (trafico5.traficox - camaraX > centro) {
					trafico5.otrosi = 7;
				}
			}

			if (trafico5.traficoy > 470) {
				if (trafico5.traficox - camaraX < centro) {
					trafico5.otrosi = 3;
				}

				if (trafico5.traficox - camaraX > centro) {
					trafico5.otrosi = 8;
				}
			}

			if (trafico5.traficoy > 520) {
				if (trafico5.traficox - camaraX < centro) {
					trafico5.otrosi = 2;
				}

				if (trafico5.traficox - camaraX > centro) {
					trafico5.otrosi = 9;
				}
			}

			if (trafico5.traficoy > 570) {
				if (trafico5.traficox - camaraX < centro) {
					trafico5.otrosi = 1;
				}

				if (trafico5.traficox - camaraX > centro) {
					trafico5.otrosi = 10;
				}

			}
			if (trafico5.traficoy > 620) {
				if (trafico5.traficox - camaraX < centro) {
					trafico5.otrosi = 0;
				}

				if (trafico5.traficox - camaraX > centro) {
					trafico5.otrosi = 11;
				}

			}

			/*porche6*/
			if (trafico6.traficoy > 370) {
				if (trafico6.traficox - camaraX < centro) {
					trafico6.otrosi = 5;
				}

				if (trafico6.traficox - camaraX > centro) {
					trafico6.otrosi = 6;
				}
			}

			if (trafico6.traficoy > 420) {
				if (trafico6.traficox - camaraX < centro) {
					trafico6.otrosi = 4;
				}

				if (trafico6.traficox - camaraX > centro) {
					trafico6.otrosi = 7;
				}
			}

			if (trafico6.traficoy > 470) {
				if (trafico6.traficox - camaraX < centro) {
					trafico6.otrosi = 3;
				}

				if (trafico6.traficox - camaraX > centro) {
					trafico6.otrosi = 8;
				}
			}

			if (trafico6.traficoy > 520) {
				if (trafico6.traficox - camaraX < centro) {
					trafico6.otrosi = 2;
				}

				if (trafico6.traficox - camaraX > centro) {
					trafico6.otrosi = 9;
				}
			}

			if (trafico6.traficoy > 570) {
				if (trafico6.traficox - camaraX < centro) {
					trafico6.otrosi = 1;
				}

				if (trafico6.traficox - camaraX > centro) {
					trafico6.otrosi = 10;
				}

			}
			if (trafico6.traficoy > 620) {
				if (trafico6.traficox - camaraX < centro) {
					trafico6.otrosi = 0;
				}

				if (trafico6.traficox - camaraX > centro) {
					trafico6.otrosi = 11;
				}

			}

			/*Colisiones*/

			if (ladoizq < trafico1.traficox + 65 - camaraX && trafico1.traficox + 65 - camaraX < ladoder && bouncer_y < trafico1.traficoy && trafico1.traficoy < 700) {
				velocidad = 0;
				velocidadt = -10;
			}

			if (ladoizq < trafico2.traficox + 65 - camaraX && trafico2.traficox + 65 - camaraX < ladoder && bouncer_y < trafico2.traficoy && trafico2.traficoy < 700) {
				velocidad = 0;
				velocidadt = -10;
			}
			if (ladoizq < trafico3.traficox + 65 - camaraX && trafico3.traficox + 65 - camaraX < ladoder && bouncer_y < trafico3.traficoy && trafico3.traficoy < 700) {
				velocidad = 0;
				velocidadt = -10;
			}
			if (ladoizq < trafico4.traficox + 65 - camaraX && trafico4.traficox + 65 - camaraX < ladoder && bouncer_y < trafico4.traficoy && trafico4.traficoy < 700) {
				velocidad = 0;
				velocidadt = -10;
			}
			if (ladoizq < trafico5.traficox + 65 - camaraX && trafico5.traficox + 65 - camaraX < ladoder && bouncer_y < trafico5.traficoy && trafico5.traficoy < 700) {
				velocidad = 0;
				velocidadt = -10;
			}
			if (ladoizq < trafico6.traficox + 65 - camaraX && trafico6.traficox + 65 - camaraX < ladoder && bouncer_y < trafico6.traficoy && trafico6.traficoy < 700) {
				velocidad = 0;
				velocidadt = -10;
			}

			/*Funcionamiento de la Camara*/

			if (camaraX > mundoAncho - SCREEN_W) {
				camaraX = mundoAncho - SCREEN_W;
			}

			if (camaraX < 0) {
				camaraX = 0;
			}

			if (bouncer_x > mundoAncho - SCREEN_W) {
				bouncer_x = mundoAncho - SCREEN_W;
			}

			if (bouncer_x < 0) {
				bouncer_x = 0;
			}

			/*Fin de partida*/

			if (tiempo < 0 & objetivo > 0){
				al_stop_timer(timer);
				hasperdio = 292.5;
			}

			if (objetivo < 0 & tiempo > 0) {
				al_stop_timer(timer);
				hasganao = 292.5;
			}

			redraw = true;
		}


		else if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
			break;
		}
		else if (ev.type == ALLEGRO_EVENT_KEY_DOWN) {
			switch (ev.keyboard.keycode) {
			case ALLEGRO_KEY_UP:
				key[KEY_UP] = true;
				break;

			case ALLEGRO_KEY_DOWN:
				key[KEY_DOWN] = true;
				break;

			case ALLEGRO_KEY_LEFT:
				key[KEY_LEFT] = true;
				break;

			case ALLEGRO_KEY_RIGHT:
				key[KEY_RIGHT] = true;
				break;
			case ALLEGRO_KEY_SPACE:
				key[KEY_SPACE] = true;
				break;
			}
		}
		else if (ev.type == ALLEGRO_EVENT_KEY_UP) {
			switch (ev.keyboard.keycode) {
			case ALLEGRO_KEY_UP:
				key[KEY_UP] = false;
				break;

			case ALLEGRO_KEY_DOWN:
				key[KEY_DOWN] = false;
				break;

			case ALLEGRO_KEY_LEFT:
				key[KEY_LEFT] = false;
				break;

			case ALLEGRO_KEY_RIGHT:
				key[KEY_RIGHT] = false;
				break;

			case ALLEGRO_KEY_SPACE:
				key[KEY_SPACE] = false;
				break;

			case ALLEGRO_KEY_ESCAPE:
				doexit = true;
				break;
			}
		}

		if (redraw && al_is_event_queue_empty(event_queue)) {
			redraw = false;

			al_clear_to_color(al_map_rgb(10, 10, 10));

			al_draw_bitmap(carretera, 640 - camaraX, carreteray, 0);
			al_draw_bitmap(carretera, 640 - camaraX, carreteray2, 0);

			al_draw_bitmap(tierra, 640 - camaraX, 0, 0);

			al_draw_filled_triangle(820 - camaraX, 720, 775 - camaraX, 400, carreterax1, 400, al_map_rgb(0, 0, 0));
			al_draw_filled_triangle(1320 - camaraX, 720, 1365 - camaraX, 400, carreterax2, 400, al_map_rgb(0, 0, 0));

			al_draw_line(820 - camaraX, 720, carreterax1, 400, al_map_rgb(0, 255, 255), 6);
			al_draw_line(1320 - camaraX, 720, carreterax2, 400, al_map_rgb(0, 255, 255), 6);

			al_draw_line(640 - camaraX, 425, carreterax1 - 4, 425, al_map_rgb(0, 255, 255), 10);
			al_draw_line(1485 - camaraX, 425, carreterax2 + 4, 425, al_map_rgb(0, 255, 255), 10);

			al_draw_bitmap(porche1, trafico1.traficox - camaraX, trafico1.traficoy, 0);
			al_draw_bitmap(porche2, trafico2.traficox - camaraX, trafico2.traficoy, 0);
			al_draw_bitmap(porche3, trafico3.traficox - camaraX, trafico3.traficoy, 0);
			al_draw_bitmap(porche4, trafico4.traficox - camaraX, trafico4.traficoy, 0);
			al_draw_bitmap(porche5, trafico5.traficox - camaraX, trafico5.traficoy, 0);
			al_draw_bitmap(porche6, trafico6.traficox - camaraX, trafico6.traficoy, 0);

			al_draw_bitmap(fondo, 640 - camaraX, 5, 0);

			al_draw_bitmap(ciudad, 640 - camaraX, 65, 0);

			al_draw_bitmap(pared2, 1485 - camaraX, 0, 0);
			al_draw_bitmap(pared2, 630 - camaraX, 0, 0);

			al_draw_bitmap(coche2, SCREEN_W / 2, bouncer_y - 10, 0);
			al_draw_bitmap(freno, frenosi, bouncer_y - 10, 0);

			al_draw_textf(font, al_map_rgb(255, 0, 0), SCREEN_W / 2 + 200, 50, 0, "%i", objetivo / 2);
			al_draw_textf(font, al_map_rgb(0, 255, 255), SCREEN_W / 2, 50, 0, "%i", tiempo / 60);

			al_draw_bitmap(ganas, hasganao, 200, 0);
			al_draw_bitmap(pierdes, hasperdio, 200, 0);

			al_flip_display();
		}
	}

	al_destroy_bitmap(fondo);
	al_destroy_bitmap(coche);
	al_destroy_timer(timer);
	al_destroy_display(display);
	al_destroy_event_queue(event_queue);

	return 0;
}
コード例 #14
0
ファイル: ex_draw_bitmap.c プロジェクト: liballeg/allegro5
int main(int argc, char **argv)
{
   ALLEGRO_TIMER *timer;
   ALLEGRO_EVENT_QUEUE *queue;
   ALLEGRO_MONITOR_INFO info;
   const char* bitmap_filename;
   int w = 640, h = 480;
   bool done = false;
   bool need_redraw = true;
   bool background = false;
   example.show_help = true;
   example.hold_bitmap_drawing = false;

   if (argc > 1) {
      bitmap_filename = argv[1];
   }
   else {
      bitmap_filename = "data/mysha256x256.png";
   }

   if (!al_init()) {
      abort_example("Failed to init Allegro.\n");
   }

   if (!al_init_image_addon()) {
      abort_example("Failed to init IIO addon.\n");
   }

   al_init_font_addon();
   init_platform_specific();

   al_get_num_video_adapters();
   
   al_get_monitor_info(0, &info);

   al_set_new_display_option(ALLEGRO_SUPPORTED_ORIENTATIONS,
                             ALLEGRO_DISPLAY_ORIENTATION_ALL, ALLEGRO_SUGGEST);
   example.display = al_create_display(w, h);
   if (!example.display) {
      abort_example("Error creating display.\n");
   }

   w = al_get_display_width(example.display);
   h = al_get_display_height(example.display);

   if (!al_install_keyboard()) {
      abort_example("Error installing keyboard.\n");
   }
  
   if (!al_install_mouse()) {
      abort_example("Error installing mouse.\n");
   }

   al_install_touch_input();

   example.font = al_create_builtin_font();
   if (!example.font) {
      abort_example("Error creating builtin font\n");
   }

   example.mysha = al_load_bitmap(bitmap_filename);
   if (!example.mysha) {
      abort_example("Error loading %s\n", bitmap_filename);
   }

   example.white = al_map_rgb_f(1, 1, 1);
   example.half_white = al_map_rgba_f(1, 1, 1, 0.5);
   example.dark = al_map_rgb(15, 15, 15);
   example.red = al_map_rgb_f(1, 0.2, 0.1);
   change_size(256);
   add_sprite();
   add_sprite();

   timer = al_create_timer(1.0 / FPS);

   queue = al_create_event_queue();
   al_register_event_source(queue, al_get_keyboard_event_source());
   al_register_event_source(queue, al_get_mouse_event_source());
   al_register_event_source(queue, al_get_timer_event_source(timer));
   
   if (al_install_touch_input())
      al_register_event_source(queue, al_get_touch_input_event_source());
   al_register_event_source(queue, al_get_display_event_source(example.display));

   al_start_timer(timer);

   while (!done) {
      float x, y;
      ALLEGRO_EVENT event;
      w = al_get_display_width(example.display);
      h = al_get_display_height(example.display);

      if (!background && need_redraw && al_is_event_queue_empty(queue)) {
         double t = -al_get_time();
         add_time();
         al_clear_to_color(al_map_rgb_f(0, 0, 0));
         redraw();
         t += al_get_time();
         example.direct_speed_measure  = t;
         al_flip_display();
         need_redraw = false;
      }

      al_wait_for_event(queue, &event);
      switch (event.type) {
         case ALLEGRO_EVENT_KEY_CHAR: /* includes repeats */
            if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE)
               done = true;
            else if (event.keyboard.keycode == ALLEGRO_KEY_UP) {
               add_sprites(1);
            }
            else if (event.keyboard.keycode == ALLEGRO_KEY_DOWN) {
               remove_sprites(1);
            }
            else if (event.keyboard.keycode == ALLEGRO_KEY_LEFT) {
               change_size(example.bitmap_size - 1);
            }
            else if (event.keyboard.keycode == ALLEGRO_KEY_RIGHT) {
               change_size(example.bitmap_size + 1);
            }
            else if (event.keyboard.keycode == ALLEGRO_KEY_F1) {
               example.show_help ^= 1;
            }
            else if (event.keyboard.keycode == ALLEGRO_KEY_SPACE) {
               example.use_memory_bitmaps ^= 1;
               change_size(example.bitmap_size);
            }
            else if (event.keyboard.keycode == ALLEGRO_KEY_B) {
               example.blending++;
               if (example.blending == 5)
                  example.blending = 0;
            }
            else if (event.keyboard.keycode == ALLEGRO_KEY_H) {
               example.hold_bitmap_drawing ^= 1;
            }
            break;

         case ALLEGRO_EVENT_DISPLAY_CLOSE:
            done = true;
            break;

         case ALLEGRO_EVENT_DISPLAY_HALT_DRAWING:

            background = true;
            al_acknowledge_drawing_halt(event.display.source);

            break;
         
         case ALLEGRO_EVENT_DISPLAY_RESUME_DRAWING:
            background = false;
            al_acknowledge_drawing_resume(event.display.source);
            break;
         
         case ALLEGRO_EVENT_DISPLAY_RESIZE:
            al_acknowledge_resize(event.display.source);
            break;
              
         case ALLEGRO_EVENT_TIMER:
            update();
            need_redraw = true;
            break;
         
         case ALLEGRO_EVENT_TOUCH_BEGIN:
            x = event.touch.x;
            y = event.touch.y;
            goto click;

         case ALLEGRO_EVENT_MOUSE_BUTTON_UP:
            x = event.mouse.x;
            y = event.mouse.y;
            goto click;
            
         click:
         {
            int fh = al_get_font_line_height(example.font);
            
            if (x < fh * 12 && y >= h - fh * 30) {
               int button = (y - (h - fh * 30)) / (fh * 6);
               if (button == 0) {
                  example.use_memory_bitmaps ^= 1;
                  change_size(example.bitmap_size);
               }
               if (button == 1) {
                  example.blending++;
                  if (example.blending == 5)
                     example.blending = 0;
               }
               if (button == 3) {
                  if (x < fh * 6)
                     remove_sprites(example.sprite_count / 2);
                  else
                     add_sprites(example.sprite_count);
               }
               if (button == 2) {
                  int s = example.bitmap_size * 2;
                  if (x < fh * 6)
                     s = example.bitmap_size / 2;
                  change_size(s);
               }
               if (button == 4) {
                  example.show_help ^= 1;
               }
                
            }
            break;
         }
      }
   }

   al_destroy_bitmap(example.bitmap);

   return 0;
}
コード例 #15
0
int main(void)
{
	//primitive variable
	bool done = false;
	bool redraw = true;
	const int FPS = 60;
	bool isGameOver = false;

	//object variables
	SpaceShip ship;
	Bullet bullets[NUM_BULLETS];
	Comet comets[NUM_COMETS];

	//Allegro variables
	ALLEGRO_DISPLAY *display = NULL;
	ALLEGRO_EVENT_QUEUE *event_queue = NULL;
	ALLEGRO_TIMER *timer = NULL;
	ALLEGRO_FONT *font18 = NULL;

	//Initialization Functions
	if(!al_init())										//initialize Allegro
		return -1;

	display = al_create_display(WIDTH, HEIGHT);			//create our display object

	if(!display)										//test display object
		return -1;

	al_init_primitives_addon();
	al_install_keyboard();
	al_init_font_addon();
	al_init_ttf_addon();

	event_queue = al_create_event_queue();
	timer = al_create_timer(1.0 / FPS);

	srand(time(NULL));
	InitShip(ship);
	InitBullet(bullets, NUM_BULLETS);
	InitComet(comets, NUM_COMETS);
	
	font18 = al_load_font("arial.ttf", 18, 0);

	al_register_event_source(event_queue, al_get_keyboard_event_source());
	al_register_event_source(event_queue, al_get_timer_event_source(timer));
	al_register_event_source(event_queue, al_get_display_event_source(display));

	al_start_timer(timer);
	while(!done)
	{
		ALLEGRO_EVENT ev;
		al_wait_for_event(event_queue, &ev);

		if(ev.type == ALLEGRO_EVENT_TIMER)
		{
			redraw = true;
			if(keys[UP])
				MoveShipUp(ship);
			if(keys[DOWN])
				MoveShipDown(ship);
			if(keys[LEFT])
				MoveShipLeft(ship);
			if(keys[RIGHT])
				MoveShipRight(ship);

			if(!isGameOver)
			{
				UpdateBullet(bullets, NUM_BULLETS);
				StartComet(comets, NUM_COMETS);
				UpdateComet(comets, NUM_COMETS);
				CollideBullet(bullets, NUM_BULLETS, comets, NUM_COMETS, ship);
				CollideComet(comets, NUM_COMETS, ship);

				if(ship.lives <= 0)
					isGameOver = true;
			}
		}
		else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
		{
			done = true;
		}
		else if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
		{
			switch(ev.keyboard.keycode)
			{
			case ALLEGRO_KEY_ESCAPE:
				done = true;
				break;
			case ALLEGRO_KEY_UP:
				keys[UP] = true;
				break;
			case ALLEGRO_KEY_DOWN:
				keys[DOWN] = true;
				break;
			case ALLEGRO_KEY_LEFT:
				keys[LEFT] = true;
				break;
			case ALLEGRO_KEY_RIGHT:
				keys[RIGHT] = true;
				break;
			case ALLEGRO_KEY_SPACE:
				keys[SPACE] = true;
				FireBullet(bullets, NUM_BULLETS, ship);
				break;
			}
		}
		else if(ev.type == ALLEGRO_EVENT_KEY_UP)
		{
			switch(ev.keyboard.keycode)
			{
			case ALLEGRO_KEY_ESCAPE:
				done = true;
				break;
			case ALLEGRO_KEY_UP:
				keys[UP] = false;
				break;
			case ALLEGRO_KEY_DOWN:
				keys[DOWN] = false;
				break;
			case ALLEGRO_KEY_LEFT:
				keys[LEFT] = false;
				break;
			case ALLEGRO_KEY_RIGHT:
				keys[RIGHT] = false;
				break;
			case ALLEGRO_KEY_SPACE:
				keys[SPACE] = false;
				break;
			}
		}

		if(redraw && al_is_event_queue_empty(event_queue))
		{
			redraw = false; 

			if(!isGameOver)
			{
				DrawShip(ship);
				DrawBullet(bullets, NUM_BULLETS);
				DrawComet(comets, NUM_COMETS);

				al_draw_textf(font18, al_map_rgb(255, 0, 255), 5, 5, 0, "Player has %i lives left. Player has destroyed %i objects", ship.lives, ship.score);
			}
			else
			{
				al_draw_textf(font18, al_map_rgb(0, 255, 255), WIDTH / 2, HEIGHT / 2, ALLEGRO_ALIGN_CENTRE, "Game Over. Final Score: %i", ship.score);
			}
		
			al_flip_display();
			al_clear_to_color(al_map_rgb(0,0,0));
		}
	}

	al_destroy_event_queue(event_queue);
	al_destroy_timer(timer);
	al_destroy_font(font18);
	al_destroy_display(display);						//destroy our display object

	return 0;
}
コード例 #16
0
int main(int argc, char** argv)
{
	int defw = 640;
	int defh = 480;
	if (argc == 3)
	{
		/*the program was run using 3 arguments
		argv[0] = name of the executable file
		argv[1] = screen width (as a string)
		argv[2] = screen height (as a string)
		*/
		defw = atoi(argv[1]);
		defh = atoi(argv[2]);
	}
	if (!al_init()) return 1; //exit if can't initialize allegro
	//initialize most stuff
	al_install_keyboard();
	al_init_primitives_addon();
	//run in a window
	al_set_new_display_flags(ALLEGRO_WINDOWED);

	//initialize our display and event queue
	ALLEGRO_DISPLAY* display = al_create_display(defw, defh);
	ALLEGRO_EVENT_QUEUE* eventq = al_create_event_queue();

	//this timer will tick once per frame
	ALLEGRO_TIMER* framet = al_create_timer(1.0 / 30.0); //30 frames per second
	al_start_timer(framet);

	//register the event sources so they send events to our queue
	al_register_event_source(eventq, al_get_display_event_source(display)); //display/window
	al_register_event_source(eventq, al_get_keyboard_event_source()); //keyboard
	al_register_event_source(eventq, al_get_timer_event_source(framet)); //fps timer

	//this box is our play field (covers the whole screen)
	CBox fieldbox(0, 0, defw, defh);

	//we setup the ball at the center of the screen with white color
	CBall ball(CBox(defw / 2 - 10, defh / 2 - 10, 20, 20), al_map_rgb(255, 255, 255));
	//we tell it to move to the left
	ball.setXYMovement(-5.0, 0.0);

	//we initialize our both players in an array
	CPlayer players[2] = {
		//red player on the left
		CPlayer(CBox(10, defh / 2 - 80 / 2, 20, 80), al_map_rgb(255, 0, 0)),
		//blue player on the right
		CPlayer(CBox(defw - 10 - 20, defh / 2 - 80 / 2, 20, 80), al_map_rgb(0, 0, 255)),
	};

	/*when this variable is set to true
	the program will quit the main loop
	and free the allocated resources
	before quitting */
	bool exit = false;
	while (!exit)
	{
		al_wait_for_event(eventq, NULL);
		ALLEGRO_EVENT ev;
		while (al_get_next_event(eventq, &ev))
		{
			if (ev.type == ALLEGRO_EVENT_TIMER)
			{
				if (ev.timer.source == framet)
				{
					//fill the screen with black
					al_clear_to_color(al_map_rgb(0, 0, 0));
					//move and draw our two players
					for (int i = 0; i<2; i++)
					{
						players[i].move(fieldbox);
						players[i].draw();
					}
					//move, collide and draw the ball
					switch (ball.move(fieldbox, players))
					{
					case 0:
						break;
					case 1:
						players[0].setScore(players[0].getScore() + 1);
						ball.setXYMovement(5.0, 0.0);
						break;
					case 2:
						players[1].setScore(players[1].getScore() + 1);
						ball.setXYMovement(-5.0, 0.0);
						break;
					}
					ball.draw();
					//show what we've drawn
					al_flip_display();
				}
			}
			else if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
			{
				//quit if the user tries to close the window
				if (ev.display.source == display) exit = true;
			}
			else if (ev.type == ALLEGRO_EVENT_KEY_DOWN)
			{
				//handle key presses
				switch (ev.keyboard.keycode)
				{
				case ALLEGRO_KEY_W:
					players[0].setYMovement(-3.0);
					break;
				case ALLEGRO_KEY_S:
					players[0].setYMovement(3.0);
					break;
				case ALLEGRO_KEY_UP:
					players[1].setYMovement(-3.0);
					break;
				case ALLEGRO_KEY_DOWN:
					players[1].setYMovement(3.0);
					break;
				case ALLEGRO_KEY_ESCAPE:
					exit = true;
					break;
				case ALLEGRO_EVENT_DISPLAY_CLOSE:
					exit = true;
					break;
				}
			}
			else if (ev.type == ALLEGRO_EVENT_KEY_UP)
			{
				int code = ev.keyboard.keycode;
				/*avoid clumsy movement making sure the released key corresponds with
				the moving direction*/
				if (code == ALLEGRO_KEY_W && players[0].getYMovement() < 0)
					players[0].setYMovement(0.0);
				else if (code == ALLEGRO_KEY_S && players[0].getYMovement() > 0)
					players[0].setYMovement(0.0);
				else if (code == ALLEGRO_KEY_UP && players[1].getYMovement() < 0)
					players[1].setYMovement(0.0);
				else if (code == ALLEGRO_KEY_DOWN && players[1].getYMovement() > 0)
					players[1].setYMovement(0.0);
			}
		}
	}
	al_destroy_event_queue(eventq);
	al_destroy_timer(framet);
	al_destroy_display(display);
}
コード例 #17
0
ファイル: killer_bunny.cpp プロジェクト: SocratesDz/kyks
int main()
{          
	const float FPS = 60.0;

	if(!al_init())
	{
		al_show_native_message_box(NULL, "Fatal Error", NULL, "No se pudo inicializar Allegro", NULL, ALLEGRO_MESSAGEBOX_ERROR);
		return -1;
	}
	
	al_set_new_display_flags(ALLEGRO_WINDOWED); // Pone la ventana en modo Windowed
	ALLEGRO_DISPLAY *display = al_create_display(ScreenWidth, ScreenHeight);

	// Pone la posición en la que debe salir la ventana
	//al_set_window_position(display, 0, 30);

	// Pone el título de la ventana
	al_set_window_title(display, "Rabbit Kills Robots");

	if(!display)	// Si no se pudo crear la ventana, entonces pone un mensaje de error
	{
		al_show_native_message_box(NULL, "Error", NULL, "No se pudo crear la pantalla", NULL, ALLEGRO_MESSAGEBOX_ERROR);
		return -1;
	}

	al_install_keyboard();
	al_install_mouse();
	al_init_image_addon();
	al_init_font_addon();
	al_init_ttf_addon();
	al_init_primitives_addon();

	// -----------------------------------------------------------------

	ALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue();
	ALLEGRO_TIMER *timer = al_create_timer(1.0/FPS);
	ALLEGRO_KEYBOARD_STATE keyState;

	// Utilizado para debugging
	ALLEGRO_FONT *font = al_load_font("sprites/DroidSans.ttf", 10, 0);

	
	ALLEGRO_BITMAP *fondo1 = al_load_bitmap("sprites/fondo1.png");
	
	
	bool done = false;

	// ---------Estructuras del juego-----------------------------------

	//~ struct Player
	//~ {
 		//~ ALLEGRO_BITMAP *image;
		//~ float x;
		//~ float y;
		//~ float moveSpeed;
		//~ float degrees;
		//~ int clip;
		//~ bool alive;
		//~ float xmouse;
		//~ float ymouse;
	//~ }player;

	struct Player player;
	player.image = al_load_bitmap("sprites/player.png");
	al_convert_mask_to_alpha(player.image, al_map_rgb(255,255,255));
	player.x = ScreenWidth / 2;
	player.y = ScreenHeight / 2;
	player.w = al_get_bitmap_width(player.image);
	player.h = al_get_bitmap_height(player.image);
	player.moveSpeed = 3;
	player.degrees = -ALLEGRO_PI/2;
   	player.alive = true;
   	player.clip = 6;
   	

	//~ struct Bala
	//~ {
		//~ ALLEGRO_BITMAP *image;
	    //~ float x;
	    //~ float y;
		//~ float dx;
		//~ float dy;
		//~ bool shot;
		//~ void update();
	//~ }bala;
	
	struct Bala bala;
	
	//~ void Bala::update()
	//~ {
		//~ bala.dx = cosf(player.xmouse - player.x);
		//~ bala.dy = senf(player.ymouse - player.y);
		//~ 
		//~ if(bala.shot){
			//~ 
			//~ bala.x += bala.dx;
			//~ bala.y += bala.dy;
			//~ }
		//~ 
	//~ }
	
	bala.image = al_load_bitmap("sprites/bullet.png");
	bala.x = player.x+50;
	bala.y = player.y+25;
	bala.shot = false;

	
	//~ struct Enemigo
	//~ {
		//~ ALLEGRO_BITMAP *image;
        //~ float x;
        //~ float y;
        //~ float velocidad_x;
        //~ float velocidad_y;
        //~ //float degrees;
	//~ }robot;

	struct Enemigo robot;
	robot.image = al_load_bitmap("sprites/Robot_sprites.png");
	//al_convert_mask_to_alpha(robot.image, al_map_rgb(255,255,255));
	robot.x = 50;
	robot.y = 50;
	robot.w = al_get_bitmap_width(robot.image);
	robot.h = al_get_bitmap_height(robot.image);
	robot.velocidad_x = 0.23;
	robot.velocidad_y = 0.23;
	
	//~ void Weapon::recargar()
	//~ {
		//~ for(int i = 0; i < 6; i++)
		//~ {
			//~ bullets[i] = bala;
		//~ }
	//~ }

		
	//~ struct Weapon
	//~ {
		//~ struct Bala bullets[player.clip];
		//~ void recargar();
	//~ }arma;
	//~ 
	//~ void Weapon::recargar()
	//~ {
		//~ for(int i = 0; i < player.clip; i++)
		//~ {
			//~ bullets[i] = bala;
		//~ }
	//~ }
    //~ 
    
	// -----------------------------------------------------------------

	// Esta variable guardará los eventos del mouse
	ALLEGRO_MOUSE_STATE mouseState;
	
	// Registro varias fuentes de eventos
	al_register_event_source(event_queue, al_get_keyboard_event_source());
	al_register_event_source(event_queue, al_get_display_event_source(display));
	al_register_event_source(event_queue, al_get_timer_event_source(timer));
	al_register_event_source(event_queue, al_get_mouse_event_source());

	// Inicializo el temporizador principal
	al_start_timer(timer);

	while(!done)
	{
		// La variable de los eventos
		ALLEGRO_EVENT ev;
		al_wait_for_event(event_queue, &ev); // Y aquí espero por los eventos


		if(ev.type == ALLEGRO_EVENT_TIMER)
		{
			// Dos funciones para pasar eventos del mouse y del teclado
			al_get_keyboard_state(&keyState);
			al_get_mouse_state(&mouseState);
			
			// Esto detecta la posición del mouse y lo guarda a un par de variables
			player.xmouse = al_get_mouse_state_axis(&mouseState, 0);
			player.ymouse = al_get_mouse_state_axis(&mouseState, 1);

			// Si presiono Esc entonces me saca del juego
			if(al_key_down(&keyState, ALLEGRO_KEY_ESCAPE))
			{
				done = true;
			}
			// Si presiono A entonces el valor x se reduce, osea, se va a la izquierda
			if(al_key_down(&keyState, ALLEGRO_KEY_A))
			{
				player.x -= player.moveSpeed;
			}
			// Si... meh, ya sabes lo que sigue
			if(al_key_down(&keyState, ALLEGRO_KEY_D))
			{
				player.x += player.moveSpeed;
			}
			// ...
			if(al_key_down(&keyState, ALLEGRO_KEY_W))
			{
				player.y -= player.moveSpeed;
			}
			// ...
			if(al_key_down(&keyState, ALLEGRO_KEY_S))
			{
				player.y += player.moveSpeed;
			}
					
		}
		
		// Esto permite que el jugador se mueva con el mouse
		player.degrees = atan2((player.ymouse-player.y),(player.xmouse-player.x));
					
		// La Inteligencia Artificial del enemigo
 		if(robot.x < player.x-25) robot.x += robot.velocidad_x;
 		if(robot.x > player.x-25) robot.x -= robot.velocidad_x;
 		if(robot.y > player.y-25) robot.y -= robot.velocidad_y;
 		if(robot.y < player.y-25) robot.y += robot.velocidad_y;
		
		// Uso de las funciones para las colisiones
		//if(Collision(player.x, player.y, 50, 50, robot.x, robot.y, 34, 34)) player.alive = false;
		if(PixelCol(player.image, robot.image, player.x-(player.w/2), player.y-(player.h/2), player.w, player.h, robot.x, robot.y, robot.w/7, robot.h)) player.alive = false;

		al_clear_to_color(al_map_rgb(255, 255, 255));	// Se pinta todo a negro
		al_draw_scaled_bitmap(fondo1,0, 0, 256, 256, 0, 0, ScreenWidth, ScreenHeight, 0);	// Se dibuja el fondo
		if(player.alive){	// Si el jugador está vivo
			al_draw_rotated_bitmap(player.image, 25, 25, player.x, player.y, player.degrees, 0); // Dibujo el jugador
			al_draw_rotated_bitmap(bala.image, 0, 0, player.x+5, player.y+5, player.degrees, 0); // Dibujo la bala (esto hay que quitarlo)
		}
		al_draw_bitmap_region(robot.image, 0, 0, 60, 52, robot.x, robot.y, 0); // Dibujo el robot
        
        
        // Esto es para el debugging
        
        // Dibujo rectángulos para las colisiones
        al_draw_rectangle(player.x-(player.w/2), player.y-(player.h/2), (player.x+player.w)-(player.w/2), (player.y+player.h)-(player.h/2), al_map_rgb(0, 255, 0), 1.0);
        al_draw_rectangle(robot.x, robot.y, robot.x+(robot.w/7), robot.y+robot.h, al_map_rgb(0, 255, 0), 1.0);
        
        // Escribo en una esquina de la pantalla, información respecto al personaje
		al_draw_textf(font, al_map_rgb(255,255,255), ScreenWidth-10, 2, ALLEGRO_ALIGN_RIGHT, "Player x, y : %.1f %.1f", player.x, player.y);
		al_draw_textf(font, al_map_rgb(255,255,255), ScreenWidth-10, 12, ALLEGRO_ALIGN_RIGHT, "Rotation (rad): %.5f", player.degrees);
		al_draw_textf(font, al_map_rgb(255,255,255), ScreenWidth-10, 22, ALLEGRO_ALIGN_RIGHT, "Rotation (degrees): %.2f", (player.degrees*180)/ALLEGRO_PI);
		
		// Actualizo la pantalla (flip)
		al_flip_display();
		
		
	}
	
	//-----After party (hay que limpiar)--------------------------------
	
	// A destruirlo todo!! BAM BAM BAM, KABOOM!!
	al_destroy_font(font);
	al_destroy_bitmap(fondo1);
	al_destroy_bitmap(robot.image);
	al_destroy_display(display);
	al_destroy_event_queue(event_queue);
	al_destroy_bitmap(player.image);
	al_destroy_timer(timer);

	return 0;
}
コード例 #18
0
ファイル: ex_audio_timer.c プロジェクト: gitustc/d2imdev
int main(void)
{
   ALLEGRO_TRANSFORM trans;
   ALLEGRO_EVENT event;
   int bps = 4;
   bool redraw = false;
   unsigned int last_timer = 0;

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

   open_log();

   al_install_keyboard();

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

   font = al_create_builtin_font();
   if (!font) {
      abort_example("Could not create font\n");
   }

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

   if (!al_reserve_samples(RESERVED_SAMPLES)) {
      abort_example("Could not set up voice and mixer\n");
   }

   ping = generate_ping();
   if (!ping) {
      abort_example("Could not generate sample\n");
   }

   timer = al_create_timer(1.0 / bps);
   al_set_timer_count(timer, -1);

   event_queue = al_create_event_queue();
   al_register_event_source(event_queue, al_get_keyboard_event_source());
   al_register_event_source(event_queue, al_get_timer_event_source(timer));

   al_identity_transform(&trans);
   al_scale_transform(&trans, 16.0, 16.0);
   al_use_transform(&trans);

   al_start_timer(timer);

   while (true) {
      al_wait_for_event(event_queue, &event);
      if (event.type == ALLEGRO_EVENT_TIMER) {
         const float speed = pow(21.0/20.0, (event.timer.count % PERIOD));
         if (!al_play_sample(ping, 1.0, 0.0, speed, ALLEGRO_PLAYMODE_ONCE, NULL)) {
            log_printf("Not enough reserved samples.\n");
         }
         redraw = true;
         last_timer = event.timer.count;
      }
      else if (event.type == ALLEGRO_EVENT_KEY_CHAR) {
         if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) {
            break;
         }
         if (event.keyboard.unichar == '+' || event.keyboard.unichar == '=') {
            if (bps < 32) {
               bps++;
               al_set_timer_speed(timer, 1.0 / bps);
            }
         }
         else if (event.keyboard.unichar == '-') {
            if (bps > 1) {
               bps--;
               al_set_timer_speed(timer, 1.0 / bps);
            }
         }
      }

      if (redraw && al_is_event_queue_empty(event_queue)) {
         ALLEGRO_COLOR c;
         if (last_timer % PERIOD == 0)
            c = al_map_rgb_f(1, 1, 1);
         else
            c = al_map_rgb_f(0.5, 0.5, 1.0);

         al_clear_to_color(al_map_rgb(0, 0, 0));
         al_draw_textf(font, c, 640/32, 480/32 - 4, ALLEGRO_ALIGN_CENTRE,
            "%u", last_timer);
         al_flip_display();
      }
   }

   close_log(false);

   return 0;
}
コード例 #19
0
bool
initialize ()
{
  ALLEGRO_BITMAP *temp_color_bitmap;
  ALLEGRO_BITMAP *temp_mask_bitmap;

  global.quit = false;
  al_set_app_name ("Super Battle Thor II");
  if (!al_init ())
    {
      fputs ("Error: Could not start allegro.\n", stderr);
      return false;
    }

  al_set_new_display_option (ALLEGRO_VSYNC, 1, ALLEGRO_SUGGEST);
  al_set_new_display_flags (ALLEGRO_GENERATE_EXPOSE_EVENTS);
  global.display = al_create_display (256, 192);
  if (!global.display)
    {
      fputs ("Error: Allegro could not create a display of 256x192 pixels.\n",
             stderr);
      return false;
    }

  if (!al_install_keyboard ())
    {
      fputs ("Allegro could not initialize the keyboard system.\n", stderr);
      return false;
    }

  global.timer = al_create_timer (ALLEGRO_BPS_TO_SECS (60));
  if (!global.timer)
    {
      fputs ("Allegro could not create a 60hrz timer.\n", stderr);
      return false;
    }

  global.queue = al_create_event_queue ();
  if (!global.queue)
    {
      fputs ("Allegro could not create an event queue.\n", stderr);
      return false;
    }
  al_register_event_source (global.queue, al_get_keyboard_event_source ());
  al_register_event_source (global.queue,
                            al_get_display_event_source (global.display));
  al_register_event_source (global.queue,
                            al_get_timer_event_source (global.timer));

  if (!al_init_image_addon ())
    {
      fputs ("Allegro could not initialize the image loading system.\n",
             stderr);
      return false;
    }

  if (!al_install_audio ())
    {
      fputs ("Allegro could not initialize the audio system.\n", stderr);
      return false;
    }
  al_reserve_samples (16);

  if (!al_init_acodec_addon ())
    {
      fputs ("Allegro could not initialize the audio file loading system.\n",
             stderr);
      return false;
    }

  al_init_font_addon ();

  /* load files */
  global.path = al_get_standard_path (ALLEGRO_PROGRAM_PATH);
  al_append_path_component (global.path, "media");

  al_set_path_filename (global.path, "proggy_tiny.png");
  global.programing_font =
    al_load_bitmap_font (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.programing_font)
    {
      fputs ("Allegro could not load proggy_tiny.png.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "mjollnir.png");
  global.sprite_bitmap[SPRITE_THOR] =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sprite_bitmap[SPRITE_THOR])
    {
      fputs ("Allegro could not load mjollnir.png.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "arrows.png");
  global.arrow_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.arrow_bitmap)
    {
      fputs ("Allegro could not load arrows.png.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "background_1_2_3_4.jpg");
  global.backgrounds[BACKGROUND_1] =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.backgrounds[BACKGROUND_1])
    {
      fputs ("Allegro could not load background_1_2_3_4.jpg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "background_5.jpg");
  global.backgrounds[BACKGROUND_5] =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.backgrounds[BACKGROUND_5])
    {
      fputs ("Allegro could not load background_5.jpg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "background_6.jpg");
  global.backgrounds[BACKGROUND_6] =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.backgrounds[BACKGROUND_6])
    {
      fputs ("Allegro could not load background_6.jpg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "title_screen.jpg");
  global.backgrounds[BACKGROUND_TITLE] =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.backgrounds[BACKGROUND_TITLE])
    {
      fputs ("Allegro could not load title_screen.jpg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "game_over.jpg");
  global.backgrounds[BACKGROUND_GAME_OVER] =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.backgrounds[BACKGROUND_GAME_OVER])
    {
      fputs ("Allegro could not load game_over.jpg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "you_win.jpg");
  global.backgrounds[BACKGROUND_YOU_WIN] =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.backgrounds[BACKGROUND_YOU_WIN])
    {
      fputs ("Allegro could not load you_win.jpg.\n", stderr);
      return false;
    }

  global.backgrounds[BACKGROUND_BLACK] = al_create_bitmap (256, 192);
  if (!global.backgrounds[BACKGROUND_BLACK])
    {
      fputs ("Allegro could not make a 256x192 bitmap :o", stderr);
      return false;
    }
  al_set_target_bitmap (global.backgrounds[BACKGROUND_BLACK]);
  al_clear_to_color (al_map_rgb (0, 0, 0));
  al_set_target_backbuffer (global.display);

/* start copy paste code here becasue I'm lazy */
/*------------------------------------------------------------------------*/
  al_set_path_filename (global.path, "0-thor.jpg");
  temp_color_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_color_bitmap)
    {
      fputs ("Allegro could not load 0-thor.jpg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "0-thor_mask.jpg");
  temp_mask_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_mask_bitmap)
    {
      fputs ("Allegro could not load 0-thor_mask.jpg.\n", stderr);
      return false;
    }

  global.sprite_bitmap[SPRITE_THOR] =
    make_from_mask (temp_color_bitmap, temp_mask_bitmap);
  al_destroy_bitmap (temp_color_bitmap);
  al_destroy_bitmap (temp_mask_bitmap);
/*------------------------------------------------------------------------*/
  al_set_path_filename (global.path, "1-giant.jpg");
  temp_color_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_color_bitmap)
    {
      fputs ("Allegro could not load 1-giant.jpg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "1-giant_mask.jpg");
  temp_mask_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_mask_bitmap)
    {
      fputs ("Allegro could not load 1-giant_mask.jpg.\n", stderr);
      return false;
    }

  global.sprite_bitmap[SPRITE_GIANT] =
    make_from_mask (temp_color_bitmap, temp_mask_bitmap);
  al_destroy_bitmap (temp_color_bitmap);
  al_destroy_bitmap (temp_mask_bitmap);
/*------------------------------------------------------------------------*/
  al_set_path_filename (global.path, "2-nidhogg.jpg");
  temp_color_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_color_bitmap)
    {
      fputs ("Allegro could not load 2-nidhogg.jpg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "2-nidhogg_mask.jpg");
  temp_mask_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_mask_bitmap)
    {
      fputs ("Allegro could not load 2-nidhogg_mask.jpg.\n", stderr);
      return false;
    }

  global.sprite_bitmap[SPRITE_NIDHOGG] =
    make_from_mask (temp_color_bitmap, temp_mask_bitmap);
  al_destroy_bitmap (temp_color_bitmap);
  al_destroy_bitmap (temp_mask_bitmap);
/*------------------------------------------------------------------------*/
  al_set_path_filename (global.path, "3-ran.jpg");
  temp_color_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_color_bitmap)
    {
      fputs ("Allegro could not load 3-ran.jpg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "3-ran_mask.jpg");
  temp_mask_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_mask_bitmap)
    {
      fputs ("Allegro could not load 3-ran_mask.jpg.\n", stderr);
      return false;
    }

  global.sprite_bitmap[SPRITE_RAN] =
    make_from_mask (temp_color_bitmap, temp_mask_bitmap);
  al_destroy_bitmap (temp_color_bitmap);
  al_destroy_bitmap (temp_mask_bitmap);
/*------------------------------------------------------------------------*/
  al_set_path_filename (global.path, "4-grendel.jpg");
  temp_color_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_color_bitmap)
    {
      fputs ("Allegro could not load 4-grendel.jpg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "4-grendel_mask.jpg");
  temp_mask_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_mask_bitmap)
    {
      fputs ("Allegro could not load 4-grendel_mask.jpg.\n", stderr);
      return false;
    }

  global.sprite_bitmap[SPRITE_GRENDEL] =
    make_from_mask (temp_color_bitmap, temp_mask_bitmap);
  al_destroy_bitmap (temp_color_bitmap);
  al_destroy_bitmap (temp_mask_bitmap);
/*------------------------------------------------------------------------*/
  al_set_path_filename (global.path, "5-fafnir.jpg");
  temp_color_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_color_bitmap)
    {
      fputs ("Allegro could not load 5-fafnir.jpg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "5-fafnir_mask.jpg");
  temp_mask_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_mask_bitmap)
    {
      fputs ("Allegro could not load 5-fafnir_mask.jpg.\n", stderr);
      return false;
    }

  global.sprite_bitmap[SPRITE_FAFNIR] =
    make_from_mask (temp_color_bitmap, temp_mask_bitmap);
  al_destroy_bitmap (temp_color_bitmap);
  al_destroy_bitmap (temp_mask_bitmap);
/*------------------------------------------------------------------------*/
  al_set_path_filename (global.path, "6-loki.jpg");
  temp_color_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_color_bitmap)
    {
      fputs ("Allegro could not load 6-loki.jpg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "6-loki_mask.jpg");
  temp_mask_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_mask_bitmap)
    {
      fputs ("Allegro could not load 6-loki_mask.jpg.\n", stderr);
      return false;
    }

  global.sprite_bitmap[SPRITE_LOKI] =
    make_from_mask (temp_color_bitmap, temp_mask_bitmap);
  al_destroy_bitmap (temp_color_bitmap);
  al_destroy_bitmap (temp_mask_bitmap);
/*------------------------------------------------------------------------*/
  al_set_path_filename (global.path, "7-fenrir.jpg");
  temp_color_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_color_bitmap)
    {
      fputs ("Allegro could not load 7-fenrir.jpg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "7-fenrir_mask.jpg");
  temp_mask_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_mask_bitmap)
    {
      fputs ("Allegro could not load 7-fenrir_mask.jpg.\n", stderr);
      return false;
    }

  global.sprite_bitmap[SPRITE_FENRIR] =
    make_from_mask (temp_color_bitmap, temp_mask_bitmap);
  al_destroy_bitmap (temp_color_bitmap);
  al_destroy_bitmap (temp_mask_bitmap);
/*------------------------------------------------------------------------*/
  al_set_path_filename (global.path, "fight.jpg");
  temp_color_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_color_bitmap)
    {
      fputs ("Allegro could not load fight.jpg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "fight_mask.jpg");
  temp_mask_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_mask_bitmap)
    {
      fputs ("Allegro could not load fight_mask.jpg.\n", stderr);
      return false;
    }

  global.sprite_bitmap[SPRITE_FIGHT] =
    make_from_mask (temp_color_bitmap, temp_mask_bitmap);
  al_destroy_bitmap (temp_color_bitmap);
  al_destroy_bitmap (temp_mask_bitmap);
/*------------------------------------------------------------------------*/
/* loading sounds here (still copy paste) */
  al_set_path_filename (global.path, "titlescreen_loop.ogg");
  global.sounds[SOUND_TITLESCREEN_LOOP] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_TITLESCREEN_LOOP])
    {
      fputs ("Allegro could not load titlescreen_loop.ogg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "begin_battle.ogg");
  global.sounds[SOUND_BEGIN_BATTLE] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_BEGIN_BATTLE])
    {
      fputs ("Allegro could not load begin_battle.ogg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "battle_loop.ogg");
  global.sounds[SOUND_BATTLE_LOOP] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_BATTLE_LOOP])
    {
      fputs ("Allegro could not load battle_loop.ogg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "dragon_loop.ogg");
  global.sounds[SOUND_DRAGON_LOOP] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_DRAGON_LOOP])
    {
      fputs ("Allegro could not load dragon_loop.ogg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "hit_1.ogg");
  global.sounds[SOUND_HIT_1] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_HIT_1])
    {
      fputs ("Allegro could not load hit_1.ogg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "hit_2.ogg");
  global.sounds[SOUND_HIT_2] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_HIT_2])
    {
      fputs ("Allegro could not load hit_2.ogg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "laugh_1.ogg");
  global.sounds[SOUND_LAUGH_1] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_LAUGH_1])
    {
      fputs ("Allegro could not load laugh_1.ogg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "laugh_2.ogg");
  global.sounds[SOUND_LAUGH_2] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_LAUGH_2])
    {
      fputs ("Allegro could not load laugh_2.ogg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "laugh_3.ogg");
  global.sounds[SOUND_LAUGH_3] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_LAUGH_3])
    {
      fputs ("Allegro could not load laugh_3.ogg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "laugh_4.ogg");
  global.sounds[SOUND_LAUGH_4] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_LAUGH_4])
    {
      fputs ("Allegro could not load laugh_4.ogg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "laugh_5.ogg");
  global.sounds[SOUND_LAUGH_5] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_LAUGH_5])
    {
      fputs ("Allegro could not load laugh_5.ogg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "laugh_6.ogg");
  global.sounds[SOUND_LAUGH_6] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_LAUGH_6])
    {
      fputs ("Allegro could not load laugh_6.ogg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "killed_baddie.ogg");
  global.sounds[SOUND_KILLED_BADDIE] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_KILLED_BADDIE])
    {
      fputs ("Allegro could not load killed_baddie.ogg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "got_hit.ogg");
  global.sounds[SOUND_GOT_HIT] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_GOT_HIT])
    {
      fputs ("Allegro could not load got_hit.ogg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "you_are_dead.ogg");
  global.sounds[SOUND_YOU_ARE_DEAD] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_YOU_ARE_DEAD])
    {
      fputs ("Allegro could not you_are_dead.ogg.\n", stderr);
      return false;
    }

  global.music = NULL;

  al_destroy_path (global.path);

  return true;
}
コード例 #20
0
// METODO PARA CRIAR O TEMPORIZADOR
void GerenciadorGrafico::CriaTimer()
{
    timer = al_create_timer(1.0 / FPS);
}
コード例 #21
0
ファイル: game.c プロジェクト: hiltonm/nostos
GAME * game_init ()
{
    if (!al_init ()) {
        fprintf (stderr, "Failed to initialize Allegro.\n");
        return NULL;
    }

    if (!al_init_image_addon ()) {
        fprintf (stderr, "Failed to initialize image addon.\n");
        return NULL;
    }

    if (!al_install_keyboard ()) {
        fprintf (stderr, "Failed to install keyboard.\n");
        return NULL;
    }

    al_init_font_addon ();

    if (!al_init_ttf_addon ()) {
        fprintf (stderr, "Failed to initialize ttf addon.\n");
        return NULL;
    }

    if (!al_init_primitives_addon ()) {
        fprintf (stderr, "Failed to initialize primitives addon.\n");
        return NULL;
    }

    GAME *game = al_malloc (sizeof (GAME));
    if (!game)
        return NULL;

    srand (time (NULL));

    game->running = true;
    game->paused = false;

    game->fullscreen = 1;
    game->windowed = 1;
    game->rrate = 60;
    game->suggest_vsync = 1;
    game->force_vsync = 0;

    game->current_npc = NULL;

    game->screen = screen_new ();

    char *filename;
    const char *str;

    filename = get_resource_path_str ("data/game.ini");
    ALLEGRO_CONFIG *game_config = al_load_config_file (filename);
    al_free (filename);

    str = al_get_config_value (game_config, "", "org");
    al_set_org_name (str);
    str = al_get_config_value (game_config, "", "app");
    al_set_app_name (str);

    ALLEGRO_PATH *settpath = al_get_standard_path (ALLEGRO_USER_SETTINGS_PATH);
    ALLEGRO_PATH *gcpath = al_clone_path (settpath);

    al_set_path_filename (gcpath, "general.ini");
    const char * gcpath_str = al_path_cstr (gcpath, ALLEGRO_NATIVE_PATH_SEP);

    ALLEGRO_CONFIG *gconfig = al_load_config_file (gcpath_str);

    if (!gconfig) {
        gconfig = al_create_config ();
        al_make_directory (al_path_cstr (settpath, ALLEGRO_NATIVE_PATH_SEP));

        set_config_i (gconfig, "display", "width", game->screen.width);
        set_config_i (gconfig, "display", "height", game->screen.height);
        set_config_i (gconfig, "display", "fullscreen", game->fullscreen);
        set_config_i (gconfig, "display", "windowed", game->windowed);
        set_config_i (gconfig, "display", "refreshrate", game->rrate);
        set_config_i (gconfig, "display", "suggest_vsync", game->suggest_vsync);
        set_config_i (gconfig, "display", "force_vsync", game->force_vsync);
    } else {
        get_config_i (gconfig, "display", "width", &game->screen.width);
        get_config_i (gconfig, "display", "height", &game->screen.height);
        get_config_i (gconfig, "display", "fullscreen", &game->fullscreen);
        get_config_i (gconfig, "display", "windowed", &game->windowed);
        get_config_i (gconfig, "display", "refreshrate", &game->rrate);
        get_config_i (gconfig, "display", "suggest_vsync", &game->suggest_vsync);
        get_config_i (gconfig, "display", "force_vsync", &game->force_vsync);
    }

    al_save_config_file (gcpath_str, gconfig);

    al_destroy_path (settpath);
    al_destroy_path (gcpath);
    al_destroy_config (gconfig);

    int flags = 0;

    if (game->fullscreen == game->windowed)
        flags |= ALLEGRO_FULLSCREEN_WINDOW;
    else if (game->fullscreen)
        flags |= ALLEGRO_FULLSCREEN;
    else
        flags |= ALLEGRO_WINDOWED;

    al_set_new_display_option (ALLEGRO_VSYNC, game->suggest_vsync, ALLEGRO_SUGGEST);
    al_set_new_display_option (ALLEGRO_DEPTH_SIZE, 8, ALLEGRO_SUGGEST);

    al_set_new_display_flags (flags);
    al_set_new_display_refresh_rate (game->rrate);
    game->display = al_create_display (game->screen.width, game->screen.height);
    if (!game->display) {
        fprintf (stderr, "Failed to create display.\n");
        al_free (game);
        return NULL;
    }

    al_set_new_bitmap_flags (ALLEGRO_VIDEO_BITMAP);

    game->timer = al_create_timer (1.0 / FPS);
    if (!game->timer) {
        fprintf (stderr, "Failed to create timer.\n");
        al_free (game);
        return NULL;
    }

    game->screen.width = al_get_display_width (game->display);
    game->screen.height = al_get_display_height (game->display);
    screen_update_size (&game->screen, game->screen.width, game->screen.height);

    game->rrate = al_get_display_refresh_rate (game->display);

    game->event_queue = al_create_event_queue ();
    if (!game->event_queue) {
        fprintf (stderr, "Failed to create event queue.\n");
        al_free (game);
        return NULL;
    }

    al_register_event_source (game->event_queue, al_get_display_event_source (game->display));
    al_register_event_source (game->event_queue, al_get_timer_event_source (game->timer));

    al_set_render_state (ALLEGRO_ALPHA_FUNCTION, ALLEGRO_RENDER_EQUAL);
    al_set_render_state (ALLEGRO_ALPHA_TEST_VALUE, 1);

    filename = get_resource_path_str ("data/sprites.ini");
    game->sprites = sprite_load_sprites (filename);
    al_free (filename);

    filename = get_resource_path_str ("data/scenes.ini");
    game->scenes = scene_load_file (filename);
    scene_load_scenes (game->scenes, game->sprites);
    al_free (filename);

    str = al_get_config_value (game_config, "", "scene");
    game->current_scene = scene_get (game->scenes, str);

    str = al_get_config_value (game_config, "", "actor");
    game->current_actor = sprite_new_actor (game->sprites, str);
    str = al_get_config_value (game_config, "", "portal");
    SCENE_PORTAL *portal = scene_get_portal (game->scenes, str);

    al_destroy_config (game_config);

    filename = get_resource_path_str ("data/ui.ini");
    game->ui = ui_load_file (filename);
    al_free (filename);

    sprite_center (game->current_actor, &portal->position);
    screen_center (&game->screen, portal->position, game->current_scene->map);

    return game;
}
コード例 #22
0
int main(void)
{
    bool done =false;
    bool redraw = true;
    ALLEGRO_DISPLAY *display = NULL;
    ALLEGRO_TIMER *timer =NULL;
    ALLEGRO_EVENT_QUEUE *event_queue = NULL;
    SpaceShip ship;
    Bullet bullet[num_bullets];
    Commet commet[num_commets];
    if(!al_init())
    {
        fprintf(stderr,"allegro is not intialized");
        return -1;
    }
    display = al_create_display(SCREEN_W,SCREEN_H);
    if(!display)
    {
        fprintf(stderr,"failed to intialize the display");
        return -1;
    }
    
    timer  = al_create_timer(1.0/FPS);
    if(!timer)
    {
        fprintf(stderr,"failed to intialize timer");
        al_destroy_display(display);
        return -1;
    }
    event_queue = al_create_event_queue();
    if(!event_queue)
    {
        fprintf(stderr,"failed to create event queue");
        al_destroy_display(display);
        al_destroy_timer(timer);
        return -1;
    }
    al_install_keyboard();
    al_register_event_source(event_queue,al_get_timer_event_source(timer));
    al_register_event_source(event_queue,al_get_keyboard_event_source());
    al_register_event_source(event_queue,al_get_display_event_source(display));
    init_ship(&ship);
    init_bullet(&bullet);
    init_commet(&commet);
    al_start_timer(timer);
    while(!done)
    {
        
        ALLEGRO_EVENT ev;
        al_wait_for_event(event_queue,&ev);
        
        if(ev.type == ALLEGRO_EVENT_TIMER)
        {
            if(keys[KEY_UP])
            {
                move_ship_up(&ship);
            }
            if(keys[KEY_DOWN])
            {
                move_ship_down(&ship);
            }if(keys[KEY_LEFT])
            {
                move_ship_left(&ship);
            }
            if(keys[KEY_RIGHT])
            {
                move_ship_right(&ship);
            }
            if(keys[KEY_SPACEBAR])
            {
                fire_bullet(&bullet,&ship);
            }
            if(!GameOver)
            {
                update_bullet(&bullet);
                update_commet(&commet);
                bullet_collision(&bullet,&commet);
            }
            
            redraw = true;
        }
        else if(ev.type==ALLEGRO_EVENT_DISPLAY_CLOSE)
        {
            done = true;
        }
        else if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
        {
            switch(ev.keyboard.keycode)
            {
                case ALLEGRO_KEY_UP:
                {
                    keys[KEY_UP]=true;
                    break;
                }
                case ALLEGRO_KEY_DOWN:
                {
                    keys[KEY_DOWN]=true;
                    break;
                }
                case ALLEGRO_KEY_LEFT:
                {
                    keys[KEY_LEFT]=true;
                    break;
                }
                case ALLEGRO_KEY_RIGHT :
                {
                    keys[KEY_RIGHT]=true;
                    break;
                }
                case ALLEGRO_KEY_SPACE:
                {
                    keys[KEY_SPACEBAR] = true;
                    break;
                }
                    
            }
        }
        else if(ev.type == ALLEGRO_EVENT_KEY_UP)
        {
            switch(ev.keyboard.keycode)
            {
                case ALLEGRO_KEY_UP:
                {
                    keys[KEY_UP]=false;
                    break;
                }
                case ALLEGRO_KEY_DOWN:
                {
                    keys[KEY_DOWN]=false;
                    break;
                }
                case ALLEGRO_KEY_LEFT:
                {
                    keys[KEY_LEFT]=false;
                    break;
                }
                case ALLEGRO_KEY_RIGHT :
                {
                    keys[KEY_RIGHT]=false;
                    break;
                }
                case ALLEGRO_KEY_SPACE:
                {
                    keys[KEY_SPACEBAR]=false;
                    break;
                }
                    
            }
        }
        
        if(redraw && al_event_queue_is_empty(event_queue))
        {
            redraw = false ;
            al_clear_to_color(al_map_rgb(255,100,100));
            draw_ship(&ship);
            draw_bullet(bullet);
            draw_commet(commet);
            al_flip_display();
            al_clear_to_color(al_map_rgb(255,100,100));
            
            
        }
    }
    al_destroy_display(display);
    al_destroy_timer(timer);
    al_destroy_event_queue(event_queue);
    return 0;
}
コード例 #23
0
int main(void)
{
   ALLEGRO_DISPLAY *display;
   ALLEGRO_TIMER *timer;
   ALLEGRO_EVENT_QUEUE *queue;
   ALLEGRO_BITMAP *bmp;
   ALLEGRO_BITMAP *mem_bmp;
   ALLEGRO_BITMAP *disp_bmp;
   ALLEGRO_FONT *font;
   char *text;
   bool done = false;
   bool redraw = true;

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

   if (!al_init_image_addon()) {
      abort_example("Failed to init IIO addon.\n");
      return 1;
   }

   al_init_font_addon();

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

   if (!al_install_keyboard()) {
      abort_example("Error installing keyboard.\n");
      return 1;
   }

   font = al_load_font("data/fixed_font.tga", 0, 0);
   if (!font) {
      abort_example("Error loading data/fixed_font.tga\n");
      return 1;
   }

   bmp = disp_bmp = al_load_bitmap("data/mysha.pcx");
   if (!bmp) {
      abort_example("Error loading data/mysha.pcx\n");
      return 1;
   }
   text = "Display bitmap (space to change)";

   al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP);
   mem_bmp = al_load_bitmap("data/mysha.pcx");
   if (!bmp) {
      abort_example("Error loading data/mysha.pcx\n");
      return 1;
   }


   timer = al_create_timer(INTERVAL);

   queue = al_create_event_queue();
   al_register_event_source(queue, al_get_keyboard_event_source());
   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);

   al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_INVERSE_ALPHA);

   while (!done) {
      ALLEGRO_EVENT event;

      if (redraw && al_is_event_queue_empty(queue)) {
         update(bmp);
         al_clear_to_color(al_map_rgb_f(0, 0, 0));
         al_draw_tinted_bitmap(bmp, al_map_rgba_f(1, 1, 1, 0.5),
            bmp_x, bmp_y, bmp_flag);
         al_draw_text(font, al_map_rgba_f(1, 1, 1, 0.5), 0, 0, 0, text);
         al_flip_display();
         redraw = false;
      }

      al_wait_for_event(queue, &event);
      switch (event.type) {
         case ALLEGRO_EVENT_KEY_DOWN:
            if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE)
               done = true;
            else if (event.keyboard.keycode == ALLEGRO_KEY_SPACE) {
               if (bmp == mem_bmp) {
                  bmp = disp_bmp;
                  text = "Display bitmap (space to change)";
               }
               else {
                  bmp = mem_bmp;
                  text = "Memory bitmap (space to change)";
               }
            }
               
            break;

         case ALLEGRO_EVENT_DISPLAY_CLOSE:
            done = true;
            break;

         case ALLEGRO_EVENT_TIMER:
            redraw = true;
            break;
      }
   }

   al_destroy_bitmap(bmp);

   return 0;
}
コード例 #24
0
ファイル: ex_noframe.c プロジェクト: BorisCarvajal/allegro5
int main(int argc, char **argv)
{
   ALLEGRO_DISPLAY *display;
   ALLEGRO_BITMAP *bitmap;
   ALLEGRO_EVENT_QUEUE *events;
   ALLEGRO_EVENT event;
   bool down = false;
   int down_x = 0, down_y = 0;
   ALLEGRO_TIMER *timer;

   (void)argc;
   (void)argv;

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

   al_install_mouse();
   al_install_keyboard();
   al_init_image_addon();
   init_platform_specific();

   al_set_new_display_flags(ALLEGRO_FRAMELESS);
   display = al_create_display(300, 200);
   if (!display) {
      abort_example("Error creating display\n");
   }
   
   bitmap = al_load_bitmap("data/fakeamp.bmp");
   if (!bitmap) {
      abort_example("Error loading fakeamp.bmp\n");
   }

   timer = al_create_timer(1.0f/30.0f);

   events = al_create_event_queue();
   al_register_event_source(events, al_get_mouse_event_source());
   al_register_event_source(events, al_get_keyboard_event_source());
   al_register_event_source(events, al_get_display_event_source(display));
   al_register_event_source(events, al_get_timer_event_source(timer));

   al_start_timer(timer);

   for (;;) {
      al_wait_for_event(events, &event);
      if (event.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) {
         if (event.mouse.button == 1 && event.mouse.x) {
            down = true;
            down_x = event.mouse.x;
            down_y = event.mouse.y;
         }
         if (event.mouse.button == 2) {
            al_set_display_flag(display, ALLEGRO_FRAMELESS,
               !(al_get_display_flags(display) & ALLEGRO_FRAMELESS));
         }
      }
      else if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
         break;
      }
      else if (event.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP) {
         if (event.mouse.button == 1) {
            down = false;
         }
      }
      else if (event.type == ALLEGRO_EVENT_MOUSE_AXES) {
         if (down) {
            int cx, cy;
            if (al_get_mouse_cursor_position(&cx, &cy)) {
               al_set_window_position(display, cx - down_x, cy - down_y);
            }
         }
      }
      else if (event.type == ALLEGRO_EVENT_KEY_DOWN &&
	    event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) {
         break;
      }
      else if (event.type == ALLEGRO_EVENT_TIMER) {
         al_draw_bitmap(bitmap, 0, 0, 0);
         al_flip_display();
      }
   }

   al_destroy_timer(timer);
   al_destroy_event_queue(events);
   al_destroy_display(display);

   return 0;
}
コード例 #25
0
ファイル: xenon.cpp プロジェクト: rbg01/programs-de-c
int main(int argc, char **argv){

    /*declaramos nave como una estructura tipo móvil, q está definida
     * en el archivo "physics.h"*/
    struct Movil nave;


    /*creamos las variables de allegro, que son punteros
     * apuntando a NULL, de momento*/
    ALLEGRO_DISPLAY *display = NULL;
    ALLEGRO_BITMAP *sprites = NULL;
    ALLEGRO_EVENT_QUEUE *event_queue = NULL;
    ALLEGRO_TIMER *timer = NULL;

    bool key[4] = {false, false, false,false};//Array para las teclas, todos a false 
    bool redraw = true;
    bool do_exit = false;

    /* Inicializamos allegro */
    if(!al_init()) {
        al_show_native_message_box (
                display,
                "Error",
                "Error",
                "Failed to initialize allegro!",
                NULL,
                ALLEGRO_MESSAGEBOX_ERROR);

        return 0;
    }

    /* Inicializamos añadido de imágenes */
    if(!al_init_image_addon()) {
        al_show_native_message_box (
                display,
                "Error",
                "Error",
                "Failed to initialize al_init_image_addon!",
                NULL,
                ALLEGRO_MESSAGEBOX_ERROR);

        return 0;
    }

ni    /* Inicializamos el teclado */
    if(!al_install_keyboard()) {
        al_show_native_message_box (
                display,
                "Error",
                "Error",
                "Failed to initialize al_init_image_addon!",
                NULL,
                ALLEGRO_MESSAGEBOX_ERROR);

        return 0;
    };

    /* Alegro artifact creation
     * del display, timer, cola eventos y sprites*/

    display = al_create_display(SCREEN_W, SCREEN_H);
    if(!display) {
        al_show_native_message_box(
                display,
                "Error",
                "Error",
                "Failed to initialize display!",
                NULL,
                ALLEGRO_MESSAGEBOX_ERROR);

        return 0;
    }


    timer = al_create_timer(1.0 / FPS);
    if(!timer) {
        al_show_native_message_box(
                display,
                "Error",
                "Error",
                "failed to create timer!\n",
                NULL,
                ALLEGRO_MESSAGEBOX_ERROR);

        al_destroy_display(display);

        return 0;
    }


    event_queue = al_create_event_queue();
    if(!event_queue) {
        al_show_native_message_box(
                display,
                "Error",
                "Error",
                "failed to create event_queue!\n",
                NULL,
                ALLEGRO_MESSAGEBOX_ERROR);

        al_destroy_display(display);
        al_destroy_timer(timer);

        return 0;
    }


    sprites = al_load_bitmap("images/xenon2_sprites.png");
    al_convert_mask_to_alpha(sprites, al_map_rgb(255,0,255));

    if(!sprites) {
        al_show_native_message_box(
                display,
                "Error",
                "Error",
                "Failed to load sprites!",
                NULL,
                ALLEGRO_MESSAGEBOX_ERROR);

        al_destroy_display(display);
        al_destroy_timer(timer);
        al_destroy_event_queue(event_queue);

        return 0;
    }

    /* registramos todos los eventos provenientes de la pantalla
     * el keyboard y el temporizador*/
    al_register_event_source(event_queue, al_get_display_event_source(display));
    al_register_event_source(event_queue, al_get_keyboard_event_source());
    al_register_event_source(event_queue, al_get_timer_event_source(timer));


    /* Init es una funcion definida como extern el "physics.h" , que le meto
     * los sprites, que es el bitmap de la nave, y &nave, que es una dirección
     * de memoria donde hemos declarado nave como estructura*/
    init(sprites, &nave);

    al_start_timer(timer);

    while(!doexit){
        ALLEGRO_EVENT ev;
        al_wait_for_event(event_queue, &ev);

        if(ev.type == ALLEGRO_EVENT_TIMER)
            redraw = true;
        else if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
            break;
        /* éste bloque funciona con el evento KEY_DOWN, y cuando apretamos
         * cualquier tecla, se registra el avento KEY_DOWN q corresponda */
        else if (ev.type == ALLEGRO_EVENT_KEY_DOWN) {
            switch(ev.keyboard.keycode) {
                case ALLEGRO_KEY_UP:
                    key[KEY_THROTTLE] = true;
                    break;

                case ALLEGRO_KEY_DOWN:
                    key[KEY_BRAKE] = true;
                    break;

                case ALLEGRO_KEY_LEFT:
                    key[KEY_ROTATE_LEFT] = true;
                    break;

                case ALLEGRO_KEY_RIGHT:
                    key[KEY_ROTATE_RIGHT] = true;
                    break;
            }
            /* Éste bloque funciona con el evento KEY_UP, cuando soltamos
             *  la tecla se registra el evento KEY_DOWN correspondiente.*/
        } else if (ev.type == ALLEGRO_EVENT_KEY_UP) {
            switch(ev.keyboard.keycode) {
                case ALLEGRO_KEY_UP:
                    key[KEY_THROTTLE] = false;
                    break;

                case ALLEGRO_KEY_DOWN:
                    key[KEY_BRAKE] = false;
                    break;

                case ALLEGRO_KEY_LEFT:
                    key[KEY_ROTATE_LEFT] = false;
                    break;

                case ALLEGRO_KEY_RIGHT:
                    key[KEY_ROTATE_RIGHT] = false;
                    break;

                case ALLEGRO_KEY_ESCAPE:
                    doexit = true;
                    break;
            }
        }

        if(redraw && al_is_event_queue_empty(event_queue)) {
            redraw = false;
            update_physics(key, &nave);
            al_clear_to_color(al_map_rgb(0,0,0));

 //         al_draw_bitmap(sprites,200,200,0);
            al_draw_bitmap(nave.img[2 + (int) (nave.v.x / ROLL) ],
                    SCREEN_W / 2 + nave.r.x,
                    SCREEN_H - 50 - nave.r.y,
                    0);
            al_flip_display();
        }
    }

        /* DEstrucción de los artefactos */
    al_destroy_display(display);
    al_destroy_timer(timer);
    al_destroy_event_queue(event_queue);
    al_destroy_bitmap(sprites);


    return 0;
}
コード例 #26
0
Framework::Framework( int Width, int Height, int Framerate, bool DropFrames )
{
	System = this;

#ifdef WRITE_LOG
	LogFile = fopen( "sjkt.txt", "a" );
	
	fprintf( LogFile, "Framework: Startup: Allegro\n" );
#endif

	if( !al_init() )
	{
		fprintf( LogFile, "Framework: Error: Cannot init Allegro\n" );
		quitProgram = true;
		return;
	}
	
	al_init_font_addon();
	if( !al_install_keyboard() || !al_install_mouse() || !al_install_joystick() || !al_init_primitives_addon() || !al_init_ttf_addon() || !al_init_image_addon() )
	{
		fprintf( LogFile, "Framework: Error: Cannot init Allegro plugin\n" );
		quitProgram = true;
		return;
	}

#ifdef NETWORK_SUPPORT
#ifdef WRITE_LOG
	fprintf( LogFile, "Framework: Startup: Network\n" );
#endif
	if( enet_initialize() != 0 )
	{
		fprintf( LogFile, "Framework: Error: Cannot init enet\n" );
		quitProgram = true;
		return;
	}
#endif

#ifdef WRITE_LOG
	fprintf( LogFile, "Framework: Startup: Default Variables\n" );
#endif
	quitProgram = false;
  ProgramStages = new StageStack();
  framesToProcess = 0;
	framesPerSecond = Framerate;
	enableSlowDown = DropFrames;

#ifdef WRITE_LOG
	fprintf( LogFile, "Framework: Startup: Settings file\n" );
#endif
  Settings = new ConfigFile( "settings.cfg" );


#ifdef DOWNLOAD_SUPPORT
#ifdef WRITE_LOG
	fprintf( LogFile, "Framework: Startup: Download Manager\n" );
#endif
	DOWNLOADS = new DownloadManager( Settings->GetQuickIntegerValue( "Downloads.Concurrent", 3 ) );
#endif

#ifdef WRITE_LOG
	fprintf( LogFile, "Framework: Startup: Allegro Events\n" );
#endif
	eventAllegro = al_create_event_queue();
	eventMutex = al_create_mutex_recursive();
	frameTimer = al_create_timer( 1.0 / (double)framesPerSecond );

	srand( (unsigned int)al_get_time() );

#ifdef WRITE_LOG
	fprintf( LogFile, "Framework: Startup: Display\n" );
#endif
	DISPLAY = new Display( Width, Height );
	DISPLAY->Initialise( Settings->GetQuickIntegerValue( "Video.Width", Width ), Settings->GetQuickIntegerValue( "Video.Height", Height ), Settings->GetQuickBooleanValue( "Video.Fullscreen", false ), (DisplayScaleMode::ScaleMode)Settings->GetQuickIntegerValue( "Video.ScaleMode", DisplayScaleMode::Letterbox ) );
	AUDIO = new Audio();

#ifdef WRITE_LOG
	fprintf( LogFile, "Framework: Startup: Register event sources\n" );
#endif
	RegisterEventSource( DISPLAY->GetEventSource() );
	RegisterEventSource( al_get_keyboard_event_source() );
	RegisterEventSource( al_get_mouse_event_source() );
	RegisterEventSource( al_get_joystick_event_source() );
	RegisterEventSource( al_get_timer_event_source( frameTimer ) );

#ifdef WRITE_LOG
	fprintf( LogFile, "Framework: Startup: Joystick IDs\n" );
#endif
	GetJoystickIDs();
}
コード例 #27
0
ファイル: copy of main.c プロジェクト: BADSA/GALAGA
int main(void){
	//allegro variables
	ALLEGRO_DISPLAY *display = NULL;
	ALLEGRO_EVENT_QUEUE *event_queue = NULL;
	ALLEGRO_BITMAP *bg = NULL;
	ALLEGRO_TIMER *timer;

	//program init
	if(!al_init())										//initialize Allegro
		return -1;

	display = al_create_display(WIDTH, HEIGHT);			//create our display object

	if(!display)										//test display object
		return -1;

	//==============================================
	//ADDON INSTALL
	//==============================================
	al_install_keyboard();
	al_init_image_addon();
	al_init_font_addon();
	al_init_ttf_addon();
	al_init_primitives_addon();

    // FONT DEL PROGRAMA.
	ALLEGRO_FONT *font = al_load_ttf_font("Sarpanch-SemiBold.ttf",30,0 );

    // VARIABLES DEL JUEGO ========================
    bg = al_load_bitmap("img/sp1.jpg");

    SpaceShip nave_jugador;
    Enemy enemies1[10];
    Enemy enemies2[10];
    Enemy enemies3[10];
    Enemy enemies4[10];
    Enemy jefe1[10];
    Bullet bullets[5];


    char vidas_char[2];


    // INICIALIZAR OBJETOS====================
    InitShip(nave_jugador);
    InitBullet(bullets, NUM_BULLETS);
    InitEnemies(enemies1,ENM1,10,0,220,WIDTH/2);
    InitEnemies(enemies2,ENM2,8,50,180,WIDTH/2+100);
    InitEnemies(enemies3,ENM3,6,100,140,WIDTH);
    InitEnemies(enemies4,ENM4,4,150,100,(WIDTH/2)+100);
    InitEnemies(jefe1,JEFE,2,200,60);
    //DrawEnemies(enemies,NUM_ENEMIES);

	//==============================================
	//TIMER INIT AND STARTUP
	//==============================================
	event_queue = al_create_event_queue();
	timer = al_create_timer(1.0 / 60);

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

	al_start_timer(timer);

    //AnimacionEntrada(enemies,NUM_ENEMIES);
    printf("ya");
    int animacion=1;
    int movimientos=0;
	while(!done){

		ALLEGRO_EVENT ev;
		al_wait_for_event(event_queue, &ev);

        // INFORMACION DEL JUEGO Y BG
        // DrawWindowStatus();
		al_draw_bitmap(bg, 0, 0, 0);
        al_draw_bitmap(nave_jugador.image, 5,440,0);
        al_draw_text(font, al_map_rgb(255,255,255), 40,430, 0, "X");
        sprintf(vidas_char,"%d",vidas);
        al_draw_text(font, al_map_rgb(255,255,255), 60,430, 0, vidas_char);
        al_draw_text(font, al_map_rgb(255,255,255), WIDTH/2 - 30, 0,ALLEGRO_ALIGN_CENTRE, "Score");
        char vartext[10];
        sprintf(vartext,"%d",score);
        al_draw_text(font, al_map_rgb(255,255,255), WIDTH/2 + 40, 0, 0, vartext);


		//==============================================
		//INPUT
		//==============================================
        if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
		{
			done = true;
		}
		else if(ev.type == ALLEGRO_EVENT_KEY_DOWN){
			switch(ev.keyboard.keycode){
			case ALLEGRO_KEY_ESCAPE:
				done = true;
				break;
			case ALLEGRO_KEY_LEFT:
				keys[LEFT] = true;
				break;
			case ALLEGRO_KEY_RIGHT:
				keys[RIGHT] = true;
				break;
			case ALLEGRO_KEY_SPACE:
				keys[SPACE] = true;
				FireBullet(bullets, NUM_BULLETS, nave_jugador);
				break;
			}
		}
		else if(ev.type == ALLEGRO_EVENT_KEY_UP)
        {
			switch(ev.keyboard.keycode)
			{
			case ALLEGRO_KEY_ESCAPE:
				done = true;
				break;
			case ALLEGRO_KEY_LEFT:
				keys[LEFT] = false;
				break;
			case ALLEGRO_KEY_RIGHT:
				keys[RIGHT] = false;
				break;
			case ALLEGRO_KEY_SPACE:
				keys[SPACE] = false;
				break;
			}
		}


		//==============================================
		//GAME UPDATE
		//==============================================
		else if(ev.type == ALLEGRO_EVENT_TIMER){
			render = true;

			if(keys[LEFT])
				MoveShipLeft(nave_jugador);
			else if(keys[RIGHT])
				MoveShipRight(nave_jugador);

            UpdateBullet(bullets, NUM_BULLETS);

            CollideBullet(bullets,NUM_BULLETS,enemies1,NUM_ENEMIES);
            CollideBullet(bullets,NUM_BULLETS,enemies2,8);
            CollideBullet(bullets,NUM_BULLETS,enemies3,6);
            CollideBullet(bullets,NUM_BULLETS,enemies4,4);
            CollideBullet(bullets,NUM_BULLETS,jefe1,2);
		}

		//==============================================
		//RENDER
		//==============================================
		if(render && al_is_event_queue_empty(event_queue))
		{
			if (animacion==1){
                printf("si primero");
                movEnemies(enemies1,10,1);
                movEnemies(enemies2, 8,1);
                movEnemies(enemies3,6,1);
                movEnemies(enemies4,4,1);
                movEnemies(jefe1,2,1);
                animacion=0;
                movimientos=1;
			}


			render = false;

            // Dibujar nave
			al_draw_bitmap(nave_jugador.image, nave_jugador.x - nave_jugador.w / 2, nave_jugador.y - nave_jugador.h / 2, 0);
			// Dibujar Balas
			DrawBullet(bullets, NUM_BULLETS);

            // Dibuja los enemigos.
            DrawEnemies(enemies1,10);
            DrawEnemies(enemies2,8);
            DrawEnemies(enemies3,6);
            DrawEnemies(enemies4,4);
            DrawEnemies(jefe1,2);

			al_flip_display();
			al_clear_to_color(al_map_rgb(0,0,0));
			if (movimientos){
                movimientos=0;
                movEnemies(enemies1,10,2);
                movEnemies(enemies2,8,3);
			}
		}

	}


    for (int i =0;i<10;i++)

    al_destroy_bitmap(enemies1[i].image);

	al_destroy_event_queue(event_queue);
	al_destroy_timer(timer);
	al_destroy_display(display);						//destroy our display object

	return 0;
}
コード例 #28
0
ファイル: ex_multisample.c プロジェクト: gitustc/d2imdev
int main(void)
{
   ALLEGRO_DISPLAY *display, *ms_display;
   ALLEGRO_EVENT_QUEUE *queue;
   ALLEGRO_TIMER *timer;
   ALLEGRO_BITMAP *memory;
   char title[1024];
   bool quit = false;
   bool redraw = true;
   int wx, wy;

   if (!al_init()) {
      abort_example("Couldn't initialise Allegro.\n");
   }
   al_init_primitives_addon();

   al_install_keyboard();

   al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP);
   memory = create_bitmap();

   /* Create the normal display. */
   al_set_new_display_option(ALLEGRO_SAMPLE_BUFFERS, 0, ALLEGRO_REQUIRE);
   al_set_new_display_option(ALLEGRO_SAMPLES, 0, ALLEGRO_SUGGEST);
   display = al_create_display(300, 450);
   if (!display) {
      abort_example("Error creating display\n");
   }
   al_set_window_title(display, "Normal");

   /* Create bitmaps for the normal display. */
   al_set_new_bitmap_flags(ALLEGRO_MIN_LINEAR | ALLEGRO_MAG_LINEAR);
   bitmap_filter = al_clone_bitmap(memory);
   al_set_new_bitmap_flags(0);
   bitmap_normal = al_clone_bitmap(memory);

   font = al_create_builtin_font();

   al_get_window_position(display, &wx, &wy);
   if (wx < 160)
      wx = 160;

   /* Create the multi-sampling display. */
   al_set_new_display_option(ALLEGRO_SAMPLE_BUFFERS, 1, ALLEGRO_REQUIRE);
   al_set_new_display_option(ALLEGRO_SAMPLES, 4, ALLEGRO_SUGGEST);
   ms_display = al_create_display(300, 450);
   if (!ms_display) {
      abort_example("Multisampling not available.\n");
   }
   sprintf(title, "Multisampling (%dx)", al_get_display_option(
      ms_display, ALLEGRO_SAMPLES));
   al_set_window_title(ms_display, title);

   /* Create bitmaps for the multi-sampling display. */
   al_set_new_bitmap_flags(ALLEGRO_MIN_LINEAR | ALLEGRO_MAG_LINEAR);
   bitmap_filter_ms = al_clone_bitmap(memory);
   al_set_new_bitmap_flags(0);
   bitmap_normal_ms = al_clone_bitmap(memory);

   font_ms = al_create_builtin_font();

   /* Move the windows next to each other, because some window manager
    * would put them on top of each other otherwise.
    */
   al_set_window_position(display, wx - 160, wy);
   al_set_window_position(ms_display, wx + 160, wy);

   timer = al_create_timer(1.0 / 30.0);

   queue = al_create_event_queue();
   al_register_event_source(queue, al_get_keyboard_event_source());
   al_register_event_source(queue, al_get_display_event_source(display));
   al_register_event_source(queue, al_get_display_event_source(ms_display));
   al_register_event_source(queue, al_get_timer_event_source(timer));

   al_start_timer(timer);
   while (!quit) {
      ALLEGRO_EVENT event;

      /* Check for ESC key or close button event and quit in either case. */
      al_wait_for_event(queue, &event);
      switch (event.type) {
         case ALLEGRO_EVENT_DISPLAY_CLOSE:
            quit = true;
            break;

         case ALLEGRO_EVENT_KEY_DOWN:
            if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE)
               quit = true;
            break;

         case ALLEGRO_EVENT_TIMER:
            bitmap_move();
            redraw = true;
            break;
      }

      if (redraw && al_is_event_queue_empty(queue)) {
         /* Draw the multi-sampled version into the first window. */
         al_set_target_backbuffer(ms_display);

         al_clear_to_color(al_map_rgb_f(1, 1, 1));

         draw(bitmap_filter_ms, 0, "filtered, multi-sample");
         draw(bitmap_normal_ms, 250, "no filter, multi-sample");

         al_flip_display();

         /* Draw the normal version into the second window. */
         al_set_target_backbuffer(display);

         al_clear_to_color(al_map_rgb_f(1, 1, 1));

         draw(bitmap_filter, 0, "filtered");
         draw(bitmap_normal, 250, "no filter");

         al_flip_display();

         redraw = false;
      }
   }

   return 0;
}
コード例 #29
0
ファイル: prueba.cpp プロジェクト: JacsonMurillo/programs-c
int main(int argc, char **argv)
{
   ALLEGRO_DISPLAY *display = NULL;
   ALLEGRO_EVENT_QUEUE *event_queue = NULL;
   ALLEGRO_TIMER *timer = NULL;
   ALLEGRO_BITMAP *bouncer = NULL;
   float bouncer_x = SCREEN_W / 2.0 - BOUNCER_SIZE / 2.0;
   float bouncer_y = SCREEN_H / 2.0 - BOUNCER_SIZE / 2.0;
   bool redraw = true;
 
   if(!al_init()) {
         fprintf(stderr, "failed to initialize allegro!\n");
         return -1;
      }
 
   if(!al_install_mouse()) {
         fprintf(stderr, "failed to initialize the mouse!\n");
         return -1;
      }
 
   timer = al_create_timer(1.0 / FPS);
   if(!timer) {
         fprintf(stderr, "failed to create timer!\n");
         return -1;
      }
 
   display = al_create_display(SCREEN_W, SCREEN_H);
   if(!display) {
         fprintf(stderr, "failed to create display!\n");
         al_destroy_timer(timer);
         return -1;
      }
 
   bouncer = al_create_bitmap(BOUNCER_SIZE, BOUNCER_SIZE);
   if(!bouncer) {
         fprintf(stderr, "failed to create bouncer bitmap!\n");
         al_destroy_display(display);
         al_destroy_timer(timer);
         return -1;
      }
 
   al_set_target_bitmap(bouncer);
 
   al_clear_to_color(al_map_rgb(255, 0, 255));
 
   al_set_target_bitmap(al_get_backbuffer(display));
 
   event_queue = al_create_event_queue();
   if(!event_queue) {
         fprintf(stderr, "failed to create event_queue!\n");
         al_destroy_bitmap(bouncer);
         al_destroy_display(display);
         al_destroy_timer(timer);
         return -1;
      }
 
   al_register_event_source(event_queue, al_get_display_event_source(display));
 
   al_register_event_source(event_queue, al_get_timer_event_source(timer));
 
   al_register_event_source(event_queue, al_get_mouse_event_source());
 
   al_clear_to_color(al_map_rgb(0,0,0));
 
   al_flip_display();
 
   al_start_timer(timer);
 
   while(1)
   {
         ALLEGRO_EVENT ev;
         al_wait_for_event(event_queue, &ev);
    
         if(ev.type == ALLEGRO_EVENT_TIMER) {
                  redraw = true;
               }
         else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
                  break;
               }
         else if(ev.type == ALLEGRO_EVENT_MOUSE_AXES ||
                               ev.type == ALLEGRO_EVENT_MOUSE_ENTER_DISPLAY) {
          
                  bouncer_x = ev.mouse.x;
                  bouncer_y = ev.mouse.y;
               }
         else if(ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP) {
                   break;
               }
    
         if(redraw && al_is_event_queue_empty(event_queue)) {
                  redraw = false;
          
                  al_clear_to_color(al_map_rgb(0,0,0));
          
                  al_draw_bitmap(bouncer, bouncer_x, bouncer_y, 0);
          
                  al_flip_display();
               }
      }
 
   al_destroy_bitmap(bouncer);
   al_destroy_timer(timer);
   al_destroy_display(display);
   al_destroy_event_queue(event_queue);
 
   return 0;
}
コード例 #30
0
ファイル: main.cpp プロジェクト: anagorko/zpk2015
int main(int argc, char **argv)
{
	InitAllegro();

	ALLEGRO_KEYBOARD_STATE klawiatura;
	ALLEGRO_MOUSE_STATE mysz;
	ALLEGRO_EVENT_QUEUE* event_queue = al_create_event_queue();
	ALLEGRO_EVENT_QUEUE* key_queue = al_create_event_queue();
	ALLEGRO_DISPLAY* okno = al_create_display(WINDOW_WIDTH, WINDOW_HEIGHT);
	ALLEGRO_FONT* defaultFont = al_create_builtin_font();
	ALLEGRO_TIMER* timer = al_create_timer(1.0 / 60.0);

	al_register_event_source(key_queue, al_get_display_event_source(okno));
	al_register_event_source(event_queue, al_get_display_event_source(okno));
	al_register_event_source(key_queue, al_get_keyboard_event_source());
	al_register_event_source(event_queue, al_get_timer_event_source(timer));

	al_set_window_title(okno, "Fraktale");
	al_set_target_bitmap(al_get_backbuffer(okno));
	
	Menu* menu = new Menu(WINDOW_WIDTH, WINDOW_HEIGHT);
	Mandelbrot* mandelbrot = new Mandelbrot(WINDOW_WIDTH, WINDOW_HEIGHT, defaultFont);
	Julia* julia = new Julia(WINDOW_WIDTH, WINDOW_HEIGHT, defaultFont);
	Window* window = new Window(menu, mandelbrot, julia);
	menu->SetWindow(window);
	mandelbrot->SetWindow(window);
	julia->SetWindow(window);

	const ALLEGRO_COLOR backgroundColor = al_map_rgb(255, 255, 255);
	const ALLEGRO_COLOR frameColor = al_map_rgb(255, 255, 255);
	const int frameThickness = 2;

	ALLEGRO_USTR* str = al_ustr_new("");
	int pos = (int)al_ustr_size(str);

	ALLEGRO_EVENT ev;

	double blokadaKlikniecia = al_get_time();
	
	int poczX = -1, poczY = -1, poprzedniStan = window->stanOkna;
	bool petla = true, klikniecieMyszy = false, klawiszWcisniety = false, wpisywanieIteracji = false;

	double screenRatio = static_cast<double>(WINDOW_HEIGHT) / static_cast<double>(WINDOW_WIDTH);

	while (petla)
	{
		if (poprzedniStan != window->stanOkna)
		{
			blokadaKlikniecia = al_get_time();
		}

		poprzedniStan = window->stanOkna;

		al_get_next_event(event_queue, &ev);
		al_get_mouse_state(&mysz);

		int mx = mysz.x;
		int my = mysz.y;

		bool koniecKlikniecia = false;

		if (mysz.buttons & 1 && klikniecieMyszy == false && al_get_time() > blokadaKlikniecia + 0.3)
		{
			klikniecieMyszy = true;

			if (window->CzyFraktal())
			{
				poczX = mx;
				poczY = my;
			}
		}
		else if (!(mysz.buttons & 1) && klikniecieMyszy == true && al_get_time() > blokadaKlikniecia + 0.3)
		{
			klikniecieMyszy = false;

			int pp = window->stanOkna;

			int respond = window->Click(mx, my);
			if (respond == Responds_t::RESPOND_CLOSE_WINDOW)
				petla = false;

			if (window->CzyFraktal() && (pp == WINDOWSTATE_MANDELBROT || pp == WINDOWSTATE_JULIA))
			{
				koniecKlikniecia = true;
			}

			if (pp == WINDOWSTATE_MENU && window->CzyFraktal())
			{
				window->ZaladujFraktal();
			}
		}

		if (koniecKlikniecia)
		{
			if (window->CzyFraktal())
			{
				Fraktal* fraktal = window->AktualnyFraktal();
				fraktal->Powieksz(poczX, mx, poczY, SkalujY(poczY, screenRatio, poczX, mx));
			}
			poczX = -1, poczY = -1;
		}

		al_get_next_event(key_queue, &ev);

		if (ev.type == ALLEGRO_EVENT_KEY_DOWN && klawiszWcisniety == false && window->CzyFraktal())
		{
			int kod = ev.keyboard.keycode;
			klawiszWcisniety = true;

			if (kod == 9)
			{
				wpisywanieIteracji = true;
			}
			else if (kod == 10)
			{
				Fraktal* fraktal = window->AktualnyFraktal();
				fraktal->Resetuj();
			}
			else if (kod >= 27 && kod <= 36 && wpisywanieIteracji)
			{
				pos += al_ustr_append_chr(str, kod + 21);
			}
			else if (kod == ALLEGRO_KEY_ENTER)
			{
				if (wpisywanieIteracji == true)
					wpisywanieIteracji = false;
				unsigned char* tmp = str->data;
				int t = atoi((const char*)tmp);
				window->SetIteracje(t);
			}
			else if (kod == ALLEGRO_KEY_BACKSPACE)
			{
				if (al_ustr_prev(str, &pos))
					al_ustr_truncate(str, pos);
			}
			else if (kod == ALLEGRO_KEY_ESCAPE)
			{
				window->stanOkna = WINDOWSTATE_MENU;
			}
		}
		else if (ev.type == ALLEGRO_EVENT_KEY_UP)
		{
			klawiszWcisniety = false;
		}

		al_clear_to_color(backgroundColor);

		if (wpisywanieIteracji)
			window->Draw(str);
		else
			window->Draw(NULL);

		if(poczX != -1)
			al_draw_rectangle(poczX, poczY, mx, SkalujY(poczY, screenRatio, poczX, mx), frameColor, frameThickness);
		al_flip_display();
	}
	al_destroy_display(okno);
	return 0;
}